diff --git a/crates/ty_ide/src/goto.rs b/crates/ty_ide/src/goto.rs index 1c4aa68a64..196e11da96 100644 --- a/crates/ty_ide/src/goto.rs +++ b/crates/ty_ide/src/goto.rs @@ -423,15 +423,15 @@ mod tests { assert_snapshot!(test.goto_type_definition(), @r#" info[goto-type-definition]: Type definition - --> stdlib/builtins.pyi:1120:7 - | - 1118 | def __getitem__(self, key: int, /) -> str | int | None: ... - 1119 | - 1120 | class str(Sequence[str]): - | ^^^ - 1121 | """ - 1122 | str(object='') -> str - | + --> stdlib/builtins.pyi:892:7 + | + 890 | def __getitem__(self, key: int, /) -> str | int | None: ... + 891 | + 892 | class str(Sequence[str]): + | ^^^ + 893 | """str(object='') -> str + 894 | str(bytes_or_buffer[, encoding[, errors]]) -> str + | info: Source --> main.py:4:13 | @@ -452,15 +452,15 @@ mod tests { assert_snapshot!(test.goto_type_definition(), @r#" info[goto-type-definition]: Type definition - --> stdlib/builtins.pyi:1120:7 - | - 1118 | def __getitem__(self, key: int, /) -> str | int | None: ... - 1119 | - 1120 | class str(Sequence[str]): - | ^^^ - 1121 | """ - 1122 | str(object='') -> str - | + --> stdlib/builtins.pyi:892:7 + | + 890 | def __getitem__(self, key: int, /) -> str | int | None: ... + 891 | + 892 | class str(Sequence[str]): + | ^^^ + 893 | """str(object='') -> str + 894 | str(bytes_or_buffer[, encoding[, errors]]) -> str + | info: Source --> main.py:2:22 | @@ -568,15 +568,15 @@ mod tests { assert_snapshot!(test.goto_type_definition(), @r#" info[goto-type-definition]: Type definition - --> stdlib/builtins.pyi:1120:7 - | - 1118 | def __getitem__(self, key: int, /) -> str | int | None: ... - 1119 | - 1120 | class str(Sequence[str]): - | ^^^ - 1121 | """ - 1122 | str(object='') -> str - | + --> stdlib/builtins.pyi:892:7 + | + 890 | def __getitem__(self, key: int, /) -> str | int | None: ... + 891 | + 892 | class str(Sequence[str]): + | ^^^ + 893 | """str(object='') -> str + 894 | str(bytes_or_buffer[, encoding[, errors]]) -> str + | info: Source --> main.py:4:18 | @@ -603,14 +603,14 @@ mod tests { // is an int. Navigating to `str` would match pyright's behavior. assert_snapshot!(test.goto_type_definition(), @r#" info[goto-type-definition]: Type definition - --> stdlib/builtins.pyi:365:7 + --> stdlib/builtins.pyi:338:7 | - 363 | _LiteralInteger = _PositiveInteger | _NegativeInteger | Literal[0] # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed - 364 | - 365 | class int: + 336 | _LiteralInteger = _PositiveInteger | _NegativeInteger | Literal[0] # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed + 337 | + 338 | class int: | ^^^ - 366 | """ - 367 | int([x]) -> integer + 339 | """int([x]) -> integer + 340 | int(x, base=10) -> integer | info: Source --> main.py:4:18 @@ -637,14 +637,14 @@ f(**kwargs) assert_snapshot!(test.goto_type_definition(), @r#" info[goto-type-definition]: Type definition - --> stdlib/builtins.pyi:3458:7 + --> stdlib/builtins.pyi:2892:7 | - 3456 | """ - 3457 | - 3458 | class dict(MutableMapping[_KT, _VT]): + 2890 | """See PEP 585""" + 2891 | + 2892 | class dict(MutableMapping[_KT, _VT]): | ^^^^ - 3459 | """ - 3460 | dict() -> new empty dictionary + 2893 | """dict() -> new empty dictionary + 2894 | dict(mapping) -> new dictionary initialized from a mapping object's | info: Source --> main.py:6:5 @@ -668,15 +668,15 @@ f(**kwargs) assert_snapshot!(test.goto_type_definition(), @r#" info[goto-type-definition]: Type definition - --> stdlib/builtins.pyi:1120:7 - | - 1118 | def __getitem__(self, key: int, /) -> str | int | None: ... - 1119 | - 1120 | class str(Sequence[str]): - | ^^^ - 1121 | """ - 1122 | str(object='') -> str - | + --> stdlib/builtins.pyi:892:7 + | + 890 | def __getitem__(self, key: int, /) -> str | int | None: ... + 891 | + 892 | class str(Sequence[str]): + | ^^^ + 893 | """str(object='') -> str + 894 | str(bytes_or_buffer[, encoding[, errors]]) -> str + | info: Source --> main.py:3:17 | @@ -761,15 +761,15 @@ f(**kwargs) assert_snapshot!(test.goto_type_definition(), @r#" info[goto-type-definition]: Type definition - --> stdlib/builtins.pyi:1120:7 - | - 1118 | def __getitem__(self, key: int, /) -> str | int | None: ... - 1119 | - 1120 | class str(Sequence[str]): - | ^^^ - 1121 | """ - 1122 | str(object='') -> str - | + --> stdlib/builtins.pyi:892:7 + | + 890 | def __getitem__(self, key: int, /) -> str | int | None: ... + 891 | + 892 | class str(Sequence[str]): + | ^^^ + 893 | """str(object='') -> str + 894 | str(bytes_or_buffer[, encoding[, errors]]) -> str + | info: Source --> main.py:4:27 | @@ -792,15 +792,14 @@ f(**kwargs) assert_snapshot!(test.goto_type_definition(), @r#" info[goto-type-definition]: Type definition - --> stdlib/types.pyi:1073:11 - | - 1071 | if sys.version_info >= (3, 10): - 1072 | @final - 1073 | class NoneType: - | ^^^^^^^^ - 1074 | """ - 1075 | The type of the None singleton. - | + --> stdlib/types.pyi:922:11 + | + 920 | if sys.version_info >= (3, 10): + 921 | @final + 922 | class NoneType: + | ^^^^^^^^ + 923 | """The type of the None singleton.""" + | info: Source --> main.py:3:17 | @@ -810,15 +809,15 @@ f(**kwargs) | info[goto-type-definition]: Type definition - --> stdlib/builtins.pyi:1120:7 - | - 1118 | def __getitem__(self, key: int, /) -> str | int | None: ... - 1119 | - 1120 | class str(Sequence[str]): - | ^^^ - 1121 | """ - 1122 | str(object='') -> str - | + --> stdlib/builtins.pyi:892:7 + | + 890 | def __getitem__(self, key: int, /) -> str | int | None: ... + 891 | + 892 | class str(Sequence[str]): + | ^^^ + 893 | """str(object='') -> str + 894 | str(bytes_or_buffer[, encoding[, errors]]) -> str + | info: Source --> main.py:3:17 | diff --git a/crates/ty_python_semantic/resources/mdtest/snapshots/invalid_argument_typ…_-_Invalid_argument_typ…_-_Test_calling_a_funct…_(3b18271a821a59b).snap b/crates/ty_python_semantic/resources/mdtest/snapshots/invalid_argument_typ…_-_Invalid_argument_typ…_-_Test_calling_a_funct…_(3b18271a821a59b).snap index 943d1d0065..389e8e13eb 100644 --- a/crates/ty_python_semantic/resources/mdtest/snapshots/invalid_argument_typ…_-_Invalid_argument_typ…_-_Test_calling_a_funct…_(3b18271a821a59b).snap +++ b/crates/ty_python_semantic/resources/mdtest/snapshots/invalid_argument_typ…_-_Invalid_argument_typ…_-_Test_calling_a_funct…_(3b18271a821a59b).snap @@ -29,16 +29,16 @@ error[invalid-argument-type]: Argument to function `loads` is incorrect | ^ Expected `str | bytes | bytearray`, found `Literal[5]` | info: Function defined here - --> stdlib/json/__init__.pyi:221:5 + --> stdlib/json/__init__.pyi:219:5 | -219 | """ -220 | -221 | def loads( +217 | """ +218 | +219 | def loads( | ^^^^^ -222 | s: str | bytes | bytearray, +220 | s: str | bytes | bytearray, | -------------------------- Parameter declared here -223 | *, -224 | cls: type[JSONDecoder] | None = None, +221 | *, +222 | cls: type[JSONDecoder] | None = None, | info: rule `invalid-argument-type` is enabled by default diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/__future__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/__future__.pyi index 76ecfca2c3..ce4442d925 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/__future__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/__future__.pyi @@ -55,15 +55,13 @@ _VersionInfo: TypeAlias = tuple[int, int, int, str, int] class _Feature: def __init__(self, optionalRelease: _VersionInfo, mandatoryRelease: _VersionInfo | None, compiler_flag: int) -> None: ... def getOptionalRelease(self) -> _VersionInfo: - """ - Return first release in which this feature was recognized. + """Return first release in which this feature was recognized. This is a 5-tuple, of the same form as sys.version_info. """ def getMandatoryRelease(self) -> _VersionInfo | None: - """ - Return release in which this feature will become mandatory. + """Return release in which this feature will become mandatory. This is a 5-tuple, of the same form as sys.version_info, or, if the feature was dropped, or the release date is undetermined, is None. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_asyncio.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_asyncio.pyi index 3a3721dad2..ef0f8e0d7f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_asyncio.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_asyncio.pyi @@ -15,8 +15,7 @@ _T_co = TypeVar("_T_co", covariant=True) _TaskYieldType: TypeAlias = Future[object] | None class Future(Awaitable[_T]): - """ - This class is *almost* compatible with concurrent.futures.Future. + """This class is *almost* compatible with concurrent.futures.Future. Differences: @@ -41,20 +40,15 @@ class Future(Awaitable[_T]): _asyncio_future_blocking: bool # is a part of duck-typing contract for `Future` def __init__(self, *, loop: AbstractEventLoop | None = ...) -> None: ... def __del__(self) -> None: - """ - Called when the instance is about to be destroyed. - """ + """Called when the instance is about to be destroyed.""" def get_loop(self) -> AbstractEventLoop: - """ - Return the event loop the Future is bound to. - """ + """Return the event loop the Future is bound to.""" @property def _callbacks(self) -> list[tuple[Callable[[Self], Any], Context]]: ... def add_done_callback(self, fn: Callable[[Self], object], /, *, context: Context | None = None) -> None: - """ - Add a callback to be run when the future becomes done. + """Add a callback to be run when the future becomes done. The callback is called with a single argument - the future object. If the future is already done when this is called, the callback is @@ -62,8 +56,7 @@ class Future(Awaitable[_T]): """ def cancel(self, msg: Any | None = None) -> bool: - """ - Cancel the future and schedule callbacks. + """Cancel the future and schedule callbacks. If the future is already done or cancelled, return False. Otherwise, change the future's state to cancelled, schedule the callbacks and @@ -71,21 +64,17 @@ class Future(Awaitable[_T]): """ def cancelled(self) -> bool: - """ - Return True if the future was cancelled. - """ + """Return True if the future was cancelled.""" def done(self) -> bool: - """ - Return True if the future is done. + """Return True if the future is done. Done means either that a result / exception are available, or that the future was cancelled. """ def result(self) -> _T: - """ - Return the result this future represents. + """Return the result this future represents. If the future has been cancelled, raises CancelledError. If the future's result isn't yet available, raises InvalidStateError. If @@ -93,8 +82,7 @@ class Future(Awaitable[_T]): """ def exception(self) -> BaseException | None: - """ - Return the exception that was set on this future. + """Return the exception that was set on this future. The exception (or None if no exception was set) is returned only if the future is done. If the future has been cancelled, raises @@ -103,44 +91,35 @@ class Future(Awaitable[_T]): """ def remove_done_callback(self, fn: Callable[[Self], object], /) -> int: - """ - Remove all instances of a callback from the "call when done" list. + """Remove all instances of a callback from the "call when done" list. Returns the number of callbacks removed. """ def set_result(self, result: _T, /) -> None: - """ - Mark the future done and set its result. + """Mark the future done and set its result. If the future is already done when this method is called, raises InvalidStateError. """ def set_exception(self, exception: type | BaseException, /) -> None: - """ - Mark the future done and set an exception. + """Mark the future done and set an exception. If the future is already done when this method is called, raises InvalidStateError. """ def __iter__(self) -> Generator[Any, None, _T]: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __await__(self) -> Generator[Any, None, _T]: - """ - Return an iterator to be used in await expression. - """ + """Return an iterator to be used in await expression.""" @property def _loop(self) -> AbstractEventLoop: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" if sys.version_info >= (3, 12): _TaskCompatibleCoro: TypeAlias = Coroutine[Any, Any, _T_co] @@ -152,9 +131,7 @@ else: # since the only reason why `asyncio.Future` is invariant is the `set_result()` method, # and `asyncio.Task.set_result()` always raises. class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportInvalidTypeArguments] - """ - A coroutine wrapped in a Future. - """ + """A coroutine wrapped in a Future.""" if sys.version_info >= (3, 12): def __init__( @@ -191,8 +168,7 @@ class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportIn def get_context(self) -> Context: ... def get_stack(self, *, limit: int | None = None) -> list[FrameType]: - """ - Return the list of stack frames for this task's coroutine. + """Return the list of stack frames for this task's coroutine. If the coroutine is not done, this returns the stack where it is suspended. If the coroutine has completed successfully or was @@ -214,8 +190,7 @@ class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportIn """ def print_stack(self, *, limit: int | None = None, file: TextIO | None = None) -> None: - """ - Print the stack or traceback for this task's coroutine. + """Print the stack or traceback for this task's coroutine. This produces output similar to that of the traceback module, for the frames retrieved by get_stack(). The limit argument @@ -225,16 +200,14 @@ class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportIn """ if sys.version_info >= (3, 11): def cancelling(self) -> int: - """ - Return the count of the task's cancellation requests. + """Return the count of the task's cancellation requests. This count is incremented when .cancel() is called and may be decremented using .uncancel(). """ def uncancel(self) -> int: - """ - Decrement the task's count of cancellation requests. + """Decrement the task's count of cancellation requests. This should be used by tasks that catch CancelledError and wish to continue indefinitely until they are cancelled again. @@ -243,13 +216,10 @@ class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportIn """ def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" def get_event_loop() -> AbstractEventLoop: - """ - Return an asyncio event loop. + """Return an asyncio event loop. When called from a coroutine or a callback (e.g. scheduled with call_soon or similar API), this function will always return the @@ -260,45 +230,39 @@ def get_event_loop() -> AbstractEventLoop: """ def get_running_loop() -> AbstractEventLoop: - """ - Return the running event loop. Raise a RuntimeError if there is none. + """Return the running event loop. Raise a RuntimeError if there is none. This function is thread-specific. """ def _set_running_loop(loop: AbstractEventLoop | None, /) -> None: - """ - Set the running event loop. + """Set the running event loop. This is a low-level function intended to be used by event loops. This function is thread-specific. """ def _get_running_loop() -> AbstractEventLoop: - """ - Return the running event loop or None. + """Return the running event loop or None. This is a low-level function intended to be used by event loops. This function is thread-specific. """ def _register_task(task: Task[Any]) -> None: - """ - Register a new task in asyncio as executed by loop. + """Register a new task in asyncio as executed by loop. Returns None. """ def _unregister_task(task: Task[Any]) -> None: - """ - Unregister a task. + """Unregister a task. Returns None. """ def _enter_task(loop: AbstractEventLoop, task: Task[Any]) -> None: - """ - Enter into task execution or resume suspended task. + """Enter into task execution or resume suspended task. Task belongs to loop. @@ -306,8 +270,7 @@ def _enter_task(loop: AbstractEventLoop, task: Task[Any]) -> None: """ def _leave_task(loop: AbstractEventLoop, task: Task[Any]) -> None: - """ - Leave task execution or suspend a task. + """Leave task execution or suspend a task. Task belongs to loop. @@ -316,18 +279,12 @@ def _leave_task(loop: AbstractEventLoop, task: Task[Any]) -> None: if sys.version_info >= (3, 12): def current_task(loop: AbstractEventLoop | None = None) -> Task[Any] | None: - """ - Return a currently executed task. - """ + """Return a currently executed task.""" if sys.version_info >= (3, 14): def future_discard_from_awaited_by(future: Future[Any], waiter: Future[Any], /) -> None: ... def future_add_to_awaited_by(future: Future[Any], waiter: Future[Any], /) -> None: - """ - Record that `fut` is awaited on by `waiter`. - """ + """Record that `fut` is awaited on by `waiter`.""" def all_tasks(loop: AbstractEventLoop | None = None) -> set[Task[Any]]: - """ - Return a set of all tasks for the loop. - """ + """Return a set of all tasks for the loop.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_bisect.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_bisect.pyi index c6ff3cdc6f..30fd0f4756 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_bisect.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_bisect.pyi @@ -24,8 +24,7 @@ if sys.version_info >= (3, 10): *, key: None = None, ) -> int: - """ - Return the index where to insert item x in list a, assuming a is sorted. + """Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e < x, and all e in a[i:] have e >= x. So if x already appears in the list, a.insert(i, x) will @@ -55,8 +54,7 @@ if sys.version_info >= (3, 10): *, key: None = None, ) -> int: - """ - Return the index where to insert item x in list a, assuming a is sorted. + """Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e <= x, and all e in a[i:] have e > x. So if x already appears in the list, a.insert(i, x) will @@ -86,8 +84,7 @@ if sys.version_info >= (3, 10): *, key: None = None, ) -> None: - """ - Insert item x in list a, and keep it sorted assuming a is sorted. + """Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the left of the leftmost x. @@ -110,8 +107,7 @@ if sys.version_info >= (3, 10): *, key: None = None, ) -> None: - """ - Insert item x in list a, and keep it sorted assuming a is sorted. + """Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the right of the rightmost x. @@ -130,8 +126,7 @@ else: def bisect_left( a: SupportsLenAndGetItem[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None ) -> int: - """ - Return the index where to insert item x in list a, assuming a is sorted. + """Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e < x, and all e in a[i:] have e >= x. So if x already appears in the list, i points just @@ -144,8 +139,7 @@ else: def bisect_right( a: SupportsLenAndGetItem[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None ) -> int: - """ - Return the index where to insert item x in list a, assuming a is sorted. + """Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e <= x, and all e in a[i:] have e > x. So if x already appears in the list, i points just @@ -158,8 +152,7 @@ else: def insort_left( a: MutableSequence[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None ) -> None: - """ - Insert item x in list a, and keep it sorted assuming a is sorted. + """Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the left of the leftmost x. @@ -170,8 +163,7 @@ else: def insort_right( a: MutableSequence[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None ) -> None: - """ - Insert item x in list a, and keep it sorted assuming a is sorted. + """Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the right of the rightmost x. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_blake2.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_blake2.pyi index feea281006..448ad15f16 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_blake2.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_blake2.pyi @@ -17,9 +17,7 @@ BLAKE2S_SALT_SIZE: int = 8 @final class blake2b: - """ - Return a new BLAKE2b hash object. - """ + """Return a new BLAKE2b hash object.""" MAX_DIGEST_SIZE: ClassVar[int] = 64 MAX_KEY_SIZE: ClassVar[int] = 64 @@ -47,30 +45,20 @@ class blake2b: usedforsecurity: bool = True, ) -> Self: ... def copy(self) -> Self: - """ - Return a copy of the hash object. - """ + """Return a copy of the hash object.""" def digest(self) -> bytes: - """ - Return the digest value as a bytes object. - """ + """Return the digest value as a bytes object.""" def hexdigest(self) -> str: - """ - Return the digest value as a string of hexadecimal digits. - """ + """Return the digest value as a string of hexadecimal digits.""" def update(self, data: ReadableBuffer, /) -> None: - """ - Update this hash object's state with the provided bytes-like object. - """ + """Update this hash object's state with the provided bytes-like object.""" @final class blake2s: - """ - Return a new BLAKE2s hash object. - """ + """Return a new BLAKE2s hash object.""" MAX_DIGEST_SIZE: ClassVar[int] = 32 MAX_KEY_SIZE: ClassVar[int] = 32 @@ -98,21 +86,13 @@ class blake2s: usedforsecurity: bool = True, ) -> Self: ... def copy(self) -> Self: - """ - Return a copy of the hash object. - """ + """Return a copy of the hash object.""" def digest(self) -> bytes: - """ - Return the digest value as a bytes object. - """ + """Return the digest value as a bytes object.""" def hexdigest(self) -> str: - """ - Return the digest value as a string of hexadecimal digits. - """ + """Return the digest value as a string of hexadecimal digits.""" def update(self, data: ReadableBuffer, /) -> None: - """ - Update this hash object's state with the provided bytes-like object. - """ + """Update this hash object's state with the provided bytes-like object.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_bz2.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_bz2.pyi index 1ab9bbf265..61a76f4f85 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_bz2.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_bz2.pyi @@ -5,8 +5,7 @@ from typing_extensions import Self @final class BZ2Compressor: - """ - Create a compressor object for compressing data incrementally. + """Create a compressor object for compressing data incrementally. compresslevel Compression level, as a number between 1 and 9. @@ -20,8 +19,7 @@ class BZ2Compressor: def __init__(self, compresslevel: int = 9, /) -> None: ... def compress(self, data: ReadableBuffer, /) -> bytes: - """ - Provide data to the compressor object. + """Provide data to the compressor object. Returns a chunk of compressed data if possible, or b'' otherwise. @@ -30,8 +28,7 @@ class BZ2Compressor: """ def flush(self) -> bytes: - """ - Finish the compression process. + """Finish the compression process. Returns the compressed data left in internal buffers. @@ -40,15 +37,13 @@ class BZ2Compressor: @final class BZ2Decompressor: - """ - Create a decompressor object for decompressing data incrementally. + """Create a decompressor object for decompressing data incrementally. For one-shot decompression, use the decompress() function instead. """ def decompress(self, data: ReadableBuffer, max_length: int = -1) -> bytes: - """ - Decompress *data*, returning uncompressed data as bytes. + """Decompress *data*, returning uncompressed data as bytes. If *max_length* is nonnegative, returns at most *max_length* bytes of decompressed data. If this limit is reached and further output can be @@ -66,18 +61,12 @@ class BZ2Decompressor: @property def eof(self) -> bool: - """ - True if the end-of-stream marker has been reached. - """ + """True if the end-of-stream marker has been reached.""" @property def needs_input(self) -> bool: - """ - True if more input is needed before more decompressed data can be produced. - """ + """True if more input is needed before more decompressed data can be produced.""" @property def unused_data(self) -> bytes: - """ - Data found after the end of the compressed stream. - """ + """Data found after the end of the compressed stream.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_codecs.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_codecs.pyi index d167a36bfe..7548f98b66 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_codecs.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_codecs.pyi @@ -17,8 +17,7 @@ _Handler: TypeAlias = Callable[[UnicodeError], tuple[str | bytes, int]] _SearchFunction: TypeAlias = Callable[[str], codecs.CodecInfo | None] def register(search_function: _SearchFunction, /) -> None: - """ - Register a codec search function. + """Register a codec search function. Search functions are expected to take one argument, the encoding name in all lower case letters, and either return None, or a tuple of functions @@ -27,15 +26,13 @@ def register(search_function: _SearchFunction, /) -> None: if sys.version_info >= (3, 10): def unregister(search_function: _SearchFunction, /) -> None: - """ - Unregister a codec search function and clear the registry's cache. + """Unregister a codec search function and clear the registry's cache. If the search function is not registered, do nothing. """ def register_error(errors: str, handler: _Handler, /) -> None: - """ - Register the specified error handler under the name errors. + """Register the specified error handler under the name errors. handler must be a callable object, that will be called with an exception instance containing information about the location of the encoding/decoding @@ -43,8 +40,7 @@ def register_error(errors: str, handler: _Handler, /) -> None: """ def lookup_error(name: str, /) -> _Handler: - """ - lookup_error(errors) -> handler + """lookup_error(errors) -> handler Return the error handler for the specified error handling name or raise a LookupError, if no handler exists under this name. @@ -75,8 +71,7 @@ _StrToStrEncoding: TypeAlias = Literal["rot13", "rot_13"] @overload def encode(obj: ReadableBuffer, encoding: _BytesToBytesEncoding, errors: str = "strict") -> bytes: - """ - Encodes obj using the codec registered for encoding. + """Encodes obj using the codec registered for encoding. The default encoding is 'utf-8'. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding @@ -91,8 +86,7 @@ def encode(obj: str, encoding: _StrToStrEncoding, errors: str = "strict") -> str def encode(obj: str, encoding: str = "utf-8", errors: str = "strict") -> bytes: ... @overload def decode(obj: ReadableBuffer, encoding: _BytesToBytesEncoding, errors: str = "strict") -> bytes: # type: ignore[overload-overlap] - """ - Decodes obj using the codec registered for encoding. + """Decodes obj using the codec registered for encoding. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding @@ -118,9 +112,7 @@ def decode(obj: str, encoding: Literal["hex", "hex_codec"], errors: str = "stric @overload def decode(obj: ReadableBuffer, encoding: str = "utf-8", errors: str = "strict") -> str: ... def lookup(encoding: str, /) -> codecs.CodecInfo: - """ - Looks up a codec tuple in the Python codec registry and returns a CodecInfo object. - """ + """Looks up a codec tuple in the Python codec registry and returns a CodecInfo object.""" def charmap_build(map: str, /) -> _CharMap: ... def ascii_decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_collections_abc.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_collections_abc.pyi index dedccac1c2..4bbff93bb8 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_collections_abc.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_collections_abc.pyi @@ -81,54 +81,38 @@ _VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers. class dict_keys(KeysView[_KT_co], Generic[_KT_co, _VT_co]): # undocumented def __eq__(self, value: object, /) -> bool: ... def __reversed__(self) -> Iterator[_KT_co]: - """ - Return a reverse iterator over the dict keys. - """ + """Return a reverse iterator over the dict keys.""" __hash__: ClassVar[None] # type: ignore[assignment] if sys.version_info >= (3, 13): def isdisjoint(self, other: Iterable[_KT_co], /) -> bool: - """ - Return True if the view and the given iterable have a null intersection. - """ + """Return True if the view and the given iterable have a null intersection.""" if sys.version_info >= (3, 10): @property def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: - """ - dictionary that this view refers to - """ + """dictionary that this view refers to""" @final class dict_values(ValuesView[_VT_co], Generic[_KT_co, _VT_co]): # undocumented def __reversed__(self) -> Iterator[_VT_co]: - """ - Return a reverse iterator over the dict values. - """ + """Return a reverse iterator over the dict values.""" if sys.version_info >= (3, 10): @property def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: - """ - dictionary that this view refers to - """ + """dictionary that this view refers to""" @final class dict_items(ItemsView[_KT_co, _VT_co]): # undocumented def __eq__(self, value: object, /) -> bool: ... def __reversed__(self) -> Iterator[tuple[_KT_co, _VT_co]]: - """ - Return a reverse iterator over the dict items. - """ + """Return a reverse iterator over the dict items.""" __hash__: ClassVar[None] # type: ignore[assignment] if sys.version_info >= (3, 13): def isdisjoint(self, other: Iterable[tuple[_KT_co, _VT_co]], /) -> bool: - """ - Return True if the view and the given iterable have a null intersection. - """ + """Return True if the view and the given iterable have a null intersection.""" if sys.version_info >= (3, 10): @property def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: - """ - dictionary that this view refers to - """ + """dictionary that this view refers to""" if sys.version_info >= (3, 12): @runtime_checkable diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_compression.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_compression.pyi index d99a7f59c2..090c462470 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_compression.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_compression.pyi @@ -17,14 +17,10 @@ class _Reader(Protocol): def seek(self, n: int, /) -> Any: ... class BaseStream(BufferedIOBase): - """ - Mode-checking helper functions. - """ + """Mode-checking helper functions.""" class DecompressReader(RawIOBase): - """ - Adapts the decompressor API to a RawIOBase reader API - """ + """Adapts the decompressor API to a RawIOBase reader API""" def __init__( self, diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_contextvars.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_contextvars.pyi index d301cc3141..6e70ec8dd2 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_contextvars.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_contextvars.pyi @@ -23,8 +23,7 @@ class ContextVar(Generic[_T]): def name(self) -> str: ... @overload def get(self) -> _T: - """ - Return a value for the context variable for the current context. + """Return a value for the context variable for the current context. If there is no value for the variable in the current context, the method will: * return the value of the default argument of the method, if provided; or @@ -38,8 +37,7 @@ class ContextVar(Generic[_T]): @overload def get(self, default: _D, /) -> _D | _T: ... def set(self, value: _T, /) -> Token[_T]: - """ - Call to set a new value for the context variable in the current context. + """Call to set a new value for the context variable in the current context. The required value argument is the new value for the context variable. @@ -48,17 +46,14 @@ class ContextVar(Generic[_T]): """ def reset(self, token: Token[_T], /) -> None: - """ - Reset the context variable. + """Reset the context variable. The variable is reset to the value it had before the `ContextVar.set()` that created the token was used. """ def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" @final class Token(Generic[_T]): @@ -69,21 +64,15 @@ class Token(Generic[_T]): MISSING: ClassVar[object] __hash__: ClassVar[None] # type: ignore[assignment] def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" if sys.version_info >= (3, 14): def __enter__(self) -> Self: - """ - Enter into Token context manager. - """ + """Enter into Token context manager.""" def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None ) -> None: - """ - Exit from Token context manager, restore the linked ContextVar. - """ + """Exit from Token context manager, restore the linked ContextVar.""" def copy_context() -> Context: ... @@ -94,8 +83,7 @@ class Context(Mapping[ContextVar[Any], Any]): def __init__(self) -> None: ... @overload def get(self, key: ContextVar[_T], default: None = None, /) -> _T | None: - """ - Return the value for `key` if `key` has the value in the context object. + """Return the value for `key` if `key` has the value in the context object. If `key` does not exist, return `default`. If `default` is not given, return None. @@ -107,23 +95,15 @@ class Context(Mapping[ContextVar[Any], Any]): def get(self, key: ContextVar[_T], default: _D, /) -> _T | _D: ... def run(self, callable: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> _T: ... def copy(self) -> Context: - """ - Return a shallow copy of the context object. - """ + """Return a shallow copy of the context object.""" __hash__: ClassVar[None] # type: ignore[assignment] def __getitem__(self, key: ContextVar[_T], /) -> _T: - """ - Return self[key]. - """ + """Return self[key].""" def __iter__(self) -> Iterator[ContextVar[Any]]: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" def __eq__(self, value: object, /) -> bool: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_csv.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_csv.pyi index ac921479fd..006d4694ff 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_csv.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_csv.pyi @@ -29,8 +29,7 @@ class Error(Exception): ... _DialectLike: TypeAlias = str | Dialect | csv.Dialect | type[Dialect | csv.Dialect] class Dialect: - """ - CSV dialect + """CSV dialect The Dialect type records CSV parsing and generation options. """ @@ -59,8 +58,7 @@ class Dialect: if sys.version_info >= (3, 10): # This class calls itself _csv.reader. class Reader: - """ - CSV reader + """CSV reader Reader objects are responsible for reading and parsing tabular data in CSV format. @@ -70,19 +68,14 @@ if sys.version_info >= (3, 10): def dialect(self) -> Dialect: ... line_num: int def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> list[str]: - """ - Implement next(self). - """ + """Implement next(self).""" # This class calls itself _csv.writer. class Writer: - """ - CSV writer + """CSV writer Writer objects are responsible for generating tabular data in CSV format from sequence input. @@ -92,32 +85,28 @@ if sys.version_info >= (3, 10): def dialect(self) -> Dialect: ... if sys.version_info >= (3, 13): def writerow(self, row: Iterable[Any], /) -> Any: - """ - writerow(iterable) + """writerow(iterable) Construct and write a CSV record from an iterable of fields. Non-string elements will be converted to string. """ def writerows(self, rows: Iterable[Iterable[Any]], /) -> None: - """ - writerows(iterable of iterables) + """writerows(iterable of iterables) Construct and write a series of iterables to a csv file. Non-string elements will be converted to string. """ else: def writerow(self, row: Iterable[Any]) -> Any: - """ - writerow(iterable) + """writerow(iterable) Construct and write a CSV record from an iterable of fields. Non-string elements will be converted to string. """ def writerows(self, rows: Iterable[Iterable[Any]]) -> None: - """ - writerows(iterable of iterables) + """writerows(iterable of iterables) Construct and write a series of iterables to a csv file. Non-string elements will be converted to string. @@ -159,8 +148,7 @@ def writer( quoting: _QuotingType = 0, strict: bool = False, ) -> _writer: - """ - csv_writer = csv.writer(fileobj [, dialect='excel'] + """csv_writer = csv.writer(fileobj [, dialect='excel'] [optional keyword args]) for row in sequence: csv_writer.writerow(row) @@ -188,8 +176,7 @@ def reader( quoting: _QuotingType = 0, strict: bool = False, ) -> _reader: - """ - csv_reader = reader(iterable [, dialect='excel'] + """csv_reader = reader(iterable [, dialect='excel'] [optional keyword args]) for row in csv_reader: process(row) @@ -217,35 +204,30 @@ def register_dialect( quoting: _QuotingType = 0, strict: bool = False, ) -> None: - """ - Create a mapping from a string name to a dialect class. + """Create a mapping from a string name to a dialect class. dialect = csv.register_dialect(name[, dialect[, **fmtparams]]) """ def unregister_dialect(name: str) -> None: - """ - Delete the name/dialect mapping associated with a string name. + """Delete the name/dialect mapping associated with a string name. csv.unregister_dialect(name) """ def get_dialect(name: str) -> Dialect: - """ - Return the dialect instance associated with name. + """Return the dialect instance associated with name. dialect = csv.get_dialect(name) """ def list_dialects() -> list[str]: - """ - Return a list of all known dialect names. + """Return a list of all known dialect names. names = csv.list_dialects() """ def field_size_limit(new_limit: int = ...) -> int: - """ - Sets an upper limit on parsed fields. + """Sets an upper limit on parsed fields. csv.field_size_limit([limit]) diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_ctypes.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_ctypes.pyi index 051ca292ee..983eb4b7b1 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_ctypes.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_ctypes.pyi @@ -33,38 +33,52 @@ if sys.platform == "win32": _COMError_Details: TypeAlias = tuple[str | None, str | None, str | None, int | None, int | None] class COMError(Exception): + """Raised when a COM method call failed.""" + hresult: int text: str | None details: _COMError_Details def __init__(self, hresult: int, text: str | None, details: _COMError_Details) -> None: ... - def CopyComPointer(src: _PointerLike, dst: _PointerLike | _CArgObject) -> int: ... - + def CopyComPointer(src: _PointerLike, dst: _PointerLike | _CArgObject) -> int: + """CopyComPointer(src, dst) -> HRESULT value""" FUNCFLAG_HRESULT: int FUNCFLAG_STDCALL: int - def FormatError(code: int = ...) -> str: ... + def FormatError(code: int = ...) -> str: + """FormatError([integer]) -> string + + Convert a win32 error code into a string. If the error code is not + given, the return value of a call to GetLastError() is used. + """ + def get_last_error() -> int: ... def set_last_error(value: int) -> int: ... - def LoadLibrary(name: str, load_flags: int = 0, /) -> int: ... - def FreeLibrary(handle: int, /) -> None: ... + def LoadLibrary(name: str, load_flags: int = 0, /) -> int: + """LoadLibrary(name, load_flags) -> handle + + Load an executable (usually a DLL), and return a handle to it. + The handle may be used to locate exported functions in this + module. load_flags are as defined for LoadLibraryEx in the + Windows API. + """ + + def FreeLibrary(handle: int, /) -> None: + """FreeLibrary(handle) -> void + + Free the handle of an executable previously loaded by LoadLibrary. + """ else: def dlclose(handle: int, /) -> None: - """ - dlclose a library - """ + """dlclose a library""" # The default for flag is RTLD_GLOBAL|RTLD_LOCAL, which is platform dependent. def dlopen(name: StrOrBytesPath, flag: int = ..., /) -> int: - """ - dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library - """ + """dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library""" def dlsym(handle: int, name: str, /) -> int: - """ - find symbol in shared library - """ + """find symbol in shared library""" if sys.version_info >= (3, 13): # This class is not exposed. It calls itself _ctypes.CType_Type. @@ -111,9 +125,7 @@ class _PyCSimpleType(_CTypeBaseType): def __rmul__(self: type[_CT], value: int, /) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] class _SimpleCData(_CData, Generic[_T], metaclass=_PyCSimpleType): - """ - XXX to be provided - """ + """XXX to be provided""" value: _T # The TypeVar can be unsolved here, @@ -139,9 +151,7 @@ class _PyCPointerType(_CTypeBaseType): def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] class _Pointer(_PointerLike, _CData, Generic[_CT], metaclass=_PyCPointerType): - """ - XXX to be provided - """ + """XXX to be provided""" _type_: type[_CT] contents: _CT @@ -151,22 +161,17 @@ class _Pointer(_PointerLike, _CData, Generic[_CT], metaclass=_PyCPointerType): def __init__(self, arg: _CT) -> None: ... @overload def __getitem__(self, key: int, /) -> Any: - """ - Return self[key]. - """ + """Return self[key].""" @overload def __getitem__(self, key: slice, /) -> list[Any]: ... def __setitem__(self, key: int, value: Any, /) -> None: - """ - Set self[key] to value. - """ + """Set self[key] to value.""" if sys.version_info < (3, 14): @overload def POINTER(type: None, /) -> type[c_void_p]: - """ - Create and return a new ctypes pointer type. + """Create and return a new ctypes pointer type. type A ctypes type. @@ -178,8 +183,7 @@ if sys.version_info < (3, 14): @overload def POINTER(type: type[_CT], /) -> type[_Pointer[_CT]]: ... def pointer(obj: _CT, /) -> _Pointer[_CT]: - """ - Create a new pointer instance, pointing to 'obj'. + """Create a new pointer instance, pointing to 'obj'. The returned object is of the type POINTER(type(obj)). Note that if you just want to pass a pointer to an object to a foreign function call, you @@ -193,14 +197,11 @@ class _CArgObject: ... if sys.version_info >= (3, 14): def byref(obj: _CData | _CDataType, offset: int = 0, /) -> _CArgObject: - """ - Return a pointer lookalike to a C instance, only usable as function argument. - """ + """Return a pointer lookalike to a C instance, only usable as function argument.""" else: def byref(obj: _CData | _CDataType, offset: int = 0) -> _CArgObject: - """ - byref(C instance[, offset=0]) -> byref-object + """byref(C instance[, offset=0]) -> byref-object Return a pointer lookalike to a C instance, only usable as function argument """ @@ -222,9 +223,7 @@ class _PyCFuncPtrType(_CTypeBaseType): def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] class CFuncPtr(_PointerLike, _CData, metaclass=_PyCFuncPtrType): - """ - Function Pointer - """ + """Function Pointer""" restype: type[_CDataType] | Callable[[int], Any] | None argtypes: Sequence[type[_CDataType]] @@ -246,9 +245,7 @@ class CFuncPtr(_PointerLike, _CData, metaclass=_PyCFuncPtrType): ) -> Self: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: - """ - Call self as a function. - """ + """Call self as a function.""" _GetT = TypeVar("_GetT") _SetT = TypeVar("_SetT") @@ -290,9 +287,7 @@ class _UnionType(_CTypeBaseType): def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] class Union(_CData, metaclass=_UnionType): - """ - Union base class - """ + """Union base class""" _fields_: ClassVar[Sequence[tuple[str, type[_CDataType]] | tuple[str, type[_CDataType], int]]] _pack_: ClassVar[int] @@ -322,9 +317,7 @@ class _PyCStructType(_CTypeBaseType): def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] class Structure(_CData, metaclass=_PyCStructType): - """ - Structure base class - """ + """Structure base class""" _fields_: ClassVar[Sequence[tuple[str, type[_CDataType]] | tuple[str, type[_CDataType], int]]] _pack_: ClassVar[int] @@ -350,8 +343,7 @@ class _PyCArrayType(_CTypeBaseType): def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] class Array(_CData, Generic[_CT], metaclass=_PyCArrayType): - """ - Abstract base class for arrays. + """Abstract base class for arrays. The recommended way to create concrete array types is by multiplying any ctypes data type with a non-negative integer. Alternatively, you can subclass @@ -391,17 +383,13 @@ class Array(_CData, Generic[_CT], metaclass=_PyCArrayType): def __init__(self, *args: Any) -> None: ... @overload def __getitem__(self, key: int, /) -> Any: - """ - Return self[key]. - """ + """Return self[key].""" @overload def __getitem__(self, key: slice, /) -> list[Any]: ... @overload def __setitem__(self, key: int, value: Any, /) -> None: - """ - Set self[key] to value. - """ + """Set self[key] to value.""" @overload def __setitem__(self, key: slice, value: Iterable[Any], /) -> None: ... @@ -409,46 +397,33 @@ class Array(_CData, Generic[_CT], metaclass=_PyCArrayType): # Can't inherit from Sized because the metaclass conflict between # Sized and _CData prevents using _CDataMeta. def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" def addressof(obj: _CData | _CDataType, /) -> int: - """ - Return the address of the C instance internal buffer - """ + """Return the address of the C instance internal buffer""" def alignment(obj_or_type: _CData | _CDataType | type[_CData | _CDataType], /) -> int: - """ - alignment(C type) -> integer + """alignment(C type) -> integer alignment(C instance) -> integer Return the alignment requirements of a C instance """ def get_errno() -> int: ... def resize(obj: _CData | _CDataType, size: int, /) -> None: - """ - Resize the memory buffer of a ctypes instance - """ + """Resize the memory buffer of a ctypes instance""" def set_errno(value: int, /) -> int: ... def sizeof(obj_or_type: _CData | _CDataType | type[_CData | _CDataType], /) -> int: - """ - Return the size in bytes of a C instance. - """ + """Return the size in bytes of a C instance.""" def PyObj_FromPtr(address: int, /) -> Any: ... def Py_DECREF(o: _T, /) -> _T: ... def Py_INCREF(o: _T, /) -> _T: ... def buffer_info(o: _CData | _CDataType | type[_CData | _CDataType], /) -> tuple[str, int, tuple[int, ...]]: - """ - Return buffer interface information - """ + """Return buffer interface information""" def call_cdeclfunction(address: int, arguments: tuple[Any, ...], /) -> Any: ... def call_function(address: int, arguments: tuple[Any, ...], /) -> Any: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_curses.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_curses.pyi index 654ec944ad..f7421fad65 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_curses.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_curses.pyi @@ -277,23 +277,16 @@ _C_API: Any version: bytes def baudrate() -> int: - """ - Return the output speed of the terminal in bits per second. - """ + """Return the output speed of the terminal in bits per second.""" def beep() -> None: - """ - Emit a short attention sound. - """ + """Emit a short attention sound.""" def can_change_color() -> bool: - """ - Return True if the programmer can change the colors displayed by the terminal. - """ + """Return True if the programmer can change the colors displayed by the terminal.""" def cbreak(flag: bool = True, /) -> None: - """ - Enter cbreak mode. + """Enter cbreak mode. flag If false, the effect is the same as calling nocbreak(). @@ -306,8 +299,7 @@ def cbreak(flag: bool = True, /) -> None: """ def color_content(color_number: int, /) -> tuple[int, int, int]: - """ - Return the red, green, and blue (RGB) components of the specified color. + """Return the red, green, and blue (RGB) components of the specified color. color_number The number of the color (0 - (COLORS-1)). @@ -317,8 +309,7 @@ def color_content(color_number: int, /) -> tuple[int, int, int]: """ def color_pair(pair_number: int, /) -> int: - """ - Return the attribute value for displaying text in the specified color. + """Return the attribute value for displaying text in the specified color. pair_number The number of the color pair. @@ -328,8 +319,7 @@ def color_pair(pair_number: int, /) -> int: """ def curs_set(visibility: int, /) -> int: - """ - Set the cursor state. + """Set the cursor state. visibility 0 for invisible, 1 for normal visible, or 2 for very visible. @@ -341,8 +331,7 @@ def curs_set(visibility: int, /) -> int: """ def def_prog_mode() -> None: - """ - Save the current terminal mode as the "program" mode. + """Save the current terminal mode as the "program" mode. The "program" mode is the mode when the running program is using curses. @@ -350,8 +339,7 @@ def def_prog_mode() -> None: """ def def_shell_mode() -> None: - """ - Save the current terminal mode as the "shell" mode. + """Save the current terminal mode as the "shell" mode. The "shell" mode is the mode when the running program is not using curses. @@ -359,21 +347,17 @@ def def_shell_mode() -> None: """ def delay_output(ms: int, /) -> None: - """ - Insert a pause in output. + """Insert a pause in output. ms Duration in milliseconds. """ def doupdate() -> None: - """ - Update the physical screen to match the virtual screen. - """ + """Update the physical screen to match the virtual screen.""" def echo(flag: bool = True, /) -> None: - """ - Enter echo mode. + """Enter echo mode. flag If false, the effect is the same as calling noecho(). @@ -382,34 +366,27 @@ def echo(flag: bool = True, /) -> None: """ def endwin() -> None: - """ - De-initialize the library, and return terminal to normal status. - """ + """De-initialize the library, and return terminal to normal status.""" def erasechar() -> bytes: - """ - Return the user's current erase character. - """ + """Return the user's current erase character.""" def filter() -> None: ... def flash() -> None: - """ - Flash the screen. + """Flash the screen. That is, change it to reverse-video and then change it back in a short interval. """ def flushinp() -> None: - """ - Flush all input buffers. + """Flush all input buffers. This throws away any typeahead that has been typed by the user and has not yet been processed by the program. """ def get_escdelay() -> int: - """ - Gets the curses ESCDELAY setting. + """Gets the curses ESCDELAY setting. Gets the number of milliseconds to wait after reading an escape character, to distinguish between an individual escape character entered on the @@ -417,39 +394,34 @@ def get_escdelay() -> int: """ def get_tabsize() -> int: - """ - Gets the curses TABSIZE setting. + """Gets the curses TABSIZE setting. Gets the number of columns used by the curses library when converting a tab character to spaces as it adds the tab to a window. """ def getmouse() -> tuple[int, int, int, int, int]: - """ - Retrieve the queued mouse event. + """Retrieve the queued mouse event. After getch() returns KEY_MOUSE to signal a mouse event, this function returns a 5-tuple (id, x, y, z, bstate). """ def getsyx() -> tuple[int, int]: - """ - Return the current coordinates of the virtual screen cursor. + """Return the current coordinates of the virtual screen cursor. Return a (y, x) tuple. If leaveok is currently true, return (-1, -1). """ def getwin(file: SupportsRead[bytes], /) -> window: - """ - Read window related data stored in the file by an earlier putwin() call. + """Read window related data stored in the file by an earlier putwin() call. The routine then creates and initializes a new window using that data, returning the new window object. """ def halfdelay(tenths: int, /) -> None: - """ - Enter half-delay mode. + """Enter half-delay mode. tenths Maximal blocking delay in tenths of seconds (1 - 255). @@ -458,14 +430,11 @@ def halfdelay(tenths: int, /) -> None: """ def has_colors() -> bool: - """ - Return True if the terminal can display colors; otherwise, return False. - """ + """Return True if the terminal can display colors; otherwise, return False.""" if sys.version_info >= (3, 10): def has_extended_color_support() -> bool: - """ - Return True if the module supports extended colors; otherwise, return False. + """Return True if the module supports extended colors; otherwise, return False. Extended color support allows more than 256 color-pairs for terminals that support more than 16 colors (e.g. xterm-256color). @@ -473,8 +442,7 @@ if sys.version_info >= (3, 10): if sys.version_info >= (3, 14): def assume_default_colors(fg: int, bg: int, /) -> None: - """ - Allow use of default values for colors on terminals supporting this feature. + """Allow use of default values for colors on terminals supporting this feature. Assign terminal default foreground/background colors to color number -1. Change the definition of the color-pair 0 to (fg, bg). @@ -483,26 +451,20 @@ if sys.version_info >= (3, 14): """ def has_ic() -> bool: - """ - Return True if the terminal has insert- and delete-character capabilities. - """ + """Return True if the terminal has insert- and delete-character capabilities.""" def has_il() -> bool: - """ - Return True if the terminal has insert- and delete-line capabilities. - """ + """Return True if the terminal has insert- and delete-line capabilities.""" def has_key(key: int, /) -> bool: - """ - Return True if the current terminal type recognizes a key with that value. + """Return True if the current terminal type recognizes a key with that value. key Key number. """ def init_color(color_number: int, r: int, g: int, b: int, /) -> None: - """ - Change the definition of a color. + """Change the definition of a color. color_number The number of the color to be changed (0 - (COLORS-1)). @@ -519,8 +481,7 @@ def init_color(color_number: int, r: int, g: int, b: int, /) -> None: """ def init_pair(pair_number: int, fg: int, bg: int, /) -> None: - """ - Change the definition of a color-pair. + """Change the definition of a color-pair. pair_number The number of the color-pair to be changed (1 - (COLOR_PAIRS-1)). @@ -534,16 +495,14 @@ def init_pair(pair_number: int, fg: int, bg: int, /) -> None: """ def initscr() -> window: - """ - Initialize the library. + """Initialize the library. Return a WindowObject which represents the whole screen. """ def intrflush(flag: bool, /) -> None: ... def is_term_resized(nlines: int, ncols: int, /) -> bool: - """ - Return True if resize_term() would modify the window structure, False otherwise. + """Return True if resize_term() would modify the window structure, False otherwise. nlines Height. @@ -552,42 +511,34 @@ def is_term_resized(nlines: int, ncols: int, /) -> bool: """ def isendwin() -> bool: - """ - Return True if endwin() has been called. - """ + """Return True if endwin() has been called.""" def keyname(key: int, /) -> bytes: - """ - Return the name of specified key. + """Return the name of specified key. key Key number. """ def killchar() -> bytes: - """ - Return the user's current line kill character. - """ + """Return the user's current line kill character.""" def longname() -> bytes: - """ - Return the terminfo long name field describing the current terminal. + """Return the terminfo long name field describing the current terminal. The maximum length of a verbose description is 128 characters. It is defined only after the call to initscr(). """ def meta(yes: bool, /) -> None: - """ - Enable/disable meta keys. + """Enable/disable meta keys. If yes is True, allow 8-bit characters to be input. If yes is False, allow only 7-bit characters. """ def mouseinterval(interval: int, /) -> None: - """ - Set and retrieve the maximum time between press and release in a click. + """Set and retrieve the maximum time between press and release in a click. interval Time in milliseconds. @@ -598,8 +549,7 @@ def mouseinterval(interval: int, /) -> None: """ def mousemask(newmask: int, /) -> tuple[int, int]: - """ - Set the mouse events to be reported, and return a tuple (availmask, oldmask). + """Set the mouse events to be reported, and return a tuple (availmask, oldmask). Return a tuple (availmask, oldmask). availmask indicates which of the specified mouse events can be reported; on complete failure it returns 0. @@ -608,16 +558,14 @@ def mousemask(newmask: int, /) -> tuple[int, int]: """ def napms(ms: int, /) -> int: - """ - Sleep for specified time. + """Sleep for specified time. ms Duration in milliseconds. """ def newpad(nlines: int, ncols: int, /) -> window: - """ - Create and return a pointer to a new pad data structure. + """Create and return a pointer to a new pad data structure. nlines Height. @@ -626,8 +574,7 @@ def newpad(nlines: int, ncols: int, /) -> window: """ def newwin(nlines: int, ncols: int, begin_y: int = ..., begin_x: int = ..., /) -> window: - """ - newwin(nlines, ncols, [begin_y=0, begin_x=0]) + """newwin(nlines, ncols, [begin_y=0, begin_x=0]) Return a new window. nlines @@ -644,8 +591,7 @@ def newwin(nlines: int, ncols: int, begin_y: int = ..., begin_x: int = ..., /) - """ def nl(flag: bool = True, /) -> None: - """ - Enter newline mode. + """Enter newline mode. flag If false, the effect is the same as calling nonl(). @@ -655,67 +601,58 @@ def nl(flag: bool = True, /) -> None: """ def nocbreak() -> None: - """ - Leave cbreak mode. + """Leave cbreak mode. Return to normal "cooked" mode with line buffering. """ def noecho() -> None: - """ - Leave echo mode. + """Leave echo mode. Echoing of input characters is turned off. """ def nonl() -> None: - """ - Leave newline mode. + """Leave newline mode. Disable translation of return into newline on input, and disable low-level translation of newline into newline/return on output. """ def noqiflush() -> None: - """ - Disable queue flushing. + """Disable queue flushing. When queue flushing is disabled, normal flush of input and output queues associated with the INTR, QUIT and SUSP characters will not be done. """ def noraw() -> None: - """ - Leave raw mode. + """Leave raw mode. Return to normal "cooked" mode with line buffering. """ def pair_content(pair_number: int, /) -> tuple[int, int]: - """ - Return a tuple (fg, bg) containing the colors for the requested color pair. + """Return a tuple (fg, bg) containing the colors for the requested color pair. pair_number The number of the color pair (0 - (COLOR_PAIRS-1)). """ def pair_number(attr: int, /) -> int: - """ - Return the number of the color-pair set by the specified attribute value. + """Return the number of the color-pair set by the specified attribute value. color_pair() is the counterpart to this function. """ def putp(string: ReadOnlyBuffer, /) -> None: - """ - Emit the value of a specified terminfo capability for the current terminal. + """Emit the value of a specified terminfo capability for the current terminal. Note that the output of putp() always goes to standard output. """ def qiflush(flag: bool = True, /) -> None: - """ - Enable queue flushing. + """Enable queue flushing. flag If false, the effect is the same as calling noqiflush(). @@ -725,8 +662,7 @@ def qiflush(flag: bool = True, /) -> None: """ def raw(flag: bool = True, /) -> None: - """ - Enter raw mode. + """Enter raw mode. flag If false, the effect is the same as calling noraw(). @@ -737,23 +673,16 @@ def raw(flag: bool = True, /) -> None: """ def reset_prog_mode() -> None: - """ - Restore the terminal to "program" mode, as previously saved by def_prog_mode(). - """ + """Restore the terminal to "program" mode, as previously saved by def_prog_mode().""" def reset_shell_mode() -> None: - """ - Restore the terminal to "shell" mode, as previously saved by def_shell_mode(). - """ + """Restore the terminal to "shell" mode, as previously saved by def_shell_mode().""" def resetty() -> None: - """ - Restore terminal mode. - """ + """Restore terminal mode.""" def resize_term(nlines: int, ncols: int, /) -> None: - """ - Backend function used by resizeterm(), performing most of the work. + """Backend function used by resizeterm(), performing most of the work. nlines Height. @@ -768,8 +697,7 @@ def resize_term(nlines: int, ncols: int, /) -> None: """ def resizeterm(nlines: int, ncols: int, /) -> None: - """ - Resize the standard and current windows to the specified dimensions. + """Resize the standard and current windows to the specified dimensions. nlines Height. @@ -781,13 +709,10 @@ def resizeterm(nlines: int, ncols: int, /) -> None: """ def savetty() -> None: - """ - Save terminal mode. - """ + """Save terminal mode.""" def set_escdelay(ms: int, /) -> None: - """ - Sets the curses ESCDELAY setting. + """Sets the curses ESCDELAY setting. ms length of the delay in milliseconds. @@ -798,8 +723,7 @@ def set_escdelay(ms: int, /) -> None: """ def set_tabsize(size: int, /) -> None: - """ - Sets the curses TABSIZE setting. + """Sets the curses TABSIZE setting. size rendered cell width of a tab character. @@ -809,8 +733,7 @@ def set_tabsize(size: int, /) -> None: """ def setsyx(y: int, x: int, /) -> None: - """ - Set the virtual screen cursor. + """Set the virtual screen cursor. y Y-coordinate. @@ -821,8 +744,7 @@ def setsyx(y: int, x: int, /) -> None: """ def setupterm(term: str | None = None, fd: int = -1) -> None: - """ - Initialize the terminal. + """Initialize the terminal. term Terminal name. @@ -833,8 +755,7 @@ def setupterm(term: str | None = None, fd: int = -1) -> None: """ def start_color() -> None: - """ - Initializes eight basic colors and global variables COLORS and COLOR_PAIRS. + """Initializes eight basic colors and global variables COLORS and COLOR_PAIRS. Must be called if the programmer wants to use colors, and before any other color manipulation routine is called. It is good practice to call this @@ -845,18 +766,13 @@ def start_color() -> None: """ def termattrs() -> int: - """ - Return a logical OR of all video attributes supported by the terminal. - """ + """Return a logical OR of all video attributes supported by the terminal.""" def termname() -> bytes: - """ - Return the value of the environment variable TERM, truncated to 14 characters. - """ + """Return the value of the environment variable TERM, truncated to 14 characters.""" def tigetflag(capname: str, /) -> int: - """ - Return the value of the Boolean capability. + """Return the value of the Boolean capability. capname The terminfo capability name. @@ -866,8 +782,7 @@ def tigetflag(capname: str, /) -> int: """ def tigetnum(capname: str, /) -> int: - """ - Return the value of the numeric capability. + """Return the value of the numeric capability. capname The terminfo capability name. @@ -877,8 +792,7 @@ def tigetnum(capname: str, /) -> int: """ def tigetstr(capname: str, /) -> bytes | None: - """ - Return the value of the string capability. + """Return the value of the string capability. capname The terminfo capability name. @@ -900,16 +814,14 @@ def tparm( i9: int = 0, /, ) -> bytes: - """ - Instantiate the specified byte string with the supplied parameters. + """Instantiate the specified byte string with the supplied parameters. str Parameterized byte string obtained from the terminfo database. """ def typeahead(fd: int, /) -> None: - """ - Specify that the file descriptor fd be used for typeahead checking. + """Specify that the file descriptor fd be used for typeahead checking. fd File descriptor. @@ -918,39 +830,30 @@ def typeahead(fd: int, /) -> None: """ def unctrl(ch: _ChType, /) -> bytes: - """ - Return a string which is a printable representation of the character ch. + """Return a string which is a printable representation of the character ch. Control characters are displayed as a caret followed by the character, for example as ^C. Printing characters are left as they are. """ def unget_wch(ch: int | str, /) -> None: - """ - Push ch so the next get_wch() will return it. - """ + """Push ch so the next get_wch() will return it.""" def ungetch(ch: _ChType, /) -> None: - """ - Push ch so the next getch() will return it. - """ + """Push ch so the next getch() will return it.""" def ungetmouse(id: int, x: int, y: int, z: int, bstate: int, /) -> None: - """ - Push a KEY_MOUSE event onto the input queue. + """Push a KEY_MOUSE event onto the input queue. The following getmouse() will return the given state data. """ def update_lines_cols() -> None: ... def use_default_colors() -> None: - """ - Equivalent to assume_default_colors(-1, -1). - """ + """Equivalent to assume_default_colors(-1, -1).""" def use_env(flag: bool, /) -> None: - """ - Use environment variables LINES and COLUMNS. + """Use environment variables LINES and COLUMNS. If used, this function should be called before initscr() or newterm() are called. @@ -969,8 +872,7 @@ class window: # undocumented encoding: str @overload def addch(self, ch: _ChType, attr: int = ...) -> None: - """ - addch([y, x,] ch, [attr=_curses.A_NORMAL]) + """addch([y, x,] ch, [attr=_curses.A_NORMAL]) Paint the character. y @@ -992,8 +894,7 @@ class window: # undocumented def addch(self, y: int, x: int, ch: _ChType, attr: int = ...) -> None: ... @overload def addnstr(self, str: str, n: int, attr: int = ...) -> None: - """ - addnstr([y, x,] str, n, [attr]) + """addnstr([y, x,] str, n, [attr]) Paint at most n characters of the string. y @@ -1017,8 +918,7 @@ class window: # undocumented def addnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... @overload def addstr(self, str: str, attr: int = ...) -> None: - """ - addstr([y, x,] str, [attr]) + """addstr([y, x,] str, [attr]) Paint the string. y @@ -1039,23 +939,16 @@ class window: # undocumented @overload def addstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... def attroff(self, attr: int, /) -> None: - """ - Remove attribute attr from the "background" set. - """ + """Remove attribute attr from the "background" set.""" def attron(self, attr: int, /) -> None: - """ - Add attribute attr from the "background" set. - """ + """Add attribute attr from the "background" set.""" def attrset(self, attr: int, /) -> None: - """ - Set the "background" set of attributes. - """ + """Set the "background" set of attributes.""" def bkgd(self, ch: _ChType, attr: int = ..., /) -> None: - """ - Set the background property of the window. + """Set the background property of the window. ch Background character. @@ -1064,8 +957,7 @@ class window: # undocumented """ def bkgdset(self, ch: _ChType, attr: int = ..., /) -> None: - """ - Set the window's background. + """Set the window's background. ch Background character. @@ -1084,8 +976,7 @@ class window: # undocumented bl: _ChType = ..., br: _ChType = ..., ) -> None: - """ - Draw a border around the edges of the window. + """Draw a border around the edges of the window. ls Left side. @@ -1112,8 +1003,7 @@ class window: # undocumented @overload def box(self) -> None: - """ - box([verch=0, horch=0]) + """box([verch=0, horch=0]) Draw a border around the edges of the window. verch @@ -1129,8 +1019,7 @@ class window: # undocumented def box(self, vertch: _ChType = ..., horch: _ChType = ...) -> None: ... @overload def chgat(self, attr: int) -> None: - """ - chgat([y, x,] [n=-1,] attr) + """chgat([y, x,] [n=-1,] attr) Set the attributes of characters. y @@ -1163,8 +1052,7 @@ class window: # undocumented def cursyncup(self) -> None: ... @overload def delch(self) -> None: - """ - delch([y, x]) + """delch([y, x]) Delete any character at (y, x). y @@ -1178,8 +1066,7 @@ class window: # undocumented def deleteln(self) -> None: ... @overload def derwin(self, begin_y: int, begin_x: int) -> window: - """ - derwin([nlines=0, ncols=0,] begin_y, begin_x) + """derwin([nlines=0, ncols=0,] begin_y, begin_x) Create a sub-window (window-relative coordinates). nlines @@ -1199,8 +1086,7 @@ class window: # undocumented @overload def derwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ... def echochar(self, ch: _ChType, attr: int = ..., /) -> None: - """ - Add character ch with attribute attr, and refresh. + """Add character ch with attribute attr, and refresh. ch Character to add. @@ -1209,8 +1095,7 @@ class window: # undocumented """ def enclose(self, y: int, x: int, /) -> bool: - """ - Return True if the screen-relative coordinates are enclosed by the window. + """Return True if the screen-relative coordinates are enclosed by the window. y Y-coordinate. @@ -1221,14 +1106,11 @@ class window: # undocumented def erase(self) -> None: ... def getbegyx(self) -> tuple[int, int]: ... def getbkgd(self) -> tuple[int, int]: - """ - Return the window's current background character/attribute pair. - """ + """Return the window's current background character/attribute pair.""" @overload def getch(self) -> int: - """ - getch([y, x]) + """getch([y, x]) Get a character code from terminal keyboard. y @@ -1245,8 +1127,7 @@ class window: # undocumented def getch(self, y: int, x: int) -> int: ... @overload def get_wch(self) -> int | str: - """ - get_wch([y, x]) + """get_wch([y, x]) Get a wide character from terminal keyboard. y @@ -1262,8 +1143,7 @@ class window: # undocumented def get_wch(self, y: int, x: int) -> int | str: ... @overload def getkey(self) -> str: - """ - getkey([y, x]) + """getkey([y, x]) Get a character (string) from terminal keyboard. y @@ -1282,8 +1162,7 @@ class window: # undocumented def getparyx(self) -> tuple[int, int]: ... @overload def getstr(self) -> bytes: - """ - getstr([[y, x,] n=2047]) + """getstr([[y, x,] n=2047]) Read a string from the user, with primitive line editing capacity. y @@ -1303,8 +1182,7 @@ class window: # undocumented def getyx(self) -> tuple[int, int]: ... @overload def hline(self, ch: _ChType, n: int) -> None: - """ - hline([y, x,] ch, n, [attr=_curses.A_NORMAL]) + """hline([y, x,] ch, n, [attr=_curses.A_NORMAL]) Display a horizontal line. y @@ -1326,8 +1204,7 @@ class window: # undocumented def immedok(self, flag: bool) -> None: ... @overload def inch(self) -> int: - """ - inch([y, x]) + """inch([y, x]) Return the character at the given position in the window. y @@ -1342,8 +1219,7 @@ class window: # undocumented def inch(self, y: int, x: int) -> int: ... @overload def insch(self, ch: _ChType, attr: int = ...) -> None: - """ - insch([y, x,] ch, [attr=_curses.A_NORMAL]) + """insch([y, x,] ch, [attr=_curses.A_NORMAL]) Insert a character before the current or specified position. y @@ -1365,8 +1241,7 @@ class window: # undocumented def insertln(self) -> None: ... @overload def insnstr(self, str: str, n: int, attr: int = ...) -> None: - """ - insnstr([y, x,] str, n, [attr]) + """insnstr([y, x,] str, n, [attr]) Insert at most n characters of the string. y @@ -1392,8 +1267,7 @@ class window: # undocumented def insnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... @overload def insstr(self, str: str, attr: int = ...) -> None: - """ - insstr([y, x,] str, [attr]) + """insstr([y, x,] str, [attr]) Insert the string before the current or specified position. y @@ -1416,8 +1290,7 @@ class window: # undocumented def insstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... @overload def instr(self, n: int = ...) -> bytes: - """ - instr([y, x,] n=2047) + """instr([y, x,] n=2047) Return a string of characters, extracted from the window. y @@ -1436,8 +1309,7 @@ class window: # undocumented @overload def instr(self, y: int, x: int, n: int = ...) -> bytes: ... def is_linetouched(self, line: int, /) -> bool: - """ - Return True if the specified line was modified, otherwise return False. + """Return True if the specified line was modified, otherwise return False. line Line number. @@ -1455,8 +1327,7 @@ class window: # undocumented def notimeout(self, yes: bool) -> None: ... @overload def noutrefresh(self) -> None: - """ - noutrefresh([pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol]) + """noutrefresh([pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol]) Mark for refresh but wait. This function updates the data structure representing the desired state of the @@ -1468,8 +1339,7 @@ class window: # undocumented def noutrefresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ... @overload def overlay(self, destwin: window) -> None: - """ - overlay(destwin, [sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol]) + """overlay(destwin, [sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol]) Overlay the window on top of destwin. The windows need not be the same size, only the overlapping region is copied. @@ -1488,8 +1358,7 @@ class window: # undocumented ) -> None: ... @overload def overwrite(self, destwin: window) -> None: - """ - overwrite(destwin, [sminrow, smincol, dminrow, dmincol, dmaxrow, + """overwrite(destwin, [sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol]) Overwrite the window on top of destwin. @@ -1508,15 +1377,13 @@ class window: # undocumented self, destwin: window, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int ) -> None: ... def putwin(self, file: SupportsWrite[bytes], /) -> None: - """ - Write all data associated with the window into the provided file object. + """Write all data associated with the window into the provided file object. This information can be later retrieved using the getwin() function. """ def redrawln(self, beg: int, num: int, /) -> None: - """ - Mark the specified lines corrupted. + """Mark the specified lines corrupted. beg Starting line number. @@ -1529,8 +1396,7 @@ class window: # undocumented def redrawwin(self) -> None: ... @overload def refresh(self) -> None: - """ - refresh([pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol]) + """refresh([pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol]) Update the display immediately. Synchronize actual screen with previous drawing/deleting methods. @@ -1550,8 +1416,7 @@ class window: # undocumented def refresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ... def resize(self, nlines: int, ncols: int) -> None: ... def scroll(self, lines: int = ...) -> None: - """ - scroll([lines=1]) + """scroll([lines=1]) Scroll the screen or scrolling region. lines @@ -1562,8 +1427,7 @@ class window: # undocumented def scrollok(self, flag: bool) -> None: ... def setscrreg(self, top: int, bottom: int, /) -> None: - """ - Define a software scrolling region. + """Define a software scrolling region. top First line number. @@ -1577,8 +1441,7 @@ class window: # undocumented def standout(self) -> None: ... @overload def subpad(self, begin_y: int, begin_x: int) -> window: - """ - subwin([nlines=0, ncols=0,] begin_y, begin_x) + """subwin([nlines=0, ncols=0,] begin_y, begin_x) Create a sub-window (screen-relative coordinates). nlines @@ -1598,8 +1461,7 @@ class window: # undocumented def subpad(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ... @overload def subwin(self, begin_y: int, begin_x: int) -> window: - """ - subwin([nlines=0, ncols=0,] begin_y, begin_x) + """subwin([nlines=0, ncols=0,] begin_y, begin_x) Create a sub-window (screen-relative coordinates). nlines @@ -1622,8 +1484,7 @@ class window: # undocumented def syncup(self) -> None: ... def timeout(self, delay: int) -> None: ... def touchline(self, start: int, count: int, changed: bool = ...) -> None: - """ - touchline(start, count, [changed=True]) + """touchline(start, count, [changed=True]) Pretend count lines have been changed, starting with line start. If changed is supplied, it specifies whether the affected lines are marked @@ -1634,8 +1495,7 @@ class window: # undocumented def untouchwin(self) -> None: ... @overload def vline(self, ch: _ChType, n: int) -> None: - """ - vline([y, x,] ch, n, [attr=_curses.A_NORMAL]) + """vline([y, x,] ch, n, [attr=_curses.A_NORMAL]) Display a vertical line. y diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_curses_panel.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_curses_panel.pyi index a307eea591..708dda3191 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_curses_panel.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_curses_panel.pyi @@ -9,85 +9,55 @@ class error(Exception): ... @final class panel: def above(self) -> panel: - """ - Return the panel above the current panel. - """ + """Return the panel above the current panel.""" def below(self) -> panel: - """ - Return the panel below the current panel. - """ + """Return the panel below the current panel.""" def bottom(self) -> None: - """ - Push the panel to the bottom of the stack. - """ + """Push the panel to the bottom of the stack.""" def hidden(self) -> bool: - """ - Return True if the panel is hidden (not visible), False otherwise. - """ + """Return True if the panel is hidden (not visible), False otherwise.""" def hide(self) -> None: - """ - Hide the panel. + """Hide the panel. This does not delete the object, it just makes the window on screen invisible. """ def move(self, y: int, x: int, /) -> None: - """ - Move the panel to the screen coordinates (y, x). - """ + """Move the panel to the screen coordinates (y, x).""" def replace(self, win: window, /) -> None: - """ - Change the window associated with the panel to the window win. - """ + """Change the window associated with the panel to the window win.""" def set_userptr(self, obj: object, /) -> None: - """ - Set the panel's user pointer to obj. - """ + """Set the panel's user pointer to obj.""" def show(self) -> None: - """ - Display the panel (which might have been hidden). - """ + """Display the panel (which might have been hidden).""" def top(self) -> None: - """ - Push panel to the top of the stack. - """ + """Push panel to the top of the stack.""" def userptr(self) -> object: - """ - Return the user pointer for the panel. - """ + """Return the user pointer for the panel.""" def window(self) -> window: - """ - Return the window object associated with the panel. - """ + """Return the window object associated with the panel.""" def bottom_panel() -> panel: - """ - Return the bottom panel in the panel stack. - """ + """Return the bottom panel in the panel stack.""" def new_panel(win: window, /) -> panel: - """ - Return a panel object, associating it with the given window win. - """ + """Return a panel object, associating it with the given window win.""" def top_panel() -> panel: - """ - Return the top panel in the panel stack. - """ + """Return the top panel in the panel stack.""" def update_panels() -> panel: - """ - Updates the virtual screen after changes in the panel stack. + """Updates the virtual screen after changes in the panel stack. This does not call curses.doupdate(), so you'll have to do this yourself. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_dbm.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_dbm.pyi index 35f022457e..070398f794 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_dbm.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_dbm.pyi @@ -40,8 +40,7 @@ if sys.platform != "win32": if sys.version_info >= (3, 11): def open(filename: StrOrBytesPath, flags: str = "r", mode: int = 0o666, /) -> _dbm: - """ - Return a database object. + """Return a database object. filename The filename to open. @@ -53,8 +52,7 @@ if sys.platform != "win32": """ else: def open(filename: str, flags: str = "r", mode: int = 0o666, /) -> _dbm: - """ - Return a database object. + """Return a database object. filename The filename to open. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_decimal.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_decimal.pyi index ca05d34429..a1f2841f07 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_decimal.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_decimal.pyi @@ -49,14 +49,10 @@ if sys.version_info >= (3, 14): IEEE_CONTEXT_MAX_BITS: Final[int] def setcontext(context: Context, /) -> None: - """ - Set a new default context. - """ + """Set a new default context.""" def getcontext() -> Context: - """ - Get the current default context. - """ + """Get the current default context.""" if sys.version_info >= (3, 11): def localcontext( @@ -71,8 +67,7 @@ if sys.version_info >= (3, 11): traps: dict[_TrapType, bool] | None = ..., flags: dict[_TrapType, bool] | None = ..., ) -> _ContextManager: - """ - Return a context manager that will set the default context to a copy of ctx + """Return a context manager that will set the default context to a copy of ctx on entry to the with-statement and restore the previous default context when exiting the with-statement. If no context is specified, a copy of the current default context is used. @@ -80,8 +75,7 @@ if sys.version_info >= (3, 11): else: def localcontext(ctx: Context | None = None) -> _ContextManager: - """ - Return a context manager that will set the default context to a copy of ctx + """Return a context manager that will set the default context to a copy of ctx on entry to the with-statement and restore the previous default context when exiting the with-statement. If no context is specified, a copy of the current default context is used. @@ -89,8 +83,7 @@ else: if sys.version_info >= (3, 14): def IEEEContext(bits: int, /) -> Context: - """ - Return a context object initialized to the proper values for one of the + """Return a context object initialized to the proper values for one of the IEEE interchange formats. The argument must be a multiple of 32 and less than IEEE_CONTEXT_MAX_BITS. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_frozen_importlib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_frozen_importlib.pyi index 9101e3b77c..88e59ad247 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_frozen_importlib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_frozen_importlib.pyi @@ -24,8 +24,7 @@ def __import__( fromlist: Sequence[str] = (), level: int = 0, ) -> ModuleType: - """ - Import a module. + """Import a module. The 'globals' argument is used to infer where the import is occurring from to handle relative imports. The 'locals' argument is ignored. The @@ -38,22 +37,17 @@ def __import__( def spec_from_loader( name: str, loader: LoaderProtocol | None, *, origin: str | None = None, is_package: bool | None = None ) -> importlib.machinery.ModuleSpec | None: - """ - Return a module spec based on various loader methods. - """ + """Return a module spec based on various loader methods.""" def module_from_spec(spec: importlib.machinery.ModuleSpec) -> types.ModuleType: - """ - Create a module based on the provided spec. - """ + """Create a module based on the provided spec.""" def _init_module_attrs( spec: importlib.machinery.ModuleSpec, module: types.ModuleType, *, override: bool = False ) -> types.ModuleType: ... class ModuleSpec: - """ - The specification for a module, used for loading. + """The specification for a module, used for loading. A module's spec is the source for information about the module. For data associated with the module, including source, use the spec's @@ -105,16 +99,13 @@ class ModuleSpec: cached: str | None @property def parent(self) -> str | None: - """ - The name of the module's parent. - """ + """The name of the module's parent.""" has_location: bool def __eq__(self, other: object) -> bool: ... __hash__: ClassVar[None] # type: ignore[assignment] class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): - """ - Meta path import for built-in modules. + """Meta path import for built-in modules. All methods are either class or static methods to avoid the need to instantiate the class. @@ -132,29 +123,22 @@ class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader) # InspectLoader @classmethod def is_package(cls, fullname: str) -> bool: - """ - Return False as built-in modules are never packages. - """ + """Return False as built-in modules are never packages.""" @classmethod def load_module(cls, fullname: str) -> types.ModuleType: - """ - Load the specified module into sys.modules and return it. + """Load the specified module into sys.modules and return it. This method is deprecated. Use loader.exec_module() instead. """ @classmethod def get_code(cls, fullname: str) -> None: - """ - Return None as built-in modules do not have code objects. - """ + """Return None as built-in modules do not have code objects.""" @classmethod def get_source(cls, fullname: str) -> None: - """ - Return None as built-in modules do not have source code. - """ + """Return None as built-in modules do not have source code.""" # Loader if sys.version_info < (3, 12): @staticmethod @@ -162,31 +146,22 @@ class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader) if sys.version_info >= (3, 10): @staticmethod def create_module(spec: ModuleSpec) -> types.ModuleType | None: - """ - Create a built-in module - """ + """Create a built-in module""" @staticmethod def exec_module(module: types.ModuleType) -> None: - """ - Exec a built-in module - """ + """Exec a built-in module""" else: @classmethod def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None: - """ - Create a built-in module - """ + """Create a built-in module""" @classmethod def exec_module(cls, module: types.ModuleType) -> None: - """ - Exec a built-in module - """ + """Exec a built-in module""" class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): - """ - Meta path import for frozen modules. + """Meta path import for frozen modules. All methods are either class or static methods to avoid the need to instantiate the class. @@ -204,29 +179,22 @@ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): # InspectLoader @classmethod def is_package(cls, fullname: str) -> bool: - """ - Return True if the frozen module is a package. - """ + """Return True if the frozen module is a package.""" @classmethod def load_module(cls, fullname: str) -> types.ModuleType: - """ - Load a frozen module. + """Load a frozen module. This method is deprecated. Use exec_module() instead. """ @classmethod def get_code(cls, fullname: str) -> None: - """ - Return the code object for the frozen module. - """ + """Return the code object for the frozen module.""" @classmethod def get_source(cls, fullname: str) -> None: - """ - Return None as frozen modules do not have source code. - """ + """Return None as frozen modules do not have source code.""" # Loader if sys.version_info < (3, 12): @staticmethod @@ -234,15 +202,11 @@ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): if sys.version_info >= (3, 10): @staticmethod def create_module(spec: ModuleSpec) -> types.ModuleType | None: - """ - Set __file__, if able. - """ + """Set __file__, if able.""" else: @classmethod def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None: - """ - Set __file__, if able. - """ + """Set __file__, if able.""" @staticmethod def exec_module(module: types.ModuleType) -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_frozen_importlib_external.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_frozen_importlib_external.pyi index 250260fde2..1b5de01167 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_frozen_importlib_external.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_frozen_importlib_external.pyi @@ -36,8 +36,7 @@ else: MAGIC_NUMBER: bytes def cache_from_source(path: StrPath, debug_override: bool | None = None, *, optimization: Any | None = None) -> str: - """ - Given the path to a .py file, return the path to its .pyc file. + """Given the path to a .py file, return the path to its .pyc file. The .py file does not need to exist; this simply returns the path to the .pyc file calculated as if the .py file were imported. @@ -55,8 +54,7 @@ def cache_from_source(path: StrPath, debug_override: bool | None = None, *, opti """ def source_from_cache(path: StrPath) -> str: - """ - Given the path to a .pyc. file, return the path to its .py file. + """Given the path to a .pyc. file, return the path to its .py file. The .pyc file does not need to exist; this simply returns the path to the .py file calculated to correspond to the .pyc file. If path does @@ -65,8 +63,7 @@ def source_from_cache(path: StrPath) -> str: """ def decode_source(source_bytes: ReadableBuffer) -> str: - """ - Decode bytes representing source code and return the string. + """Decode bytes representing source code and return the string. Universal newline support is used in the decoding. """ @@ -78,8 +75,7 @@ def spec_from_file_location( loader: LoaderProtocol | None = None, submodule_search_locations: list[str] | None = ..., ) -> importlib.machinery.ModuleSpec | None: - """ - Return a module spec based on a file location. + """Return a module spec based on a file location. To indicate that the module is a package, set submodule_search_locations to a list of directory paths. An @@ -94,9 +90,7 @@ def spec_from_file_location( "Future versions of Python may not enable this finder by default." ) class WindowsRegistryFinder(importlib.abc.MetaPathFinder): - """ - Meta path finder for modules declared in the Windows registry. - """ + """Meta path finder for modules declared in the Windows registry.""" if sys.version_info < (3, 12): @classmethod @@ -108,29 +102,24 @@ class WindowsRegistryFinder(importlib.abc.MetaPathFinder): ) -> ModuleSpec | None: ... class PathFinder(importlib.abc.MetaPathFinder): - """ - Meta path finder for sys.path and package __path__ attributes. - """ + """Meta path finder for sys.path and package __path__ attributes.""" if sys.version_info >= (3, 10): @staticmethod def invalidate_caches() -> None: - """ - Call the invalidate_caches() method on all path entry finders + """Call the invalidate_caches() method on all path entry finders stored in sys.path_importer_cache (where implemented). """ else: @classmethod def invalidate_caches(cls) -> None: - """ - Call the invalidate_caches() method on all path entry finders + """Call the invalidate_caches() method on all path entry finders stored in sys.path_importer_cache (where implemented). """ if sys.version_info >= (3, 10): @staticmethod def find_distributions(context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: - """ - Find distributions. + """Find distributions. Return an iterable of all Distribution instances capable of loading the metadata for packages matching ``context.name`` @@ -140,8 +129,7 @@ class PathFinder(importlib.abc.MetaPathFinder): else: @classmethod def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: - """ - Find distributions. + """Find distributions. Return an iterable of all Distribution instances capable of loading the metadata for packages matching ``context.name`` @@ -153,8 +141,7 @@ class PathFinder(importlib.abc.MetaPathFinder): def find_spec( cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None ) -> ModuleSpec | None: - """ - Try to find a spec for 'fullname' on sys.path or 'path'. + """Try to find a spec for 'fullname' on sys.path or 'path'. The search is based on sys.path_hooks and sys.path_importer_cache. """ @@ -169,8 +156,7 @@ BYTECODE_SUFFIXES: list[str] EXTENSION_SUFFIXES: list[str] class FileFinder(importlib.abc.PathEntryFinder): - """ - File-based finder. + """File-based finder. Interactions with the file system are cached for performance, being refreshed when the directory the finder is handling has been modified. @@ -178,8 +164,7 @@ class FileFinder(importlib.abc.PathEntryFinder): path: str def __init__(self, path: str, *loader_details: tuple[type[importlib.abc.Loader], list[str]]) -> None: - """ - Initialize with the path to search on and a variable number of + """Initialize with the path to search on and a variable number of 2-tuples containing the loader and the file suffixes the loader recognizes. """ @@ -188,8 +173,7 @@ class FileFinder(importlib.abc.PathEntryFinder): def path_hook( cls, *loader_details: tuple[type[importlib.abc.Loader], list[str]] ) -> Callable[[str], importlib.abc.PathEntryFinder]: - """ - A class method which returns a closure to use on sys.path_hook + """A class method which returns a closure to use on sys.path_hook which will return an instance using the specified loaders and the path called on the closure. @@ -198,56 +182,43 @@ class FileFinder(importlib.abc.PathEntryFinder): """ class _LoaderBasics: - """ - Base class of common code needed by both SourceLoader and + """Base class of common code needed by both SourceLoader and SourcelessFileLoader. """ def is_package(self, fullname: str) -> bool: - """ - Concrete implementation of InspectLoader.is_package by checking if + """Concrete implementation of InspectLoader.is_package by checking if the path returned by get_filename has a filename of '__init__.py'. """ def create_module(self, spec: ModuleSpec) -> types.ModuleType | None: - """ - Use default semantics for module creation. - """ + """Use default semantics for module creation.""" def exec_module(self, module: types.ModuleType) -> None: - """ - Execute the module. - """ + """Execute the module.""" def load_module(self, fullname: str) -> types.ModuleType: - """ - This method is deprecated. - """ + """This method is deprecated.""" class SourceLoader(_LoaderBasics): def path_mtime(self, path: str) -> float: - """ - Optional method that returns the modification time (an int) for the + """Optional method that returns the modification time (an int) for the specified path (a str). Raises OSError when the path cannot be handled. """ def set_data(self, path: str, data: bytes) -> None: - """ - Optional method which writes data (bytes) to a file path (a str). + """Optional method which writes data (bytes) to a file path (a str). Implementing this method allows for the writing of bytecode files. """ def get_source(self, fullname: str) -> str | None: - """ - Concrete implementation of InspectLoader.get_source. - """ + """Concrete implementation of InspectLoader.get_source.""" def path_stats(self, path: str) -> Mapping[str, Any]: - """ - Optional method returning a metadata dict for the specified + """Optional method returning a metadata dict for the specified path (a str). Possible keys: @@ -262,47 +233,38 @@ class SourceLoader(_LoaderBasics): def source_to_code( self, data: ReadableBuffer | str | _ast.Module | _ast.Expression | _ast.Interactive, path: ReadableBuffer | StrPath ) -> types.CodeType: - """ - Return the code object compiled from source. + """Return the code object compiled from source. The 'data' argument can be any object type that compile() supports. """ def get_code(self, fullname: str) -> types.CodeType | None: - """ - Concrete implementation of InspectLoader.get_code. + """Concrete implementation of InspectLoader.get_code. Reading of bytecode requires path_stats to be implemented. To write bytecode, set_data must also be implemented. """ class FileLoader: - """ - Base file loader class which implements the loader protocol methods that + """Base file loader class which implements the loader protocol methods that require file system usage. """ name: str path: str def __init__(self, fullname: str, path: str) -> None: - """ - Cache the module name and the path to the file found by the + """Cache the module name and the path to the file found by the finder. """ def get_data(self, path: str) -> bytes: - """ - Return the data from path as raw bytes. - """ + """Return the data from path as raw bytes.""" def get_filename(self, name: str | None = None) -> str: - """ - Return the path to the source file as found by the finder. - """ + """Return the path to the source file as found by the finder.""" def load_module(self, name: str | None = None) -> types.ModuleType: - """ - Load a module from a file. + """Load a module from a file. This method is deprecated. Use exec_module() instead. """ @@ -316,19 +278,13 @@ class FileLoader: def contents(self) -> Iterator[str]: ... class SourceFileLoader(importlib.abc.FileLoader, FileLoader, importlib.abc.SourceLoader, SourceLoader): # type: ignore[misc] # incompatible method arguments in base classes - """ - Concrete implementation of SourceLoader using the file system. - """ + """Concrete implementation of SourceLoader using the file system.""" def set_data(self, path: str, data: ReadableBuffer, *, _mode: int = 0o666) -> None: - """ - Write bytes data to a file. - """ + """Write bytes data to a file.""" def path_stats(self, path: str) -> Mapping[str, Any]: - """ - Return the metadata for the path. - """ + """Return the metadata for the path.""" def source_to_code( # type: ignore[override] # incompatible with InspectLoader.source_to_code self, @@ -337,55 +293,39 @@ class SourceFileLoader(importlib.abc.FileLoader, FileLoader, importlib.abc.Sourc *, _optimize: int = -1, ) -> types.CodeType: - """ - Return the code object compiled from source. + """Return the code object compiled from source. The 'data' argument can be any object type that compile() supports. """ class SourcelessFileLoader(importlib.abc.FileLoader, FileLoader, _LoaderBasics): - """ - Loader which handles sourceless file imports. - """ + """Loader which handles sourceless file imports.""" def get_code(self, fullname: str) -> types.CodeType | None: ... def get_source(self, fullname: str) -> None: - """ - Return None as there is no source code. - """ + """Return None as there is no source code.""" class ExtensionFileLoader(FileLoader, _LoaderBasics, importlib.abc.ExecutionLoader): - """ - Loader for extension modules. + """Loader for extension modules. The constructor is designed to work with FileFinder. """ def __init__(self, name: str, path: str) -> None: ... def get_filename(self, name: str | None = None) -> str: - """ - Return the path to the source file as found by the finder. - """ + """Return the path to the source file as found by the finder.""" def get_source(self, fullname: str) -> None: - """ - Return None as extension modules have no source code. - """ + """Return None as extension modules have no source code.""" def create_module(self, spec: ModuleSpec) -> types.ModuleType: - """ - Create an uninitialized extension module - """ + """Create an uninitialized extension module""" def exec_module(self, module: types.ModuleType) -> None: - """ - Initialize an extension module - """ + """Initialize an extension module""" def get_code(self, fullname: str) -> None: - """ - Return None as an extension module cannot create a code object. - """ + """Return None as an extension module cannot create a code object.""" def __eq__(self, other: object) -> bool: ... def __hash__(self) -> int: ... @@ -399,15 +339,12 @@ if sys.version_info >= (3, 11): def get_source(self, fullname: str) -> Literal[""]: ... def get_code(self, fullname: str) -> types.CodeType: ... def create_module(self, spec: ModuleSpec) -> None: - """ - Use default semantics for module creation. - """ + """Use default semantics for module creation.""" def exec_module(self, module: types.ModuleType) -> None: ... @deprecated("load_module() is deprecated; use exec_module() instead") def load_module(self, fullname: str) -> types.ModuleType: - """ - Load a namespace module. + """Load a namespace module. This method is deprecated. Use exec_module() instead. """ @@ -417,8 +354,7 @@ if sys.version_info >= (3, 11): @staticmethod @deprecated("module_repr() is deprecated, and has been removed in Python 3.12") def module_repr(module: types.ModuleType) -> str: - """ - Return repr for the module. + """Return repr for the module. The method is deprecated. The import machinery does the job itself. """ @@ -433,15 +369,12 @@ else: def get_source(self, fullname: str) -> Literal[""]: ... def get_code(self, fullname: str) -> types.CodeType: ... def create_module(self, spec: ModuleSpec) -> None: - """ - Use default semantics for module creation. - """ + """Use default semantics for module creation.""" def exec_module(self, module: types.ModuleType) -> None: ... @deprecated("load_module() is deprecated; use exec_module() instead") def load_module(self, fullname: str) -> types.ModuleType: - """ - Load a namespace module. + """Load a namespace module. This method is deprecated. Use exec_module() instead. """ @@ -449,8 +382,7 @@ else: @staticmethod @deprecated("module_repr() is deprecated, and has been removed in Python 3.12") def module_repr(module: types.ModuleType) -> str: - """ - Return repr for the module. + """Return repr for the module. The method is deprecated. The import machinery does the job itself. """ @@ -460,15 +392,13 @@ else: @classmethod @deprecated("module_repr() is deprecated, and has been removed in Python 3.12") def module_repr(cls, module: types.ModuleType) -> str: - """ - Return repr for the module. + """Return repr for the module. The method is deprecated. The import machinery does the job itself. """ if sys.version_info >= (3, 13): class AppleFrameworkLoader(ExtensionFileLoader, importlib.abc.ExecutionLoader): - """ - A loader for modules that have been packaged as frameworks for + """A loader for modules that have been packaged as frameworks for compatibility with Apple's iOS App Store policies. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_gdbm.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_gdbm.pyi index 0d75d11ef1..e32f15cb17 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_gdbm.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_gdbm.pyi @@ -56,8 +56,7 @@ if sys.platform != "win32": if sys.version_info >= (3, 11): def open(filename: StrOrBytesPath, flags: str = "r", mode: int = 0o666, /) -> _gdbm: - """ - Open a dbm database and return a dbm object. + """Open a dbm database and return a dbm object. The filename argument is the name of the database file. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_hashlib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_hashlib.pyi index 3d746666fa..e4325d265d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_hashlib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_hashlib.pyi @@ -27,8 +27,7 @@ class _HashObject(Protocol): def update(self, obj: ReadableBuffer, /) -> None: ... class HASH: - """ - A hash is an object used to calculate a checksum of a string of information. + """A hash is an object used to calculate a checksum of a string of information. Methods: @@ -50,31 +49,22 @@ class HASH: @property def name(self) -> str: ... def copy(self) -> Self: - """ - Return a copy of the hash object. - """ + """Return a copy of the hash object.""" def digest(self) -> bytes: - """ - Return the digest value as a bytes object. - """ + """Return the digest value as a bytes object.""" def hexdigest(self) -> str: - """ - Return the digest value as a string of hexadecimal digits. - """ + """Return the digest value as a string of hexadecimal digits.""" def update(self, obj: ReadableBuffer, /) -> None: - """ - Update this hash object's state with the provided string. - """ + """Update this hash object's state with the provided string.""" if sys.version_info >= (3, 10): class UnsupportedDigestmodError(ValueError): ... class HASHXOF(HASH): - """ - A hash is an object used to calculate a checksum of a string of information. + """A hash is an object used to calculate a checksum of a string of information. Methods: @@ -90,19 +80,14 @@ class HASHXOF(HASH): """ def digest(self, length: int) -> bytes: # type: ignore[override] - """ - Return the digest value as a bytes object. - """ + """Return the digest value as a bytes object.""" def hexdigest(self, length: int) -> str: # type: ignore[override] - """ - Return the digest value as a string of hexadecimal digits. - """ + """Return the digest value as a string of hexadecimal digits.""" @final class HMAC: - """ - The object used to calculate HMAC of a message. + """The object used to calculate HMAC of a message. Methods: @@ -124,32 +109,24 @@ class HMAC: @property def name(self) -> str: ... def copy(self) -> Self: - """ - Return a copy ("clone") of the HMAC object. - """ + """Return a copy ("clone") of the HMAC object.""" def digest(self) -> bytes: - """ - Return the digest of the bytes passed to the update() method so far. - """ + """Return the digest of the bytes passed to the update() method so far.""" def hexdigest(self) -> str: - """ - Return hexadecimal digest of the bytes passed to the update() method so far. + """Return hexadecimal digest of the bytes passed to the update() method so far. This may be used to exchange the value safely in email or other non-binary environments. """ def update(self, msg: ReadableBuffer) -> None: - """ - Update the HMAC object with msg. - """ + """Update the HMAC object with msg.""" @overload def compare_digest(a: ReadableBuffer, b: ReadableBuffer, /) -> bool: - """ - Return 'a == b'. + """Return 'a == b'. This function uses an approach designed to prevent timing analysis, making it appropriate for cryptography. @@ -165,8 +142,7 @@ def compare_digest(a: ReadableBuffer, b: ReadableBuffer, /) -> bool: @overload def compare_digest(a: AnyStr, b: AnyStr, /) -> bool: ... def get_fips_mode() -> int: - """ - Determine the OpenSSL FIPS mode of operation. + """Determine the OpenSSL FIPS mode of operation. For OpenSSL 3.0.0 and newer it returns the state of the default provider in the default OSSL context. It's not quite the same as FIPS_mode() but good @@ -177,14 +153,11 @@ def get_fips_mode() -> int: """ def hmac_new(key: bytes | bytearray, msg: ReadableBuffer = b"", digestmod: _DigestMod = None) -> HMAC: - """ - Return a new hmac object. - """ + """Return a new hmac object.""" if sys.version_info >= (3, 13): def new(name: str, data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None) -> HASH: - """ - Return a new hash object using the named algorithm. + """Return a new hash object using the named algorithm. An optional string argument may be provided and will be automatically hashed. @@ -193,81 +166,56 @@ if sys.version_info >= (3, 13): """ def openssl_md5(data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None) -> HASH: - """ - Returns a md5 hash object; optionally initialized with a string - """ + """Returns a md5 hash object; optionally initialized with a string""" def openssl_sha1(data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None) -> HASH: - """ - Returns a sha1 hash object; optionally initialized with a string - """ + """Returns a sha1 hash object; optionally initialized with a string""" def openssl_sha224(data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None) -> HASH: - """ - Returns a sha224 hash object; optionally initialized with a string - """ + """Returns a sha224 hash object; optionally initialized with a string""" def openssl_sha256(data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None) -> HASH: - """ - Returns a sha256 hash object; optionally initialized with a string - """ + """Returns a sha256 hash object; optionally initialized with a string""" def openssl_sha384(data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None) -> HASH: - """ - Returns a sha384 hash object; optionally initialized with a string - """ + """Returns a sha384 hash object; optionally initialized with a string""" def openssl_sha512(data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None) -> HASH: - """ - Returns a sha512 hash object; optionally initialized with a string - """ + """Returns a sha512 hash object; optionally initialized with a string""" def openssl_sha3_224( data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None ) -> HASH: - """ - Returns a sha3-224 hash object; optionally initialized with a string - """ + """Returns a sha3-224 hash object; optionally initialized with a string""" def openssl_sha3_256( data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None ) -> HASH: - """ - Returns a sha3-256 hash object; optionally initialized with a string - """ + """Returns a sha3-256 hash object; optionally initialized with a string""" def openssl_sha3_384( data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None ) -> HASH: - """ - Returns a sha3-384 hash object; optionally initialized with a string - """ + """Returns a sha3-384 hash object; optionally initialized with a string""" def openssl_sha3_512( data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None ) -> HASH: - """ - Returns a sha3-512 hash object; optionally initialized with a string - """ + """Returns a sha3-512 hash object; optionally initialized with a string""" def openssl_shake_128( data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None ) -> HASHXOF: - """ - Returns a shake-128 variable hash object; optionally initialized with a string - """ + """Returns a shake-128 variable hash object; optionally initialized with a string""" def openssl_shake_256( data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None ) -> HASHXOF: - """ - Returns a shake-256 variable hash object; optionally initialized with a string - """ + """Returns a shake-256 variable hash object; optionally initialized with a string""" else: def new(name: str, string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: - """ - Return a new hash object using the named algorithm. + """Return a new hash object using the named algorithm. An optional string argument may be provided and will be automatically hashed. @@ -276,78 +224,48 @@ else: """ def openssl_md5(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: - """ - Returns a md5 hash object; optionally initialized with a string - """ + """Returns a md5 hash object; optionally initialized with a string""" def openssl_sha1(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: - """ - Returns a sha1 hash object; optionally initialized with a string - """ + """Returns a sha1 hash object; optionally initialized with a string""" def openssl_sha224(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: - """ - Returns a sha224 hash object; optionally initialized with a string - """ + """Returns a sha224 hash object; optionally initialized with a string""" def openssl_sha256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: - """ - Returns a sha256 hash object; optionally initialized with a string - """ + """Returns a sha256 hash object; optionally initialized with a string""" def openssl_sha384(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: - """ - Returns a sha384 hash object; optionally initialized with a string - """ + """Returns a sha384 hash object; optionally initialized with a string""" def openssl_sha512(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: - """ - Returns a sha512 hash object; optionally initialized with a string - """ + """Returns a sha512 hash object; optionally initialized with a string""" def openssl_sha3_224(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: - """ - Returns a sha3-224 hash object; optionally initialized with a string - """ + """Returns a sha3-224 hash object; optionally initialized with a string""" def openssl_sha3_256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: - """ - Returns a sha3-256 hash object; optionally initialized with a string - """ + """Returns a sha3-256 hash object; optionally initialized with a string""" def openssl_sha3_384(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: - """ - Returns a sha3-384 hash object; optionally initialized with a string - """ + """Returns a sha3-384 hash object; optionally initialized with a string""" def openssl_sha3_512(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: - """ - Returns a sha3-512 hash object; optionally initialized with a string - """ + """Returns a sha3-512 hash object; optionally initialized with a string""" def openssl_shake_128(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASHXOF: - """ - Returns a shake-128 variable hash object; optionally initialized with a string - """ + """Returns a shake-128 variable hash object; optionally initialized with a string""" def openssl_shake_256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASHXOF: - """ - Returns a shake-256 variable hash object; optionally initialized with a string - """ + """Returns a shake-256 variable hash object; optionally initialized with a string""" def hmac_digest(key: bytes | bytearray, msg: ReadableBuffer, digest: str) -> bytes: - """ - Single-shot HMAC. - """ + """Single-shot HMAC.""" def pbkdf2_hmac( hash_name: str, password: ReadableBuffer, salt: ReadableBuffer, iterations: int, dklen: int | None = None ) -> bytes: - """ - Password based key derivation function 2 (PKCS #5 v2.0) with HMAC as pseudorandom function. - """ + """Password based key derivation function 2 (PKCS #5 v2.0) with HMAC as pseudorandom function.""" def scrypt(password: ReadableBuffer, *, salt: ReadableBuffer, n: int, r: int, p: int, maxmem: int = 0, dklen: int = 64) -> bytes: - """ - scrypt password-based key derivation function. - """ + """scrypt password-based key derivation function.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_heapq.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_heapq.pyi index d846249778..ad18df7cce 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_heapq.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_heapq.pyi @@ -37,31 +37,23 @@ _T = TypeVar("_T") # list items must be comparable __about__: Final[str] def heapify(heap: list[Any], /) -> None: # list items must be comparable - """ - Transform list into a heap, in-place, in O(len(heap)) time. - """ + """Transform list into a heap, in-place, in O(len(heap)) time.""" def heappop(heap: list[_T], /) -> _T: - """ - Pop the smallest item off the heap, maintaining the heap invariant. - """ + """Pop the smallest item off the heap, maintaining the heap invariant.""" def heappush(heap: list[_T], item: _T, /) -> None: - """ - Push item onto heap, maintaining the heap invariant. - """ + """Push item onto heap, maintaining the heap invariant.""" def heappushpop(heap: list[_T], item: _T, /) -> _T: - """ - Push item on the heap, then pop and return the smallest item from the heap. + """Push item on the heap, then pop and return the smallest item from the heap. The combined action runs more efficiently than heappush() followed by a separate call to heappop(). """ def heapreplace(heap: list[_T], item: _T, /) -> _T: - """ - Pop and return the current smallest value, and add the new item. + """Pop and return the current smallest value, and add the new item. This is more efficient than heappop() followed by heappush(), and can be more appropriate when using a fixed-size heap. Note that the value @@ -74,29 +66,20 @@ def heapreplace(heap: list[_T], item: _T, /) -> _T: if sys.version_info >= (3, 14): def heapify_max(heap: list[Any], /) -> None: # list items must be comparable - """ - Maxheap variant of heapify. - """ + """Maxheap variant of heapify.""" def heappop_max(heap: list[_T], /) -> _T: - """ - Maxheap variant of heappop. - """ + """Maxheap variant of heappop.""" def heappush_max(heap: list[_T], item: _T, /) -> None: - """ - Push item onto max heap, maintaining the heap invariant. - """ + """Push item onto max heap, maintaining the heap invariant.""" def heappushpop_max(heap: list[_T], item: _T, /) -> _T: - """ - Maxheap variant of heappushpop. + """Maxheap variant of heappushpop. The combined action runs more efficiently than heappush_max() followed by a separate call to heappop_max(). """ def heapreplace_max(heap: list[_T], item: _T, /) -> _T: - """ - Maxheap variant of heapreplace. - """ + """Maxheap variant of heapreplace.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_imp.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_imp.pyi index f9356d4469..7d8502a7ac 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_imp.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_imp.pyi @@ -14,76 +14,54 @@ if sys.version_info >= (3, 14): def source_hash(key: int, source: ReadableBuffer) -> bytes: ... def create_builtin(spec: ModuleSpec, /) -> types.ModuleType: - """ - Create an extension module. - """ + """Create an extension module.""" def create_dynamic(spec: ModuleSpec, file: Any = None, /) -> types.ModuleType: - """ - Create an extension module. - """ + """Create an extension module.""" def acquire_lock() -> None: - """ - Acquires the interpreter's import lock for the current thread. + """Acquires the interpreter's import lock for the current thread. This lock should be used by import hooks to ensure thread-safety when importing modules. On platforms without threads, this function does nothing. """ def exec_builtin(mod: types.ModuleType, /) -> int: - """ - Initialize a built-in module. - """ + """Initialize a built-in module.""" def exec_dynamic(mod: types.ModuleType, /) -> int: - """ - Initialize an extension module. - """ + """Initialize an extension module.""" def extension_suffixes() -> list[str]: - """ - Returns the list of file suffixes used to identify extension modules. - """ + """Returns the list of file suffixes used to identify extension modules.""" def init_frozen(name: str, /) -> types.ModuleType: - """ - Initializes a frozen module. - """ + """Initializes a frozen module.""" def is_builtin(name: str, /) -> int: - """ - Returns True if the module name corresponds to a built-in module. - """ + """Returns True if the module name corresponds to a built-in module.""" def is_frozen(name: str, /) -> bool: - """ - Returns True if the module name corresponds to a frozen module. - """ + """Returns True if the module name corresponds to a frozen module.""" def is_frozen_package(name: str, /) -> bool: - """ - Returns True if the module name is of a frozen package. - """ + """Returns True if the module name is of a frozen package.""" def lock_held() -> bool: - """ - Return True if the import lock is currently held, else False. + """Return True if the import lock is currently held, else False. On platforms without threads, return False. """ def release_lock() -> None: - """ - Release the interpreter's import lock. + """Release the interpreter's import lock. On platforms without threads, this function does nothing. """ if sys.version_info >= (3, 11): def find_frozen(name: str, /, *, withdata: bool = False) -> tuple[memoryview | None, bool, str | None] | None: - """ - Return info about the corresponding frozen module (if there is one) or None. + """Return info about the corresponding frozen module (if there is one) or None. The returned info (a 2-tuple): @@ -95,12 +73,8 @@ if sys.version_info >= (3, 11): """ def get_frozen_object(name: str, data: ReadableBuffer | None = None, /) -> types.CodeType: - """ - Create a code object for a frozen module. - """ + """Create a code object for a frozen module.""" else: def get_frozen_object(name: str, /) -> types.CodeType: - """ - Create a code object for a frozen module. - """ + """Create a code object for a frozen module.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_interpchannels.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_interpchannels.pyi index 4f772ab3bf..75a40344fe 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_interpchannels.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_interpchannels.pyi @@ -16,41 +16,29 @@ class ChannelNotFoundError(ChannelError): ... # Mark as final, since instantiating ChannelID is not supported. @final class ChannelID: - """ - A channel ID identifies a channel and may be used as an int. - """ + """A channel ID identifies a channel and may be used as an int.""" @property def end(self) -> Literal["send", "recv", "both"]: - """ - 'send', 'recv', or 'both' - """ + """'send', 'recv', or 'both'""" @property def send(self) -> Self: - """ - the 'send' end of the channel - """ + """the 'send' end of the channel""" @property def recv(self) -> Self: - """ - the 'recv' end of the channel - """ + """the 'recv' end of the channel""" def __eq__(self, other: object) -> bool: ... def __ge__(self, other: ChannelID) -> bool: ... def __gt__(self, other: ChannelID) -> bool: ... def __hash__(self) -> int: ... def __index__(self) -> int: - """ - Return self converted to an integer, if self is suitable for use as an index into a list. - """ + """Return self converted to an integer, if self is suitable for use as an index into a list.""" def __int__(self) -> int: - """ - int(self) - """ + """int(self)""" def __le__(self, other: ChannelID) -> bool: ... def __lt__(self, other: ChannelID) -> bool: ... @@ -58,8 +46,7 @@ class ChannelID: @final class ChannelInfo(structseq[int], tuple[bool, bool, bool, int, int, int, int, int]): - """ - ChannelInfo + """ChannelInfo A named tuple of a channel's state. """ @@ -76,125 +63,89 @@ class ChannelInfo(structseq[int], tuple[bool, bool, bool, int, int, int, int, in ) @property def open(self) -> bool: - """ - both ends are open - """ + """both ends are open""" @property def closing(self) -> bool: - """ - send is closed, recv is non-empty - """ + """send is closed, recv is non-empty""" @property def closed(self) -> bool: - """ - both ends are closed - """ + """both ends are closed""" @property def count(self) -> int: # type: ignore[override] - """ - queued objects - """ + """queued objects""" @property def num_interp_send(self) -> int: - """ - interpreters bound to the send end - """ + """interpreters bound to the send end""" @property def num_interp_send_released(self) -> int: - """ - interpreters bound to the send end and released - """ + """interpreters bound to the send end and released""" @property def num_interp_recv(self) -> int: - """ - interpreters bound to the send end - """ + """interpreters bound to the send end""" @property def num_interp_recv_released(self) -> int: - """ - interpreters bound to the send end and released - """ + """interpreters bound to the send end and released""" @property def num_interp_both(self) -> int: - """ - interpreters bound to both ends - """ + """interpreters bound to both ends""" @property def num_interp_both_recv_released(self) -> int: - """ - interpreters bound to both ends and released_from_the recv end - """ + """interpreters bound to both ends and released_from_the recv end""" @property def num_interp_both_send_released(self) -> int: - """ - interpreters bound to both ends and released_from_the send end - """ + """interpreters bound to both ends and released_from_the send end""" @property def num_interp_both_released(self) -> int: - """ - interpreters bound to both ends and released_from_both - """ + """interpreters bound to both ends and released_from_both""" @property def recv_associated(self) -> bool: - """ - current interpreter is bound to the recv end - """ + """current interpreter is bound to the recv end""" @property def recv_released(self) -> bool: - """ - current interpreter *was* bound to the recv end - """ + """current interpreter *was* bound to the recv end""" @property def send_associated(self) -> bool: - """ - current interpreter is bound to the send end - """ + """current interpreter is bound to the send end""" @property def send_released(self) -> bool: - """ - current interpreter *was* bound to the send end - """ + """current interpreter *was* bound to the send end""" def create(unboundop: Literal[1, 2, 3]) -> ChannelID: - """ - channel_create(unboundop) -> cid + """channel_create(unboundop) -> cid Create a new cross-interpreter channel and return a unique generated ID. """ def destroy(cid: SupportsIndex) -> None: - """ - channel_destroy(cid) + """channel_destroy(cid) Close and finalize the channel. Afterward attempts to use the channel will behave as though it never existed. """ def list_all() -> list[ChannelID]: - """ - channel_list_all() -> [cid] + """channel_list_all() -> [cid] Return the list of all IDs for active channels. """ def list_interpreters(cid: SupportsIndex, *, send: bool) -> list[int]: - """ - channel_list_interpreters(cid, *, send) -> [id] + """channel_list_interpreters(cid, *, send) -> [id] Return the list of all interpreter IDs associated with an end of the channel. @@ -203,24 +154,21 @@ def list_interpreters(cid: SupportsIndex, *, send: bool) -> list[int]: """ def send(cid: SupportsIndex, obj: object, *, blocking: bool = True, timeout: float | None = None) -> None: - """ - channel_send(cid, obj, *, blocking=True, timeout=None) + """channel_send(cid, obj, *, blocking=True, timeout=None) Add the object's data to the channel's queue. By default this waits for the object to be received. """ def send_buffer(cid: SupportsIndex, obj: Buffer, *, blocking: bool = True, timeout: float | None = None) -> None: - """ - channel_send_buffer(cid, obj, *, blocking=True, timeout=None) + """channel_send_buffer(cid, obj, *, blocking=True, timeout=None) Add the object's buffer to the channel's queue. By default this waits for the object to be received. """ def recv(cid: SupportsIndex, default: object = ...) -> tuple[Any, Literal[1, 2, 3]]: - """ - channel_recv(cid, [default]) -> (obj, unboundop) + """channel_recv(cid, [default]) -> (obj, unboundop) Return a new object from the data at the front of the channel's queue. @@ -229,8 +177,7 @@ def recv(cid: SupportsIndex, default: object = ...) -> tuple[Any, Literal[1, 2, """ def close(cid: SupportsIndex, *, send: bool = False, recv: bool = False) -> None: - """ - channel_close(cid, *, send=None, recv=None, force=False) + """channel_close(cid, *, send=None, recv=None, force=False) Close the channel for all interpreters. @@ -258,29 +205,25 @@ def close(cid: SupportsIndex, *, send: bool = False, recv: bool = False) -> None """ def get_count(cid: SupportsIndex) -> int: - """ - get_count(cid) + """get_count(cid) Return the number of items in the channel. """ def get_info(cid: SupportsIndex) -> ChannelInfo: - """ - get_info(cid) + """get_info(cid) Return details about the channel. """ def get_channel_defaults(cid: SupportsIndex) -> Literal[1, 2, 3]: - """ - get_channel_defaults(cid) + """get_channel_defaults(cid) Return the channel's default values, set when it was created. """ def release(cid: SupportsIndex, *, send: bool = False, recv: bool = False, force: bool = False) -> None: - """ - channel_release(cid, *, send=None, recv=None, force=True) + """channel_release(cid, *, send=None, recv=None, force=True) Close the channel for the current interpreter. 'send' and 'recv' (bool) may be used to indicate the ends to close. By default both diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_interpqueues.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_interpqueues.pyi index 4113faf29d..63a7e5a238 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_interpqueues.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_interpqueues.pyi @@ -9,23 +9,19 @@ from typing_extensions import TypeAlias _UnboundOp: TypeAlias = Literal[1, 2, 3] class QueueError(RuntimeError): - """ - Indicates that a queue-related error happened. - """ + """Indicates that a queue-related error happened.""" class QueueNotFoundError(QueueError): ... def bind(qid: SupportsIndex) -> None: - """ - bind(qid) + """bind(qid) Take a reference to the identified queue. The queue is not destroyed until there are no references left. """ def create(maxsize: SupportsIndex, fmt: SupportsIndex, unboundop: _UnboundOp) -> int: - """ - create(maxsize, unboundop, fallback) -> qid + """create(maxsize, unboundop, fallback) -> qid Create a new cross-interpreter queue and return its unique generated ID. It is a new reference as though bind() had been called on the queue. @@ -35,16 +31,14 @@ def create(maxsize: SupportsIndex, fmt: SupportsIndex, unboundop: _UnboundOp) -> """ def destroy(qid: SupportsIndex) -> None: - """ - destroy(qid) + """destroy(qid) Clear and destroy the queue. Afterward attempts to use the queue will behave as though it never existed. """ def get(qid: SupportsIndex) -> tuple[Any, int, _UnboundOp | None]: - """ - get(qid) -> (obj, unboundop) + """get(qid) -> (obj, unboundop) Return a new object from the data at the front of the queue. The unbound op is also returned. @@ -53,51 +47,44 @@ def get(qid: SupportsIndex) -> tuple[Any, int, _UnboundOp | None]: """ def get_count(qid: SupportsIndex) -> int: - """ - get_count(qid) + """get_count(qid) Return the number of items in the queue. """ def get_maxsize(qid: SupportsIndex) -> int: - """ - get_maxsize(qid) + """get_maxsize(qid) Return the maximum number of items in the queue. """ def get_queue_defaults(qid: SupportsIndex) -> tuple[int, _UnboundOp]: - """ - get_queue_defaults(qid) + """get_queue_defaults(qid) Return the queue's default values, set when it was created. """ def is_full(qid: SupportsIndex) -> bool: - """ - is_full(qid) + """is_full(qid) Return true if the queue has a maxsize and has reached it. """ def list_all() -> list[tuple[int, int, _UnboundOp]]: - """ - list_all() -> [(qid, unboundop, fallback)] + """list_all() -> [(qid, unboundop, fallback)] Return the list of IDs for all queues. Each corresponding default unbound op and fallback is also included. """ def put(qid: SupportsIndex, obj: Any, fmt: SupportsIndex, unboundop: _UnboundOp) -> None: - """ - put(qid, obj) + """put(qid, obj) Add the object's data to the queue. """ def release(qid: SupportsIndex) -> None: - """ - release(qid) + """release(qid) Release a reference to the queue. The queue is destroyed once there are no references left. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_interpreters.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_interpreters.pyi index ce616ffb5b..7c13fbd076 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_interpreters.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_interpreters.pyi @@ -12,26 +12,19 @@ _Configs: TypeAlias = Literal["default", "isolated", "legacy", "empty", ""] _SharedDict: TypeAlias = dict[str, Any] # many objects can be shared class InterpreterError(Exception): - """ - A cross-interpreter operation failed - """ + """A cross-interpreter operation failed""" class InterpreterNotFoundError(InterpreterError): - """ - An interpreter was not found - """ + """An interpreter was not found""" class NotShareableError(ValueError): ... class CrossInterpreterBufferView: def __buffer__(self, flags: int, /) -> memoryview: - """ - Return a buffer object that exposes the underlying memory of the object. - """ + """Return a buffer object that exposes the underlying memory of the object.""" def new_config(name: _Configs = "isolated", /, **overides: object) -> types.SimpleNamespace: - """ - new_config(name='isolated', /, **overrides) -> type.SimpleNamespace + """new_config(name='isolated', /, **overrides) -> type.SimpleNamespace Return a representation of a new PyInterpreterConfig. @@ -43,8 +36,7 @@ def new_config(name: _Configs = "isolated", /, **overides: object) -> types.Simp """ def create(config: types.SimpleNamespace | _Configs | None = "isolated", *, reqrefs: bool = False) -> int: - """ - create([config], *, reqrefs=False) -> ID + """create([config], *, reqrefs=False) -> ID Create a new interpreter and return a unique generated ID. @@ -59,8 +51,7 @@ def create(config: types.SimpleNamespace | _Configs | None = "isolated", *, reqr """ def destroy(id: SupportsIndex, *, restrict: bool = False) -> None: - """ - destroy(id, *, restrict=False) + """destroy(id, *, restrict=False) Destroy the identified interpreter. @@ -69,43 +60,37 @@ def destroy(id: SupportsIndex, *, restrict: bool = False) -> None: """ def list_all(*, require_ready: bool) -> list[tuple[int, int]]: - """ - list_all() -> [(ID, whence)] + """list_all() -> [(ID, whence)] Return a list containing the ID of every existing interpreter. """ def get_current() -> tuple[int, int]: - """ - get_current() -> (ID, whence) + """get_current() -> (ID, whence) Return the ID of current interpreter. """ def get_main() -> tuple[int, int]: - """ - get_main() -> (ID, whence) + """get_main() -> (ID, whence) Return the ID of main interpreter. """ def is_running(id: SupportsIndex, *, restrict: bool = False) -> bool: - """ - is_running(id, *, restrict=False) -> bool + """is_running(id, *, restrict=False) -> bool Return whether or not the identified interpreter is running. """ def get_config(id: SupportsIndex, *, restrict: bool = False) -> types.SimpleNamespace: - """ - get_config(id, *, restrict=False) -> types.SimpleNamespace + """get_config(id, *, restrict=False) -> types.SimpleNamespace Return a representation of the config used to initialize the interpreter. """ def whence(id: SupportsIndex) -> int: - """ - whence(id) -> int + """whence(id) -> int Return an identifier for where the interpreter was created. """ @@ -117,8 +102,7 @@ def exec( *, restrict: bool = False, ) -> None | types.SimpleNamespace: - """ - exec(id, code, shared=None, *, restrict=False) + """exec(id, code, shared=None, *, restrict=False) Execute the provided code in the identified interpreter. This is equivalent to running the builtin exec() under the target @@ -143,8 +127,7 @@ def call( *, restrict: bool = False, ) -> object: - """ - call(id, callable, args=None, kwargs=None, *, restrict=False) + """call(id, callable, args=None, kwargs=None, *, restrict=False) Call the provided object in the identified interpreter. Pass the given args and kwargs, if possible. @@ -157,8 +140,7 @@ def run_string( *, restrict: bool = False, ) -> None: - """ - run_string(id, script, shared=None, *, restrict=False) + """run_string(id, script, shared=None, *, restrict=False) Execute the provided string in the identified interpreter. @@ -168,8 +150,7 @@ def run_string( def run_func( id: SupportsIndex, func: types.CodeType | Callable[[], object], shared: _SharedDict | None = None, *, restrict: bool = False ) -> None: - """ - run_func(id, func, shared=None, *, restrict=False) + """run_func(id, func, shared=None, *, restrict=False) Execute the body of the provided function in the identified interpreter. Code objects are also supported. In both cases, closures and args @@ -179,8 +160,7 @@ def run_func( """ def set___main___attrs(id: SupportsIndex, updates: _SharedDict, *, restrict: bool = False) -> None: - """ - set___main___attrs(id, ns, *, restrict=False) + """set___main___attrs(id, ns, *, restrict=False) Bind the given attributes in the interpreter's __main__ module. """ @@ -188,16 +168,14 @@ def set___main___attrs(id: SupportsIndex, updates: _SharedDict, *, restrict: boo def incref(id: SupportsIndex, *, implieslink: bool = False, restrict: bool = False) -> None: ... def decref(id: SupportsIndex, *, restrict: bool = False) -> None: ... def is_shareable(obj: object) -> bool: - """ - is_shareable(obj) -> bool + """is_shareable(obj) -> bool Return True if the object's data may be shared between interpreters and False otherwise. """ def capture_exception(exc: BaseException | None = None) -> types.SimpleNamespace: - """ - capture_exception(exc=None) -> types.SimpleNamespace + """capture_exception(exc=None) -> types.SimpleNamespace Return a snapshot of an exception. If "exc" is None then the current exception, if any, is used (but not cleared). diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_io.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_io.pyi index 471415d8cf..fb53ca1171 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_io.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_io.pyi @@ -51,8 +51,7 @@ DEFAULT_BUFFER_SIZE: Final = 8192 open = builtins.open def open_code(path: str) -> IO[bytes]: - """ - Opens the provided file with the intent to import the contents. + """Opens the provided file with the intent to import the contents. This may perform extra validation beyond open(), but is otherwise interchangeable with calling open(path, 'rb'). @@ -61,8 +60,7 @@ def open_code(path: str) -> IO[bytes]: BlockingIOError = builtins.BlockingIOError class _IOBase: - """ - The abstract base class for all I/O classes. + """The abstract base class for all I/O classes. This class provides dummy implementations for many methods that derived classes can override selectively; the default implementations @@ -94,57 +92,47 @@ class _IOBase: """ def __iter__(self) -> Iterator[bytes]: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> bytes: - """ - Implement next(self). - """ + """Implement next(self).""" def __enter__(self) -> Self: ... def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... def close(self) -> None: - """ - Flush and close the IO object. + """Flush and close the IO object. This method has no effect if the file is already closed. """ def fileno(self) -> int: - """ - Return underlying file descriptor if one exists. + """Return underlying file descriptor if one exists. Raise OSError if the IO object does not use a file descriptor. """ def flush(self) -> None: - """ - Flush write buffers, if applicable. + """Flush write buffers, if applicable. This is not implemented for read-only and non-blocking streams. """ def isatty(self) -> bool: - """ - Return whether this is an 'interactive' stream. + """Return whether this is an 'interactive' stream. Return False if it can't be determined. """ def readable(self) -> bool: - """ - Return whether object was opened for reading. + """Return whether object was opened for reading. If False, read() will raise OSError. """ read: Callable[..., Any] def readlines(self, hint: int = -1, /) -> list[bytes]: - """ - Return a list of lines from the stream. + """Return a list of lines from the stream. hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all @@ -152,8 +140,7 @@ class _IOBase: """ def seek(self, offset: int, whence: int = 0, /) -> int: - """ - Change the stream position to the given byte offset. + """Change the stream position to the given byte offset. offset The stream position, relative to 'whence'. @@ -171,44 +158,37 @@ class _IOBase: """ def seekable(self) -> bool: - """ - Return whether object supports random access. + """Return whether object supports random access. If False, seek(), tell() and truncate() will raise OSError. This method may need to do a test seek(). """ def tell(self) -> int: - """ - Return current stream position. - """ + """Return current stream position.""" def truncate(self, size: int | None = None, /) -> int: - """ - Truncate file to size bytes. + """Truncate file to size bytes. File pointer is left unchanged. Size defaults to the current IO position as reported by tell(). Return the new size. """ def writable(self) -> bool: - """ - Return whether object was opened for writing. + """Return whether object was opened for writing. If False, write() will raise OSError. """ write: Callable[..., Any] def writelines(self, lines: Iterable[ReadableBuffer], /) -> None: - """ - Write a list of lines to stream. + """Write a list of lines to stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end. """ def readline(self, size: int | None = -1, /) -> bytes: - """ - Read and return a line from the stream. + """Read and return a line from the stream. If size is specified, at most size bytes will be read. @@ -218,23 +198,17 @@ class _IOBase: """ def __del__(self) -> None: - """ - Called when the instance is about to be destroyed. - """ + """Called when the instance is about to be destroyed.""" @property def closed(self) -> bool: ... def _checkClosed(self) -> None: ... # undocumented class _RawIOBase(_IOBase): - """ - Base class for raw binary I/O. - """ + """Base class for raw binary I/O.""" def readall(self) -> bytes: - """ - Read until EOF, using multiple read() call. - """ + """Read until EOF, using multiple read() call.""" # The following methods can return None if the file is in non-blocking mode # and no data is available. def readinto(self, buffer: WriteableBuffer, /) -> int | MaybeNone: ... @@ -242,8 +216,7 @@ class _RawIOBase(_IOBase): def read(self, size: int = -1, /) -> bytes | MaybeNone: ... class _BufferedIOBase(_IOBase): - """ - Base class for buffered IO objects. + """Base class for buffered IO objects. The main difference with RawIOBase is that the read() method supports omitting the size argument, and does not have a default @@ -259,8 +232,7 @@ class _BufferedIOBase(_IOBase): """ def detach(self) -> RawIOBase: - """ - Disconnect this buffer from its underlying raw stream and return it. + """Disconnect this buffer from its underlying raw stream and return it. After the raw stream has been detached, the buffer is in an unusable state. @@ -268,8 +240,7 @@ class _BufferedIOBase(_IOBase): def readinto(self, buffer: WriteableBuffer, /) -> int: ... def write(self, buffer: ReadableBuffer, /) -> int: - """ - Write buffer b to the IO stream. + """Write buffer b to the IO stream. Return the number of bytes written, which is always the length of b in bytes. @@ -280,8 +251,7 @@ class _BufferedIOBase(_IOBase): def readinto1(self, buffer: WriteableBuffer, /) -> int: ... def read(self, size: int | None = -1, /) -> bytes: - """ - Read and return up to n bytes. + """Read and return up to n bytes. If the size argument is omitted, None, or negative, read and return all data until EOF. @@ -300,16 +270,14 @@ class _BufferedIOBase(_IOBase): """ def read1(self, size: int = -1, /) -> bytes: - """ - Read and return up to size bytes, with at most one read() call to the underlying raw stream. + """Read and return up to size bytes, with at most one read() call to the underlying raw stream. Return an empty bytes object on EOF. A short result does not imply that EOF is imminent. """ class FileIO(RawIOBase, _RawIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of writelines in the base classes - """ - Open a file. + """Open a file. The mode can be 'r' (default), 'w', 'x' or 'a' for reading, writing, exclusive creation or appending. The file will be created if it @@ -334,13 +302,10 @@ class FileIO(RawIOBase, _RawIOBase, BinaryIO): # type: ignore[misc] # incompat ) -> None: ... @property def closefd(self) -> bool: - """ - True if the file descriptor will be closed by close(). - """ + """True if the file descriptor will be closed by close().""" def seek(self, pos: int, whence: int = 0, /) -> int: - """ - Move to new file position and return the file position. + """Move to new file position and return the file position. Argument offset is a byte count. Optional argument whence defaults to SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values @@ -352,8 +317,7 @@ class FileIO(RawIOBase, _RawIOBase, BinaryIO): # type: ignore[misc] # incompat """ def read(self, size: int | None = -1, /) -> bytes | MaybeNone: - """ - Read at most size bytes, returned as bytes. + """Read at most size bytes, returned as bytes. If size is less than 0, read all bytes in the file making multiple read calls. See ``FileIO.readall``. @@ -366,9 +330,7 @@ class FileIO(RawIOBase, _RawIOBase, BinaryIO): # type: ignore[misc] # incompat """ class BytesIO(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of methods in the base classes - """ - Buffered I/O implementation using an in-memory bytes buffer. - """ + """Buffered I/O implementation using an in-memory bytes buffer.""" def __init__(self, initial_bytes: ReadableBuffer = b"") -> None: ... # BytesIO does not contain a "name" field. This workaround is necessary @@ -376,26 +338,20 @@ class BytesIO(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # as a read-only property on IO[]. name: Any def getvalue(self) -> bytes: - """ - Retrieve the entire contents of the BytesIO object. - """ + """Retrieve the entire contents of the BytesIO object.""" def getbuffer(self) -> memoryview: - """ - Get a read-write view over the contents of the BytesIO object. - """ + """Get a read-write view over the contents of the BytesIO object.""" def read1(self, size: int | None = -1, /) -> bytes: - """ - Read at most size bytes, returned as a bytes object. + """Read at most size bytes, returned as a bytes object. If the size argument is negative or omitted, read until EOF is reached. Return an empty bytes object at EOF. """ def readlines(self, size: int | None = None, /) -> list[bytes]: - """ - List of bytes objects, each a line from the file. + """List of bytes objects, each a line from the file. Call readline() repeatedly and return a list of the lines so read. The optional size argument, if given, is an approximate bound on the @@ -403,8 +359,7 @@ class BytesIO(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] """ def seek(self, pos: int, whence: int = 0, /) -> int: - """ - Change stream position. + """Change stream position. Seek to byte offset pos relative to position indicated by whence: 0 Start of stream (the default). pos should be >= 0; @@ -441,9 +396,7 @@ class _BufferedReaderStream(Protocol): _BufferedReaderStreamT = TypeVar("_BufferedReaderStreamT", bound=_BufferedReaderStream, default=_BufferedReaderStream) class BufferedReader(BufferedIOBase, _BufferedIOBase, BinaryIO, Generic[_BufferedReaderStreamT]): # type: ignore[misc] # incompatible definitions of methods in the base classes - """ - Create a new buffered reader using the given readable raw IO object. - """ + """Create a new buffered reader using the given readable raw IO object.""" raw: _BufferedReaderStreamT def __init__(self, raw: _BufferedReaderStreamT, buffer_size: int = 8192) -> None: ... @@ -452,8 +405,7 @@ class BufferedReader(BufferedIOBase, _BufferedIOBase, BinaryIO, Generic[_Buffere def truncate(self, pos: int | None = None, /) -> int: ... class BufferedWriter(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of writelines in the base classes - """ - A buffer for a writeable sequential RawIO object. + """A buffer for a writeable sequential RawIO object. The constructor creates a BufferedWriter for the given writeable raw stream. If the buffer_size is not given, it defaults to @@ -467,8 +419,7 @@ class BufferedWriter(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore def truncate(self, pos: int | None = None, /) -> int: ... class BufferedRandom(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of methods in the base classes - """ - A buffered interface to random access streams. + """A buffered interface to random access streams. The constructor creates a reader and writer for a seekable stream, raw, given in the first argument. If the buffer_size is omitted it @@ -484,8 +435,7 @@ class BufferedRandom(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore def truncate(self, pos: int | None = None, /) -> int: ... class BufferedRWPair(BufferedIOBase, _BufferedIOBase, Generic[_BufferedReaderStreamT]): - """ - A buffered reader and writer object together. + """A buffered reader and writer object together. A buffered reader object and buffered writer object put together to form a sequential IO object that can read and write. This is typically @@ -500,8 +450,7 @@ class BufferedRWPair(BufferedIOBase, _BufferedIOBase, Generic[_BufferedReaderStr def peek(self, size: int = 0, /) -> bytes: ... class _TextIOBase(_IOBase): - """ - Base class for text I/O. + """Base class for text I/O. This class provides a character and line based interface to stream I/O. There is no readinto method because Python's character strings @@ -512,49 +461,40 @@ class _TextIOBase(_IOBase): errors: str | None newlines: str | tuple[str, ...] | None def __iter__(self) -> Iterator[str]: # type: ignore[override] - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> str: # type: ignore[override] - """ - Implement next(self). - """ + """Implement next(self).""" def detach(self) -> BinaryIO: - """ - Separate the underlying buffer from the TextIOBase and return it. + """Separate the underlying buffer from the TextIOBase and return it. After the underlying buffer has been detached, the TextIO is in an unusable state. """ def write(self, s: str, /) -> int: - """ - Write string s to stream. + """Write string s to stream. Return the number of characters written (which is always equal to the length of the string). """ def writelines(self, lines: Iterable[str], /) -> None: # type: ignore[override] - """ - Write a list of lines to stream. + """Write a list of lines to stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end. """ def readline(self, size: int = -1, /) -> str: # type: ignore[override] - """ - Read until newline or EOF. + """Read until newline or EOF. Return an empty string if EOF is hit immediately. If size is specified, at most size characters will be read. """ def readlines(self, hint: int = -1, /) -> list[str]: # type: ignore[override] - """ - Return a list of lines from the stream. + """Return a list of lines from the stream. hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all @@ -562,8 +502,7 @@ class _TextIOBase(_IOBase): """ def read(self, size: int | None = -1, /) -> str: - """ - Read at most size characters from stream. + """Read at most size characters from stream. Read from underlying buffer until we have size characters or we hit EOF. If size is negative or omitted, read until EOF. @@ -595,8 +534,7 @@ class _WrappedBuffer(Protocol): _BufferT_co = TypeVar("_BufferT_co", bound=_WrappedBuffer, default=_WrappedBuffer, covariant=True) class TextIOWrapper(TextIOBase, _TextIOBase, TextIO, Generic[_BufferT_co]): # type: ignore[misc] # incompatible definitions of write in the base classes - """ - Character and line based layer over a BufferedIOBase object, buffer. + """Character and line based layer over a BufferedIOBase object, buffer. encoding gives the name of the encoding that the stream will be decoded or encoded with. It defaults to locale.getencoding(). @@ -651,8 +589,7 @@ class TextIOWrapper(TextIOBase, _TextIOBase, TextIO, Generic[_BufferT_co]): # t line_buffering: bool | None = None, write_through: bool | None = None, ) -> None: - """ - Reconfigure the text stream with new parameters. + """Reconfigure the text stream with new parameters. This also does an implicit stream flush. """ @@ -663,8 +600,7 @@ class TextIOWrapper(TextIOBase, _TextIOBase, TextIO, Generic[_BufferT_co]): # t # TextIOWrapper's version of seek only supports a limited subset of # operations. def seek(self, cookie: int, whence: int = 0, /) -> int: - """ - Set the stream position, and return the new stream position. + """Set the stream position, and return the new stream position. cookie Zero or an opaque number returned by tell(). @@ -687,8 +623,7 @@ class TextIOWrapper(TextIOBase, _TextIOBase, TextIO, Generic[_BufferT_co]): # t def truncate(self, pos: int | None = None, /) -> int: ... class StringIO(TextIOBase, _TextIOBase, TextIO): # type: ignore[misc] # incompatible definitions of write in the base classes - """ - Text I/O implementation using an in-memory buffer. + """Text I/O implementation using an in-memory buffer. The initial_value argument sets the value of object. The newline argument is like the one of TextIOWrapper's constructor. @@ -700,15 +635,12 @@ class StringIO(TextIOBase, _TextIOBase, TextIO): # type: ignore[misc] # incomp # as a read-only property on IO[]. name: Any def getvalue(self) -> str: - """ - Retrieve the entire contents of the object. - """ + """Retrieve the entire contents of the object.""" @property def line_buffering(self) -> bool: ... def seek(self, pos: int, whence: int = 0, /) -> int: - """ - Change stream position. + """Change stream position. Seek to character offset pos relative to position indicated by whence: 0 Start of stream (the default). pos should be >= 0; @@ -718,8 +650,7 @@ class StringIO(TextIOBase, _TextIOBase, TextIO): # type: ignore[misc] # incomp """ def truncate(self, pos: int | None = None, /) -> int: - """ - Truncate size to pos. + """Truncate size to pos. The pos argument defaults to the current file position, as returned by tell(). The current file position is unchanged. @@ -727,8 +658,7 @@ class StringIO(TextIOBase, _TextIOBase, TextIO): # type: ignore[misc] # incomp """ class IncrementalNewlineDecoder: - """ - Codec used when reading a file in universal newlines mode. + """Codec used when reading a file in universal newlines mode. It wraps another incremental decoder, translating \\r\\n and \\r into \\n. It also records the types of newlines encountered. When used with @@ -749,8 +679,7 @@ class IncrementalNewlineDecoder: if sys.version_info >= (3, 10): @overload def text_encoding(encoding: None, stacklevel: int = 2, /) -> Literal["locale", "utf-8"]: - """ - A helper function to choose the text encoding. + """A helper function to choose the text encoding. When encoding is not None, this function returns it. Otherwise, this function returns the default text encoding diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_json.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_json.pyi index eb893c4959..cd3c3eba5b 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_json.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_json.pyi @@ -8,57 +8,39 @@ from typing_extensions import Self @final class make_encoder: - """ - Encoder(markers, default, encoder, indent, key_separator, item_separator, sort_keys, skipkeys, allow_nan) - """ + """Encoder(markers, default, encoder, indent, key_separator, item_separator, sort_keys, skipkeys, allow_nan)""" @property def sort_keys(self) -> bool: - """ - sort_keys - """ + """sort_keys""" @property def skipkeys(self) -> bool: - """ - skipkeys - """ + """skipkeys""" @property def key_separator(self) -> str: - """ - key_separator - """ + """key_separator""" @property def indent(self) -> str | None: - """ - indent - """ + """indent""" @property def markers(self) -> dict[int, Any] | None: - """ - markers - """ + """markers""" @property def default(self) -> Callable[[Any], Any]: - """ - default - """ + """default""" @property def encoder(self) -> Callable[[str], str]: - """ - encoder - """ + """encoder""" @property def item_separator(self) -> str: - """ - item_separator - """ + """item_separator""" def __new__( cls, @@ -73,15 +55,11 @@ class make_encoder: allow_nan: bool, ) -> Self: ... def __call__(self, obj: object, _current_indent_level: int) -> Any: - """ - Call self as a function. - """ + """Call self as a function.""" @final class make_scanner: - """ - JSON scanner object - """ + """JSON scanner object""" object_hook: Any object_pairs_hook: Any @@ -92,27 +70,22 @@ class make_scanner: # TODO: 'context' needs the attrs above (ducktype), but not __call__. def __new__(cls, context: make_scanner) -> Self: ... def __call__(self, string: str, index: int) -> tuple[Any, int]: - """ - Call self as a function. - """ + """Call self as a function.""" def encode_basestring(s: str, /) -> str: - """ - encode_basestring(string) -> string + """encode_basestring(string) -> string Return a JSON representation of a Python string """ def encode_basestring_ascii(s: str, /) -> str: - """ - encode_basestring_ascii(string) -> string + """encode_basestring_ascii(string) -> string Return an ASCII-only JSON representation of a Python string """ def scanstring(string: str, end: int, strict: bool = ...) -> tuple[str, int]: - """ - scanstring(string, end, strict=True) -> (string, end) + """scanstring(string, end, strict=True) -> (string, end) Scan the string s for a JSON string. End is the index of the character in s after the quote that started the JSON string. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_locale.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_locale.pyi index d6475250fc..f0973adc8e 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_locale.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_locale.pyi @@ -36,30 +36,20 @@ LC_ALL: Final[int] CHAR_MAX: Final = 127 def setlocale(category: int, locale: str | None = None, /) -> str: - """ - Activates/queries locale processing. - """ + """Activates/queries locale processing.""" def localeconv() -> _LocaleConv: - """ - Returns numeric and monetary locale-specific parameters. - """ + """Returns numeric and monetary locale-specific parameters.""" if sys.version_info >= (3, 11): def getencoding() -> str: - """ - Get the current locale encoding. - """ + """Get the current locale encoding.""" def strcoll(os1: str, os2: str, /) -> int: - """ - Compares two strings according to the locale. - """ + """Compares two strings according to the locale.""" def strxfrm(string: str, /) -> str: - """ - Return a string that can be used as a key for locale-aware comparisons. - """ + """Return a string that can be used as a key for locale-aware comparisons.""" # native gettext functions # https://docs.python.org/3/library/locale.html#access-to-message-catalogs @@ -130,42 +120,30 @@ if sys.platform != "win32": ALT_DIGITS: Final[int] def nl_langinfo(key: int, /) -> str: - """ - Return the value for the locale information associated with key. - """ + """Return the value for the locale information associated with key.""" # This is dependent on `libintl.h` which is a part of `gettext` # system dependency. These functions might be missing. # But, we always say that they are present. def gettext(msg: str, /) -> str: - """ - gettext(msg) -> string + """gettext(msg) -> string Return translation of msg. """ def dgettext(domain: str | None, msg: str, /) -> str: - """ - dgettext(domain, msg) -> string + """dgettext(domain, msg) -> string Return translation of msg in domain. """ def dcgettext(domain: str | None, msg: str, category: int, /) -> str: - """ - Return translation of msg in domain and category. - """ + """Return translation of msg in domain and category.""" def textdomain(domain: str | None, /) -> str: - """ - Set the C library's textdmain to domain, returning the new domain. - """ + """Set the C library's textdmain to domain, returning the new domain.""" def bindtextdomain(domain: str, dir: StrPath | None, /) -> str: - """ - Bind the C library's domain to dir. - """ + """Bind the C library's domain to dir.""" def bind_textdomain_codeset(domain: str, codeset: str | None, /) -> str | None: - """ - Bind the C library's domain to codeset. - """ + """Bind the C library's domain to codeset.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_lsprof.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_lsprof.pyi index a90edd3f5b..f24d3c356f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_lsprof.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_lsprof.pyi @@ -9,8 +9,7 @@ from types import CodeType from typing import Any, Final, final class Profiler: - """ - Build a profiler object using the specified timer function. + """Build a profiler object using the specified timer function. The default timer is a fast built-in one based on real time. For custom timer functions returning integers, 'timeunit' can @@ -22,8 +21,7 @@ class Profiler: self, timer: Callable[[], float] | None = None, timeunit: float = 0.0, subcalls: bool = True, builtins: bool = True ) -> None: ... def getstats(self) -> list[profiler_entry]: - """ - list of profiler_entry objects. + """list of profiler_entry objects. getstats() -> list of profiler_entry objects @@ -49,8 +47,7 @@ class Profiler: """ def enable(self, subcalls: bool = True, builtins: bool = True) -> None: - """ - Start collecting profiling information. + """Start collecting profiling information. subcalls If True, also records for each function @@ -61,14 +58,10 @@ class Profiler: """ def disable(self) -> None: - """ - Stop collecting profiling information. - """ + """Stop collecting profiling information.""" def clear(self) -> None: - """ - Clear all profiling information collected so far. - """ + """Clear all profiling information collected so far.""" @final class profiler_entry(structseq[Any], tuple[CodeType | str, int, int, float, float, list[profiler_subentry]]): diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_lzma.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_lzma.pyi index 38cbc51b3a..b3b9746cbd 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_lzma.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_lzma.pyi @@ -37,8 +37,7 @@ PRESET_EXTREME: int # v big number @final class LZMADecompressor: - """ - Create a decompressor object for decompressing data incrementally. + """Create a decompressor object for decompressing data incrementally. format Specifies the container format of the input stream. If this is @@ -64,8 +63,7 @@ class LZMADecompressor: def __init__(self, format: int | None = ..., memlimit: int | None = ..., filters: _FilterChain | None = ...) -> None: ... def decompress(self, data: ReadableBuffer, max_length: int = -1) -> bytes: - """ - Decompress *data*, returning uncompressed data as bytes. + """Decompress *data*, returning uncompressed data as bytes. If *max_length* is nonnegative, returns at most *max_length* bytes of decompressed data. If this limit is reached and further output can be @@ -83,32 +81,23 @@ class LZMADecompressor: @property def check(self) -> int: - """ - ID of the integrity check used by the input stream. - """ + """ID of the integrity check used by the input stream.""" @property def eof(self) -> bool: - """ - True if the end-of-stream marker has been reached. - """ + """True if the end-of-stream marker has been reached.""" @property def unused_data(self) -> bytes: - """ - Data found after the end of the compressed stream. - """ + """Data found after the end of the compressed stream.""" @property def needs_input(self) -> bool: - """ - True if more input is needed before more decompressed data can be produced. - """ + """True if more input is needed before more decompressed data can be produced.""" @final class LZMACompressor: - """ - LZMACompressor(format=FORMAT_XZ, check=-1, preset=None, filters=None) + """LZMACompressor(format=FORMAT_XZ, check=-1, preset=None, filters=None) Create a compressor object for compressing data incrementally. @@ -146,8 +135,7 @@ class LZMACompressor: ) -> None: ... def compress(self, data: ReadableBuffer, /) -> bytes: - """ - Provide data to the compressor object. + """Provide data to the compressor object. Returns a chunk of compressed data if possible, or b'' otherwise. @@ -156,8 +144,7 @@ class LZMACompressor: """ def flush(self) -> bytes: - """ - Finish the compression process. + """Finish the compression process. Returns the compressed data left in internal buffers. @@ -165,13 +152,10 @@ class LZMACompressor: """ class LZMAError(Exception): - """ - Call to liblzma failed. - """ + """Call to liblzma failed.""" def is_check_supported(check_id: int, /) -> bool: - """ - Test whether the given integrity check is supported. + """Test whether the given integrity check is supported. Always returns True for CHECK_NONE and CHECK_CRC32. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_markupbase.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_markupbase.pyi index 812095ee2a..7ad0ff96e2 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_markupbase.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_markupbase.pyi @@ -9,16 +9,13 @@ import sys from typing import Any class ParserBase: - """ - Parser base class which provides some common support methods used + """Parser base class which provides some common support methods used by the SGML/HTML and XHTML parsers. """ def reset(self) -> None: ... def getpos(self) -> tuple[int, int]: - """ - Return current line number and offset. - """ + """Return current line number and offset.""" def unknown_decl(self, data: str) -> None: ... def parse_comment(self, i: int, report: bool = True) -> int: ... # undocumented diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_msi.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_msi.pyi index 779fda3b67..0653815096 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_msi.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_msi.pyi @@ -1,3 +1,7 @@ +""" +Documentation +""" + import sys if sys.platform == "win32": @@ -46,11 +50,34 @@ if sys.platform == "win32": __new__: None # type: ignore[assignment] __init__: None # type: ignore[assignment] - def UuidCreate() -> str: ... - def FCICreate(cabname: str, files: list[str], /) -> None: ... - def OpenDatabase(path: str, persist: int, /) -> _Database: ... - def CreateRecord(count: int, /) -> _Record: ... + def UuidCreate() -> str: + """Return the string representation of a new unique identifier.""" + def FCICreate(cabname: str, files: list[str], /) -> None: + """Create a new CAB file. + + cabname + the name of the CAB file + files + a list of tuples, each containing the name of the file on disk, + and the name of the file inside the CAB file + """ + + def OpenDatabase(path: str, persist: int, /) -> _Database: + """Return a new database object. + + path + the file name of the MSI file + persist + the persistence mode + """ + + def CreateRecord(count: int, /) -> _Record: + """Return a new record object. + + count + the number of fields of the record + """ MSICOLINFO_NAMES: int MSICOLINFO_TYPES: int MSIDBOPEN_CREATE: int diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_operator.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_operator.pyi index cc07f131ef..da61639e93 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_operator.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_operator.pyi @@ -51,170 +51,104 @@ class _SupportsPos(Protocol[_T_co]): # All four comparison functions must have the same signature, or we get false-positive errors def lt(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: - """ - Same as a < b. - """ + """Same as a < b.""" def le(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: - """ - Same as a <= b. - """ + """Same as a <= b.""" def eq(a: object, b: object, /) -> Any: - """ - Same as a == b. - """ + """Same as a == b.""" def ne(a: object, b: object, /) -> Any: - """ - Same as a != b. - """ + """Same as a != b.""" def ge(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: - """ - Same as a >= b. - """ + """Same as a >= b.""" def gt(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: - """ - Same as a > b. - """ + """Same as a > b.""" def not_(a: object, /) -> bool: - """ - Same as not a. - """ + """Same as not a.""" def truth(a: object, /) -> bool: - """ - Return True if a is true, False otherwise. - """ + """Return True if a is true, False otherwise.""" def is_(a: object, b: object, /) -> bool: - """ - Same as a is b. - """ + """Same as a is b.""" def is_not(a: object, b: object, /) -> bool: - """ - Same as a is not b. - """ + """Same as a is not b.""" def abs(a: SupportsAbs[_T], /) -> _T: - """ - Same as abs(a). - """ + """Same as abs(a).""" def add(a: Any, b: Any, /) -> Any: - """ - Same as a + b. - """ + """Same as a + b.""" def and_(a: Any, b: Any, /) -> Any: - """ - Same as a & b. - """ + """Same as a & b.""" def floordiv(a: Any, b: Any, /) -> Any: - """ - Same as a // b. - """ + """Same as a // b.""" def index(a: SupportsIndex, /) -> int: - """ - Same as a.__index__() - """ + """Same as a.__index__()""" def inv(a: _SupportsInversion[_T_co], /) -> _T_co: - """ - Same as ~a. - """ + """Same as ~a.""" def invert(a: _SupportsInversion[_T_co], /) -> _T_co: - """ - Same as ~a. - """ + """Same as ~a.""" def lshift(a: Any, b: Any, /) -> Any: - """ - Same as a << b. - """ + """Same as a << b.""" def mod(a: Any, b: Any, /) -> Any: - """ - Same as a % b. - """ + """Same as a % b.""" def mul(a: Any, b: Any, /) -> Any: - """ - Same as a * b. - """ + """Same as a * b.""" def matmul(a: Any, b: Any, /) -> Any: - """ - Same as a @ b. - """ + """Same as a @ b.""" def neg(a: _SupportsNeg[_T_co], /) -> _T_co: - """ - Same as -a. - """ + """Same as -a.""" def or_(a: Any, b: Any, /) -> Any: - """ - Same as a | b. - """ + """Same as a | b.""" def pos(a: _SupportsPos[_T_co], /) -> _T_co: - """ - Same as +a. - """ + """Same as +a.""" def pow(a: Any, b: Any, /) -> Any: - """ - Same as a ** b. - """ + """Same as a ** b.""" def rshift(a: Any, b: Any, /) -> Any: - """ - Same as a >> b. - """ + """Same as a >> b.""" def sub(a: Any, b: Any, /) -> Any: - """ - Same as a - b. - """ + """Same as a - b.""" def truediv(a: Any, b: Any, /) -> Any: - """ - Same as a / b. - """ + """Same as a / b.""" def xor(a: Any, b: Any, /) -> Any: - """ - Same as a ^ b. - """ + """Same as a ^ b.""" def concat(a: Sequence[_T], b: Sequence[_T], /) -> Sequence[_T]: - """ - Same as a + b, for a and b sequences. - """ + """Same as a + b, for a and b sequences.""" def contains(a: Container[object], b: object, /) -> bool: - """ - Same as b in a (note reversed operands). - """ + """Same as b in a (note reversed operands).""" def countOf(a: Iterable[object], b: object, /) -> int: - """ - Return the number of items in a which are, or which equal, b. - """ + """Return the number of items in a which are, or which equal, b.""" @overload def delitem(a: MutableSequence[Any], b: SupportsIndex, /) -> None: - """ - Same as del a[b]. - """ + """Same as del a[b].""" @overload def delitem(a: MutableSequence[Any], b: slice, /) -> None: ... @@ -222,30 +156,23 @@ def delitem(a: MutableSequence[Any], b: slice, /) -> None: ... def delitem(a: MutableMapping[_K, Any], b: _K, /) -> None: ... @overload def getitem(a: Sequence[_T], b: slice, /) -> Sequence[_T]: - """ - Same as a[b]. - """ + """Same as a[b].""" @overload def getitem(a: SupportsGetItem[_K, _V], b: _K, /) -> _V: ... def indexOf(a: Iterable[_T], b: _T, /) -> int: - """ - Return the first index of b in a. - """ + """Return the first index of b in a.""" @overload def setitem(a: MutableSequence[_T], b: SupportsIndex, c: _T, /) -> None: - """ - Same as a[b] = c. - """ + """Same as a[b] = c.""" @overload def setitem(a: MutableSequence[_T], b: slice, c: Sequence[_T], /) -> None: ... @overload def setitem(a: MutableMapping[_K, _V], b: _K, c: _V, /) -> None: ... def length_hint(obj: object, default: int = 0, /) -> int: - """ - Return an estimate of the number of items in obj. + """Return an estimate of the number of items in obj. This is useful for presizing containers when building from an iterable. @@ -255,84 +182,53 @@ def length_hint(obj: object, default: int = 0, /) -> int: """ def iadd(a: Any, b: Any, /) -> Any: - """ - Same as a += b. - """ + """Same as a += b.""" def iand(a: Any, b: Any, /) -> Any: - """ - Same as a &= b. - """ + """Same as a &= b.""" def iconcat(a: Any, b: Any, /) -> Any: - """ - Same as a += b, for a and b sequences. - """ + """Same as a += b, for a and b sequences.""" def ifloordiv(a: Any, b: Any, /) -> Any: - """ - Same as a //= b. - """ + """Same as a //= b.""" def ilshift(a: Any, b: Any, /) -> Any: - """ - Same as a <<= b. - """ + """Same as a <<= b.""" def imod(a: Any, b: Any, /) -> Any: - """ - Same as a %= b. - """ + """Same as a %= b.""" def imul(a: Any, b: Any, /) -> Any: - """ - Same as a *= b. - """ + """Same as a *= b.""" def imatmul(a: Any, b: Any, /) -> Any: - """ - Same as a @= b. - """ + """Same as a @= b.""" def ior(a: Any, b: Any, /) -> Any: - """ - Same as a |= b. - """ + """Same as a |= b.""" def ipow(a: Any, b: Any, /) -> Any: - """ - Same as a **= b. - """ + """Same as a **= b.""" def irshift(a: Any, b: Any, /) -> Any: - """ - Same as a >>= b. - """ + """Same as a >>= b.""" def isub(a: Any, b: Any, /) -> Any: - """ - Same as a -= b. - """ + """Same as a -= b.""" def itruediv(a: Any, b: Any, /) -> Any: - """ - Same as a /= b. - """ + """Same as a /= b.""" def ixor(a: Any, b: Any, /) -> Any: - """ - Same as a ^= b. - """ + """Same as a ^= b.""" if sys.version_info >= (3, 11): def call(obj: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> _R: - """ - Same as obj(*args, **kwargs). - """ + """Same as obj(*args, **kwargs).""" def _compare_digest(a: AnyStr, b: AnyStr, /) -> bool: - """ - Return 'a == b'. + """Return 'a == b'. This function uses an approach designed to prevent timing analysis, making it appropriate for cryptography. @@ -347,11 +243,7 @@ def _compare_digest(a: AnyStr, b: AnyStr, /) -> bool: if sys.version_info >= (3, 14): def is_none(a: object, /) -> TypeIs[None]: - """ - Same as a is None. - """ + """Same as a is None.""" def is_not_none(a: _T | None, /) -> TypeIs[_T]: - """ - Same as a is not None. - """ + """Same as a is not None.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_osx_support.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_osx_support.pyi index c056c66f67..8455d3a9d5 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_osx_support.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_osx_support.pyi @@ -16,73 +16,49 @@ _COMPILER_CONFIG_VARS: Final[tuple[str, ...]] # undocumented _INITPRE: Final[str] # undocumented def _find_executable(executable: str, path: str | None = None) -> str | None: # undocumented - """ - Tries to find 'executable' in the directories listed in 'path'. + """Tries to find 'executable' in the directories listed in 'path'. A string listing directories separated by 'os.pathsep'; defaults to os.environ['PATH']. Returns the complete filename or None if not found. """ def _read_output(commandstring: str, capture_stderr: bool = False) -> str | None: # undocumented - """ - Output from successful command execution or None - """ + """Output from successful command execution or None""" def _find_build_tool(toolname: str) -> str: # undocumented - """ - Find a build tool on current path or using xcrun - """ + """Find a build tool on current path or using xcrun""" _SYSTEM_VERSION: Final[str | None] # undocumented def _get_system_version() -> str: # undocumented - """ - Return the OS X system version as a string - """ + """Return the OS X system version as a string""" def _remove_original_values(_config_vars: dict[str, str]) -> None: # undocumented - """ - Remove original unmodified values for testing - """ + """Remove original unmodified values for testing""" def _save_modified_value(_config_vars: dict[str, str], cv: str, newvalue: str) -> None: # undocumented - """ - Save modified and original unmodified value of configuration var - """ + """Save modified and original unmodified value of configuration var""" def _supports_universal_builds() -> bool: # undocumented - """ - Returns True if universal builds are supported on this system - """ + """Returns True if universal builds are supported on this system""" def _find_appropriate_compiler(_config_vars: dict[str, str]) -> dict[str, str]: # undocumented - """ - Find appropriate C compiler for extension module builds - """ + """Find appropriate C compiler for extension module builds""" def _remove_universal_flags(_config_vars: dict[str, str]) -> dict[str, str]: # undocumented - """ - Remove all universal build arguments from config vars - """ + """Remove all universal build arguments from config vars""" def _remove_unsupported_archs(_config_vars: dict[str, str]) -> dict[str, str]: # undocumented - """ - Remove any unsupported archs from config vars - """ + """Remove any unsupported archs from config vars""" def _override_all_archs(_config_vars: dict[str, str]) -> dict[str, str]: # undocumented - """ - Allow override of all archs with ARCHFLAGS env var - """ + """Allow override of all archs with ARCHFLAGS env var""" def _check_for_unavailable_sdk(_config_vars: dict[str, str]) -> dict[str, str]: # undocumented - """ - Remove references to any SDKs not available - """ + """Remove references to any SDKs not available""" def compiler_fixup(compiler_so: Iterable[str], cc_args: Sequence[str]) -> list[str]: - """ - This function will strip '-isysroot PATH' and '-arch ARCH' from the + """This function will strip '-isysroot PATH' and '-arch ARCH' from the compile flags if the user has specified one them in extra_compile_flags. This is needed because '-arch ARCH' adds another architecture to the @@ -91,8 +67,7 @@ def compiler_fixup(compiler_so: Iterable[str], cc_args: Sequence[str]) -> list[s """ def customize_config_vars(_config_vars: dict[str, str]) -> dict[str, str]: - """ - Customize Python build configuration variables. + """Customize Python build configuration variables. Called internally from sysconfig with a mutable mapping containing name/value pairs parsed from the configured @@ -117,8 +92,7 @@ def customize_config_vars(_config_vars: dict[str, str]) -> dict[str, str]: """ def customize_compiler(_config_vars: dict[str, str]) -> dict[str, str]: - """ - Customize compiler path and configuration variables. + """Customize compiler path and configuration variables. This customization is performed when the first extension module build is requested @@ -126,6 +100,4 @@ def customize_compiler(_config_vars: dict[str, str]) -> dict[str, str]: """ def get_platform_osx(_config_vars: dict[str, str], osname: _T, release: _K, machine: _V) -> tuple[str | _T, str | _K, str | _V]: - """ - Filter values for get_platform() - """ + """Filter values for get_platform()""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_pickle.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_pickle.pyi index bfe9e1c1cc..c93fa445be 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_pickle.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_pickle.pyi @@ -30,8 +30,7 @@ def dump( fix_imports: bool = True, buffer_callback: _BufferCallback = None, ) -> None: - """ - Write a pickled representation of obj to the open file object file. + """Write a pickled representation of obj to the open file object file. This is equivalent to ``Pickler(file, protocol).dump(obj)``, but may be more efficient. @@ -60,8 +59,7 @@ def dump( """ def dumps(obj: Any, protocol: int | None = None, *, fix_imports: bool = True, buffer_callback: _BufferCallback = None) -> bytes: - """ - Return the pickled representation of the object as a bytes object. + """Return the pickled representation of the object as a bytes object. The optional *protocol* argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2, 3, 4 and 5. The default @@ -89,8 +87,7 @@ def load( errors: str = "strict", buffers: Iterable[Any] | None = (), ) -> Any: - """ - Read and return an object from the pickle data stored in a file. + """Read and return an object from the pickle data stored in a file. This is equivalent to ``Unpickler(file).load()``, but may be more efficient. @@ -124,8 +121,7 @@ def loads( errors: str = "strict", buffers: Iterable[Any] | None = (), ) -> Any: - """ - Read and return an object from the given pickle data. + """Read and return an object from the given pickle data. The protocol version of the pickle is detected automatically, so no protocol argument is needed. Bytes past the pickled object's @@ -151,8 +147,7 @@ class PicklerMemoProxy: def copy(self, /) -> dict[int, tuple[int, Any]]: ... class Pickler: - """ - This takes a binary file for writing a pickle data stream. + """This takes a binary file for writing a pickle data stream. The optional *protocol* argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2, 3, 4 and 5. The default @@ -200,13 +195,10 @@ class Pickler: @memo.setter def memo(self, value: PicklerMemoProxy | dict[int, tuple[int, Any]]) -> None: ... def dump(self, obj: Any, /) -> None: - """ - Write a pickled representation of the given object to the open file. - """ + """Write a pickled representation of the given object to the open file.""" def clear_memo(self) -> None: - """ - Clears the pickler's "memo". + """Clears the pickler's "memo". The memo is the data structure that remembers which objects the pickler has already seen, so that shared or recursive objects are @@ -222,8 +214,7 @@ class UnpicklerMemoProxy: def copy(self, /) -> dict[int, tuple[int, Any]]: ... class Unpickler: - """ - This takes a binary file for reading a pickle data stream. + """This takes a binary file for reading a pickle data stream. The protocol version of the pickle is detected automatically, so no protocol argument is needed. Bytes past the pickled object's @@ -259,8 +250,7 @@ class Unpickler: @memo.setter def memo(self, value: UnpicklerMemoProxy | dict[int, tuple[int, Any]]) -> None: ... def load(self) -> Any: - """ - Load a pickle. + """Load a pickle. Read a pickled object representation from the open file object given in the constructor, and return the reconstituted object hierarchy @@ -268,8 +258,7 @@ class Unpickler: """ def find_class(self, module_name: str, global_name: str, /) -> Any: - """ - Return an object from a specified module. + """Return an object from a specified module. If necessary, the module will be imported. Subclasses may override this method (e.g. to restrict unpickling of arbitrary classes and diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_posixsubprocess.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_posixsubprocess.pyi index 16e5d9dc98..6b01cd0b1d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_posixsubprocess.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_posixsubprocess.pyi @@ -34,8 +34,7 @@ if sys.platform != "win32": preexec_fn: Callable[[], None], /, ) -> int: - """ - Spawn a fresh new child process. + """Spawn a fresh new child process. Fork a child process, close parent file descriptors as appropriate in the child and duplicate the few that are needed before calling exec() in the @@ -84,8 +83,7 @@ if sys.platform != "win32": allow_vfork: bool, /, ) -> int: - """ - Spawn a fresh new child process. + """Spawn a fresh new child process. Fork a child process, close parent file descriptors as appropriate in the child and duplicate the few that are needed before calling exec() in the diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_py_abc.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_py_abc.pyi index 3438dbe558..b273d36204 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_py_abc.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_py_abc.pyi @@ -6,8 +6,7 @@ _T = TypeVar("_T") _CacheToken = NewType("_CacheToken", int) def get_cache_token() -> _CacheToken: - """ - Returns the current ABC cache token. + """Returns the current ABC cache token. The token is an opaque object (supporting equality testing) identifying the current version of the ABC cache for virtual subclasses. The token changes @@ -15,8 +14,7 @@ def get_cache_token() -> _CacheToken: """ class ABCMeta(type): - """ - Metaclass for defining Abstract Base Classes (ABCs). + """Metaclass for defining Abstract Base Classes (ABCs). Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register @@ -33,8 +31,7 @@ class ABCMeta(type): mcls: type[_typeshed.Self], name: str, bases: tuple[type[Any], ...], namespace: dict[str, Any], / ) -> _typeshed.Self: ... def register(cls, subclass: type[_T]) -> type[_T]: - """ - Register a virtual subclass of an ABC. + """Register a virtual subclass of an ABC. Returns the subclass, to allow usage as a class decorator. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_queue.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_queue.pyi index 37902bec5d..749b54b3cd 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_queue.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_queue.pyi @@ -9,24 +9,17 @@ from typing import Any, Generic, TypeVar _T = TypeVar("_T") class Empty(Exception): - """ - Exception raised by Queue.get(block=0)/get_nowait(). - """ + """Exception raised by Queue.get(block=0)/get_nowait().""" class SimpleQueue(Generic[_T]): - """ - Simple, unbounded, reentrant FIFO queue. - """ + """Simple, unbounded, reentrant FIFO queue.""" def __init__(self) -> None: ... def empty(self) -> bool: - """ - Return True if the queue is empty, False otherwise (not reliable!). - """ + """Return True if the queue is empty, False otherwise (not reliable!).""" def get(self, block: bool = True, timeout: float | None = None) -> _T: - """ - Remove and return an item from the queue. + """Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is @@ -38,35 +31,28 @@ class SimpleQueue(Generic[_T]): """ def get_nowait(self) -> _T: - """ - Remove and return an item from the queue without blocking. + """Remove and return an item from the queue without blocking. Only get an item if one is immediately available. Otherwise raise the Empty exception. """ def put(self, item: _T, block: bool = True, timeout: float | None = None) -> None: - """ - Put the item on the queue. + """Put the item on the queue. The optional 'block' and 'timeout' arguments are ignored, as this method never blocks. They are provided for compatibility with the Queue class. """ def put_nowait(self, item: _T) -> None: - """ - Put an item into the queue without blocking. + """Put an item into the queue without blocking. This is exactly equivalent to `put(item)` and is only provided for compatibility with the Queue class. """ def qsize(self) -> int: - """ - Return the approximate size of the queue (not reliable!). - """ + """Return the approximate size of the queue (not reliable!).""" def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_random.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_random.pyi index 828afce01c..02cc964ca4 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_random.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_random.pyi @@ -8,35 +8,24 @@ from typing_extensions import TypeAlias _State: TypeAlias = tuple[int, ...] class Random: - """ - Random() -> create a random number generator with its own internal state. - """ + """Random() -> create a random number generator with its own internal state.""" def __init__(self, seed: object = ...) -> None: ... def seed(self, n: object = None, /) -> None: - """ - seed([n]) -> None. + """seed([n]) -> None. Defaults to use urandom and falls back to a combination of the current time and the process identifier. """ def getstate(self) -> _State: - """ - getstate() -> tuple containing the current state. - """ + """getstate() -> tuple containing the current state.""" def setstate(self, state: _State, /) -> None: - """ - setstate(state) -> None. Restores generator state. - """ + """setstate(state) -> None. Restores generator state.""" def random(self) -> float: - """ - random() -> x in the interval [0, 1). - """ + """random() -> x in the interval [0, 1).""" def getrandbits(self, k: int, /) -> int: - """ - getrandbits(k) -> x. Generates an int with k random bits. - """ + """getrandbits(k) -> x. Generates an int with k random bits.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_sitebuiltins.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_sitebuiltins.pyi index f59c5f5f24..e0d7462db4 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_sitebuiltins.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_sitebuiltins.pyi @@ -1,4 +1,5 @@ """ + The objects used by the site module to add custom builtins. """ @@ -13,8 +14,7 @@ class Quitter: def __call__(self, code: sys._ExitCode = None) -> NoReturn: ... class _Printer: - """ - interactive prompt objects for printing the license text, a list of + """interactive prompt objects for printing the license text, a list of contributors and the copyright notice. """ @@ -23,8 +23,7 @@ class _Printer: def __call__(self) -> None: ... class _Helper: - """ - Define the builtin 'help'. + """Define the builtin 'help'. This is a wrapper around pydoc.help that provides a helpful message when 'help' is typed at the Python interactive prompt. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_socket.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_socket.pyi index 9d4d7ada4b..4524c7c417 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_socket.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_socket.pyi @@ -738,8 +738,7 @@ if sys.platform != "win32" and sys.platform != "darwin": # ===== Classes ===== class socket: - """ - socket(family=AF_INET, type=SOCK_STREAM, proto=0) -> socket object + """socket(family=AF_INET, type=SOCK_STREAM, proto=0) -> socket object socket(family=-1, type=-1, proto=-1, fileno=None) -> socket object Open a socket of the given type. The family argument specifies the @@ -787,27 +786,19 @@ class socket: @property def family(self) -> int: - """ - the socket family - """ + """the socket family""" @property def type(self) -> int: - """ - the socket type - """ + """the socket type""" @property def proto(self) -> int: - """ - the socket protocol - """ + """the socket protocol""" # F811: "Redefinition of unused `timeout`" @property def timeout(self) -> float | None: # noqa: F811 - """ - the socket timeout - """ + """the socket timeout""" if sys.platform == "win32": def __init__( self, family: int = ..., type: int = ..., proto: int = ..., fileno: SupportsIndex | bytes | None = ... @@ -816,8 +807,7 @@ class socket: def __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: SupportsIndex | None = ...) -> None: ... def bind(self, address: _Address, /) -> None: - """ - bind(address) + """bind(address) Bind the socket to a local address. For IP sockets, the address is a pair (host, port); the host must refer to the local host. For raw packet @@ -825,31 +815,27 @@ class socket: """ def close(self) -> None: - """ - close() + """close() Close the socket. It cannot be used after this call. """ def connect(self, address: _Address, /) -> None: - """ - connect(address) + """connect(address) Connect the socket to a remote address. For IP sockets, the address is a pair (host, port). """ def connect_ex(self, address: _Address, /) -> int: - """ - connect_ex(address) -> errno + """connect_ex(address) -> errno This is like connect(address), but returns an error code (the errno value) instead of raising an exception when an error occurs. """ def detach(self) -> int: - """ - detach() + """detach() Close the socket object without closing the underlying file descriptor. The object cannot be used after this call, but the file descriptor @@ -857,23 +843,20 @@ class socket: """ def fileno(self) -> int: - """ - fileno() -> integer + """fileno() -> integer Return the integer file descriptor of the socket. """ def getpeername(self) -> _RetAddress: - """ - getpeername() -> address info + """getpeername() -> address info Return the address of the remote endpoint. For IP sockets, the address info is a pair (hostaddr, port). """ def getsockname(self) -> _RetAddress: - """ - getsockname() -> address info + """getsockname() -> address info Return the address of the local endpoint. The format depends on the address family. For IPv4 sockets, the address info is a pair @@ -883,8 +866,7 @@ class socket: @overload def getsockopt(self, level: int, optname: int, /) -> int: - """ - getsockopt(level, option[, buffersize]) -> value + """getsockopt(level, option[, buffersize]) -> value Get a socket option. See the Unix manual for level and option. If a nonzero buffersize argument is given, the return value is a @@ -894,16 +876,14 @@ class socket: @overload def getsockopt(self, level: int, optname: int, buflen: int, /) -> bytes: ... def getblocking(self) -> bool: - """ - getblocking() + """getblocking() Returns True if socket is in blocking mode, or False if it is in non-blocking mode. """ def gettimeout(self) -> float | None: - """ - gettimeout() -> timeout + """gettimeout() -> timeout Returns the timeout in seconds (float) associated with socket operations. A timeout of None indicates that timeouts on socket @@ -913,8 +893,7 @@ class socket: def ioctl(self, control: int, option: int | tuple[int, int, int] | bool, /) -> None: ... def listen(self, backlog: int = ..., /) -> None: - """ - listen([backlog]) + """listen([backlog]) Enable a server to accept connections. If backlog is specified, it must be at least 0 (if it is lower, it is set to 0); it specifies the number of @@ -923,8 +902,7 @@ class socket: """ def recv(self, bufsize: int, flags: int = ..., /) -> bytes: - """ - recv(buffersize[, flags]) -> data + """recv(buffersize[, flags]) -> data Receive up to buffersize bytes from the socket. For the optional flags argument, see the Unix manual. When no data is available, block until @@ -933,15 +911,13 @@ class socket: """ def recvfrom(self, bufsize: int, flags: int = ..., /) -> tuple[bytes, _RetAddress]: - """ - recvfrom(buffersize[, flags]) -> (data, address info) + """recvfrom(buffersize[, flags]) -> (data, address info) Like recv(buffersize, flags) but also return the sender's address info. """ if sys.platform != "win32": def recvmsg(self, bufsize: int, ancbufsize: int = ..., flags: int = ..., /) -> tuple[bytes, list[_CMSG], int, Any]: - """ - recvmsg(bufsize[, ancbufsize[, flags]]) -> (data, ancdata, msg_flags, address) + """recvmsg(bufsize[, ancbufsize[, flags]]) -> (data, ancdata, msg_flags, address) Receive normal data (up to bufsize bytes) and ancillary data from the socket. The ancbufsize argument sets the size in bytes of the @@ -973,8 +949,7 @@ class socket: def recvmsg_into( self, buffers: Iterable[WriteableBuffer], ancbufsize: int = ..., flags: int = ..., / ) -> tuple[int, list[_CMSG], int, Any]: - """ - recvmsg_into(buffers[, ancbufsize[, flags]]) -> (nbytes, ancdata, msg_flags, address) + """recvmsg_into(buffers[, ancbufsize[, flags]]) -> (nbytes, ancdata, msg_flags, address) Receive normal data and ancillary data from the socket, scattering the non-ancillary data into a series of buffers. The buffers argument @@ -1008,15 +983,13 @@ class socket: """ def recvfrom_into(self, buffer: WriteableBuffer, nbytes: int = ..., flags: int = ...) -> tuple[int, _RetAddress]: - """ - recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info) + """recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info) Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info. """ def recv_into(self, buffer: WriteableBuffer, nbytes: int = ..., flags: int = ...) -> int: - """ - recv_into(buffer, [nbytes[, flags]]) -> nbytes_read + """recv_into(buffer, [nbytes[, flags]]) -> nbytes_read A version of recv() that stores its data into a buffer rather than creating a new string. Receive up to buffersize bytes from the socket. If buffersize @@ -1026,8 +999,7 @@ class socket: """ def send(self, data: ReadableBuffer, flags: int = ..., /) -> int: - """ - send(data[, flags]) -> count + """send(data[, flags]) -> count Send a data string to the socket. For the optional flags argument, see the Unix manual. Return the number of bytes @@ -1035,8 +1007,7 @@ class socket: """ def sendall(self, data: ReadableBuffer, flags: int = ..., /) -> None: - """ - sendall(data[, flags]) + """sendall(data[, flags]) Send a data string to the socket. For the optional flags argument, see the Unix manual. This calls send() repeatedly @@ -1046,8 +1017,7 @@ class socket: @overload def sendto(self, data: ReadableBuffer, address: _Address, /) -> int: - """ - sendto(data[, flags], address) -> count + """sendto(data[, flags], address) -> count Like send(data, flags) but allows specifying the destination address. For IP sockets, the address is a pair (hostaddr, port). @@ -1064,8 +1034,7 @@ class socket: address: _Address | None = ..., /, ) -> int: - """ - sendmsg(buffers[, ancdata[, flags[, address]]]) -> count + """sendmsg(buffers[, ancdata[, flags[, address]]]) -> count Send normal and ancillary data to the socket, gathering the non-ancillary data from a series of buffers and concatenating it into @@ -1085,16 +1054,14 @@ class socket: def sendmsg_afalg( self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... ) -> int: - """ - sendmsg_afalg([msg], *, op[, iv[, assoclen[, flags=MSG_MORE]]]) + """sendmsg_afalg([msg], *, op[, iv[, assoclen[, flags=MSG_MORE]]]) Set operation mode, IV and length of associated data for an AF_ALG operation socket. """ def setblocking(self, flag: bool, /) -> None: - """ - setblocking(flag) + """setblocking(flag) Set the socket to blocking (flag is true) or non-blocking (false). setblocking(True) is equivalent to settimeout(None); @@ -1102,8 +1069,7 @@ class socket: """ def settimeout(self, value: float | None, /) -> None: - """ - settimeout(timeout) + """settimeout(timeout) Set a timeout on socket operations. 'timeout' can be a float, giving in seconds, or None. Setting a timeout of None disables @@ -1113,8 +1079,7 @@ class socket: @overload def setsockopt(self, level: int, optname: int, value: int | ReadableBuffer, /) -> None: - """ - setsockopt(level, option, value: int) + """setsockopt(level, option, value: int) setsockopt(level, option, value: buffer) setsockopt(level, option, None, optlen: int) @@ -1129,8 +1094,7 @@ class socket: def share(self, process_id: int, /) -> bytes: ... def shutdown(self, how: int, /) -> None: - """ - shutdown(flag) + """shutdown(flag) Shut down the reading side of the socket (flag == SHUT_RD), the writing side of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR). @@ -1141,16 +1105,14 @@ SocketType = socket # ===== Functions ===== def close(fd: SupportsIndex, /) -> None: - """ - close(integer) -> None + """close(integer) -> None Close an integer socket file descriptor. This is like os.close(), but for sockets; on some platforms os.close() won't work for socket file descriptors. """ def dup(fd: SupportsIndex, /) -> int: - """ - dup(integer) -> integer + """dup(integer) -> integer Duplicate an integer socket file descriptor. This is like os.dup(), but for sockets; on some platforms os.dup() won't work for socket file descriptors. @@ -1165,60 +1127,52 @@ def getaddrinfo( proto: int = ..., flags: int = ..., ) -> list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]]: - """ - getaddrinfo(host, port [, family, type, proto, flags]) + """getaddrinfo(host, port [, family, type, proto, flags]) -> list of (family, type, proto, canonname, sockaddr) Resolve host and port into addrinfo struct. """ def gethostbyname(hostname: str, /) -> str: - """ - gethostbyname(host) -> address + """gethostbyname(host) -> address Return the IP address (a string of the form '255.255.255.255') for a host. """ def gethostbyname_ex(hostname: str, /) -> tuple[str, list[str], list[str]]: - """ - gethostbyname_ex(host) -> (name, aliaslist, addresslist) + """gethostbyname_ex(host) -> (name, aliaslist, addresslist) Return the true host name, a list of aliases, and a list of IP addresses, for a host. The host argument is a string giving a host name or IP number. """ def gethostname() -> str: - """ - gethostname() -> string + """gethostname() -> string Return the current host name. """ def gethostbyaddr(ip_address: str, /) -> tuple[str, list[str], list[str]]: - """ - gethostbyaddr(host) -> (name, aliaslist, addresslist) + """gethostbyaddr(host) -> (name, aliaslist, addresslist) Return the true host name, a list of aliases, and a list of IP addresses, for a host. The host argument is a string giving a host name or IP number. """ def getnameinfo(sockaddr: tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], flags: int, /) -> tuple[str, str]: - """ - getnameinfo(sockaddr, flags) --> (host, port) + """getnameinfo(sockaddr, flags) --> (host, port) Get host and port for a sockaddr. """ def getprotobyname(protocolname: str, /) -> int: - """ - getprotobyname(name) -> integer + """getprotobyname(name) -> integer Return the protocol number for the named protocol. (Rarely used.) """ def getservbyname(servicename: str, protocolname: str = ..., /) -> int: - """ - getservbyname(servicename[, protocolname]) -> integer + """getservbyname(servicename[, protocolname]) -> integer Return a port number from a service name and protocol name. The optional protocol name, if given, should be 'tcp' or 'udp', @@ -1226,8 +1180,7 @@ def getservbyname(servicename: str, protocolname: str = ..., /) -> int: """ def getservbyport(port: int, protocolname: str = ..., /) -> str: - """ - getservbyport(port[, protocolname]) -> string + """getservbyport(port[, protocolname]) -> string Return the service name from a port number and protocol name. The optional protocol name, if given, should be 'tcp' or 'udp', @@ -1235,53 +1188,38 @@ def getservbyport(port: int, protocolname: str = ..., /) -> str: """ def ntohl(x: int, /) -> int: # param & ret val are 32-bit ints - """ - Convert a 32-bit unsigned integer from network to host byte order. - """ + """Convert a 32-bit unsigned integer from network to host byte order.""" def ntohs(x: int, /) -> int: # param & ret val are 16-bit ints - """ - Convert a 16-bit unsigned integer from network to host byte order. - """ + """Convert a 16-bit unsigned integer from network to host byte order.""" def htonl(x: int, /) -> int: # param & ret val are 32-bit ints - """ - Convert a 32-bit unsigned integer from host to network byte order. - """ + """Convert a 32-bit unsigned integer from host to network byte order.""" def htons(x: int, /) -> int: # param & ret val are 16-bit ints - """ - Convert a 16-bit unsigned integer from host to network byte order. - """ + """Convert a 16-bit unsigned integer from host to network byte order.""" def inet_aton(ip_addr: str, /) -> bytes: # ret val 4 bytes in length - """ - Convert an IP address in string format (123.45.67.89) to the 32-bit packed binary format used in low-level network functions. - """ + """Convert an IP address in string format (123.45.67.89) to the 32-bit packed binary format used in low-level network functions.""" def inet_ntoa(packed_ip: ReadableBuffer, /) -> str: - """ - Convert an IP address from 32-bit packed binary format to string format. - """ + """Convert an IP address from 32-bit packed binary format to string format.""" def inet_pton(address_family: int, ip_string: str, /) -> bytes: - """ - inet_pton(af, ip) -> packed IP address string + """inet_pton(af, ip) -> packed IP address string Convert an IP address from string format to a packed string suitable for use with low-level network functions. """ def inet_ntop(address_family: int, packed_ip: ReadableBuffer, /) -> str: - """ - inet_ntop(af, packed_ip) -> string formatted IP address + """inet_ntop(af, packed_ip) -> string formatted IP address Convert a packed IP address of the given family to string format. """ def getdefaulttimeout() -> float | None: - """ - getdefaulttimeout() -> timeout + """getdefaulttimeout() -> timeout Returns the default timeout in seconds (float) for new socket objects. A value of None indicates that new socket objects have no timeout. @@ -1290,8 +1228,7 @@ def getdefaulttimeout() -> float | None: # F811: "Redefinition of unused `timeout`" def setdefaulttimeout(timeout: float | None, /) -> None: # noqa: F811 - """ - setdefaulttimeout(timeout) + """setdefaulttimeout(timeout) Set the default timeout in seconds (float) for new socket objects. A value of None indicates that new socket objects have no timeout. @@ -1300,15 +1237,13 @@ def setdefaulttimeout(timeout: float | None, /) -> None: # noqa: F811 if sys.platform != "win32": def sethostname(name: str, /) -> None: - """ - sethostname(name) + """sethostname(name) Sets the hostname to name. """ def CMSG_LEN(length: int, /) -> int: - """ - CMSG_LEN(length) -> control message length + """CMSG_LEN(length) -> control message length Return the total length, without trailing padding, of an ancillary data item with associated data of the given length. This value can @@ -1320,8 +1255,7 @@ if sys.platform != "win32": """ def CMSG_SPACE(length: int, /) -> int: - """ - CMSG_SPACE(length) -> buffer size + """CMSG_SPACE(length) -> buffer size Return the buffer size needed for recvmsg() to receive an ancillary data item with associated data of the given length, along with any @@ -1332,8 +1266,7 @@ if sys.platform != "win32": """ def socketpair(family: int = ..., type: int = ..., proto: int = ..., /) -> tuple[socket, socket]: - """ - socketpair([family[, type [, proto]]]) -> (socket object, socket object) + """socketpair([family[, type [, proto]]]) -> (socket object, socket object) Create a pair of socket objects from the sockets returned by the platform socketpair() function. @@ -1342,27 +1275,21 @@ if sys.platform != "win32": """ def if_nameindex() -> list[tuple[int, str]]: - """ - if_nameindex() + """if_nameindex() Returns a list of network interface information (index, name) tuples. """ def if_nametoindex(oname: str, /) -> int: - """ - Returns the interface index corresponding to the interface name if_name. - """ + """Returns the interface index corresponding to the interface name if_name.""" if sys.version_info >= (3, 14): def if_indextoname(if_index: int, /) -> str: - """ - Returns the interface name corresponding to the interface index if_index. - """ + """Returns the interface name corresponding to the interface index if_index.""" else: def if_indextoname(index: int, /) -> str: - """ - if_indextoname(if_index) + """if_indextoname(if_index) Returns the interface name corresponding to the interface index if_index. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_sqlite3.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_sqlite3.pyi index 914f14f9e5..541fa9e751 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_sqlite3.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_sqlite3.pyi @@ -215,16 +215,12 @@ if sys.version_info >= (3, 11): # Can take or return anything depending on what's in the registry. @overload def adapt(obj: Any, proto: Any, /) -> Any: - """ - Adapt given object to given protocol. - """ + """Adapt given object to given protocol.""" @overload def adapt(obj: Any, proto: Any, alt: _T, /) -> Any | _T: ... def complete_statement(statement: str) -> bool: - """ - Checks if a string contains a complete SQL statement. - """ + """Checks if a string contains a complete SQL statement.""" if sys.version_info >= (3, 12): @overload @@ -239,8 +235,7 @@ if sys.version_info >= (3, 12): *, autocommit: bool = ..., ) -> Connection: - """ - Open a connection to the SQLite database file 'database'. + """Open a connection to the SQLite database file 'database'. You can use ":memory:" to open a database connection to a database that resides in RAM instead of on disk. @@ -289,8 +284,7 @@ else: cached_statements: int = 128, uri: bool = False, ) -> Connection: - """ - Opens a connection to the SQLite database file database. + """Opens a connection to the SQLite database file database. You can use ":memory:" to open a database connection to a database that resides in RAM instead of on disk. @@ -321,15 +315,12 @@ else: ) -> _ConnectionT: ... def enable_callback_tracebacks(enable: bool, /) -> None: - """ - Enable or disable callback functions throwing errors to stderr. - """ + """Enable or disable callback functions throwing errors to stderr.""" if sys.version_info < (3, 12): # takes a pos-or-keyword argument because there is a C wrapper def enable_shared_cache(do_enable: int) -> None: - """ - Enable or disable shared cache mode for the calling thread. + """Enable or disable shared cache mode for the calling thread. This method is deprecated and will be removed in Python 3.12. Shared cache is strongly discouraged by the SQLite 3 documentation. @@ -339,26 +330,20 @@ if sys.version_info < (3, 12): if sys.version_info >= (3, 10): def register_adapter(type: type[_T], adapter: _Adapter[_T], /) -> None: - """ - Register a function to adapt Python objects to SQLite values. - """ + """Register a function to adapt Python objects to SQLite values.""" def register_converter(typename: str, converter: _Converter, /) -> None: - """ - Register a function to convert SQLite values to Python objects. - """ + """Register a function to convert SQLite values to Python objects.""" else: def register_adapter(type: type[_T], caster: _Adapter[_T], /) -> None: - """ - register_adapter(type, callable) + """register_adapter(type, callable) Registers an adapter with sqlite3's adapter registry. """ def register_converter(name: str, converter: _Converter, /) -> None: - """ - register_converter(typename, callable) + """register_converter(typename, callable) Registers a converter with sqlite3. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_ssl.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_ssl.pyi index 56998dd438..84b5dba610 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_ssl.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_ssl.pyi @@ -51,22 +51,18 @@ class _CertInfo(TypedDict): crlDistributionPoints: NotRequired[tuple[str, ...] | None] def RAND_add(string: str | ReadableBuffer, entropy: float, /) -> None: - """ - Mix string into the OpenSSL PRNG state. + """Mix string into the OpenSSL PRNG state. entropy (a float) is a lower bound on the entropy contained in string. See RFC 4086. """ def RAND_bytes(n: int, /) -> bytes: - """ - Generate n cryptographically strong pseudo-random bytes. - """ + """Generate n cryptographically strong pseudo-random bytes.""" if sys.version_info < (3, 12): def RAND_pseudo_bytes(n: int, /) -> tuple[bytes, bool]: - """ - Generate n pseudo-random bytes. + """Generate n pseudo-random bytes. Return a pair (bytes, is_cryptographic). is_cryptographic is True if the bytes generated are cryptographically strong. @@ -76,37 +72,48 @@ if sys.version_info < (3, 10): def RAND_egd(path: str) -> None: ... def RAND_status() -> bool: - """ - Returns True if the OpenSSL PRNG has been seeded with enough data and False if not. + """Returns True if the OpenSSL PRNG has been seeded with enough data and False if not. It is necessary to seed the PRNG with RAND_add() on some platforms before using the ssl() function. """ def get_default_verify_paths() -> tuple[str, str, str, str]: - """ - Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs. + """Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs. The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'. """ if sys.platform == "win32": _EnumRetType: TypeAlias = list[tuple[bytes, str, set[str] | bool]] - def enum_certificates(store_name: str) -> _EnumRetType: ... - def enum_crls(store_name: str) -> _EnumRetType: ... + def enum_certificates(store_name: str) -> _EnumRetType: + """Retrieve certificates from Windows' cert store. + + store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide + more cert storages, too. The function returns a list of (bytes, + encoding_type, trust) tuples. The encoding_type flag can be interpreted + with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either + a set of OIDs or the boolean True. + """ + + def enum_crls(store_name: str) -> _EnumRetType: + """Retrieve CRLs from Windows' cert store. + + store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide + more cert storages, too. The function returns a list of (bytes, + encoding_type) tuples. The encoding_type flag can be interpreted with + X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. + """ def txt2obj(txt: str, name: bool = False) -> tuple[int, str, str, str]: - """ - Lookup NID, short name, long name and OID of an ASN1_OBJECT. + """Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default objects are looked up by OID. With name=True short and long name are also matched. """ def nid2obj(nid: int, /) -> tuple[int, str, str, str]: - """ - Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID. - """ + """Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.""" class _SSLContext: check_hostname: bool @@ -124,8 +131,7 @@ class _SSLContext: verify_mode: int def __new__(cls, protocol: int, /) -> Self: ... def cert_store_stats(self) -> dict[str, int]: - """ - Returns quantities of loaded X.509 certificates. + """Returns quantities of loaded X.509 certificates. X.509 certificates with a CA extension and certificate revocation lists inside the context's cert store. @@ -136,8 +142,7 @@ class _SSLContext: @overload def get_ca_certs(self, binary_form: Literal[False] = False) -> list[_PeerCertRetDictType]: - """ - Returns a list of dicts with information of loaded CA certs. + """Returns a list of dicts with information of loaded CA certs. If the optional argument is True, returns a DER-encoded copy of the CA certificate. @@ -177,8 +182,7 @@ class MemoryBIO: pending: int def __new__(self) -> Self: ... def read(self, size: int = -1, /) -> bytes: - """ - Read up to size bytes from the memory BIO. + """Read up to size bytes from the memory BIO. If size is not specified, read the entire buffer. If the return value is an empty bytes instance, this means either @@ -187,15 +191,13 @@ class MemoryBIO: """ def write(self, b: ReadableBuffer, /) -> int: - """ - Writes the bytes b into the memory BIO. + """Writes the bytes b into the memory BIO. Returns the number of bytes written. """ def write_eof(self) -> None: - """ - Write an EOF marker to the memory BIO. + """Write an EOF marker to the memory BIO. When all data has been read, the "eof" property will be True. """ @@ -205,33 +207,23 @@ class SSLSession: __hash__: ClassVar[None] # type: ignore[assignment] @property def has_ticket(self) -> bool: - """ - Does the session contain a ticket? - """ + """Does the session contain a ticket?""" @property def id(self) -> bytes: - """ - Session ID. - """ + """Session ID.""" @property def ticket_lifetime_hint(self) -> int: - """ - Ticket life time hint. - """ + """Ticket life time hint.""" @property def time(self) -> int: - """ - Session creation time (seconds since epoch). - """ + """Session creation time (seconds since epoch).""" @property def timeout(self) -> int: - """ - Session timeout (delta in seconds). - """ + """Session timeout (delta in seconds).""" # _ssl.Certificate is weird: it can't be instantiated or subclassed. # Instances can only be created via methods of the private _ssl._SSLSocket class, diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_stat.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_stat.pyi index 7d2039c847..4c391ff533 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_stat.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_stat.pyi @@ -137,89 +137,73 @@ UF_NOUNLINK: Final = 0x00000010 UF_OPAQUE: Final = 0x00000008 def S_IMODE(mode: int, /) -> int: - """ - Return the portion of the file's mode that can be set by os.chmod(). - """ + """Return the portion of the file's mode that can be set by os.chmod().""" def S_IFMT(mode: int, /) -> int: - """ - Return the portion of the file's mode that describes the file type. - """ + """Return the portion of the file's mode that describes the file type.""" def S_ISBLK(mode: int, /) -> bool: - """ - S_ISBLK(mode) -> bool + """S_ISBLK(mode) -> bool Return True if mode is from a block special device file. """ def S_ISCHR(mode: int, /) -> bool: - """ - S_ISCHR(mode) -> bool + """S_ISCHR(mode) -> bool Return True if mode is from a character special device file. """ def S_ISDIR(mode: int, /) -> bool: - """ - S_ISDIR(mode) -> bool + """S_ISDIR(mode) -> bool Return True if mode is from a directory. """ def S_ISDOOR(mode: int, /) -> bool: - """ - S_ISDOOR(mode) -> bool + """S_ISDOOR(mode) -> bool Return True if mode is from a door. """ def S_ISFIFO(mode: int, /) -> bool: - """ - S_ISFIFO(mode) -> bool + """S_ISFIFO(mode) -> bool Return True if mode is from a FIFO (named pipe). """ def S_ISLNK(mode: int, /) -> bool: - """ - S_ISLNK(mode) -> bool + """S_ISLNK(mode) -> bool Return True if mode is from a symbolic link. """ def S_ISPORT(mode: int, /) -> bool: - """ - S_ISPORT(mode) -> bool + """S_ISPORT(mode) -> bool Return True if mode is from an event port. """ def S_ISREG(mode: int, /) -> bool: - """ - S_ISREG(mode) -> bool + """S_ISREG(mode) -> bool Return True if mode is from a regular file. """ def S_ISSOCK(mode: int, /) -> bool: - """ - S_ISSOCK(mode) -> bool + """S_ISSOCK(mode) -> bool Return True if mode is from a socket. """ def S_ISWHT(mode: int, /) -> bool: - """ - S_ISWHT(mode) -> bool + """S_ISWHT(mode) -> bool Return True if mode is from a whiteout. """ def filemode(mode: int, /) -> str: - """ - Convert a file's mode to a string of the form '-rwxrwxrwx' - """ + """Convert a file's mode to a string of the form '-rwxrwxrwx'""" if sys.platform == "win32": IO_REPARSE_TAG_SYMLINK: Final = 0xA000000C diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_struct.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_struct.pyi index fa0be6623a..cd7a182b4e 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_struct.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_struct.pyi @@ -34,16 +34,14 @@ from collections.abc import Iterator from typing import Any def pack(fmt: str | bytes, /, *v: Any) -> bytes: - """ - pack(format, v1, v2, ...) -> bytes + """pack(format, v1, v2, ...) -> bytes Return a bytes object containing the values v1, v2, ... packed according to the format string. See help(struct) for more on format strings. """ def pack_into(fmt: str | bytes, buffer: WriteableBuffer, offset: int, /, *v: Any) -> None: - """ - pack_into(format, buffer, offset, v1, v2, ...) + """pack_into(format, buffer, offset, v1, v2, ...) Pack the values v1, v2, ... according to the format string and write the packed bytes into the writable buffer buf starting at offset. Note @@ -52,8 +50,7 @@ def pack_into(fmt: str | bytes, buffer: WriteableBuffer, offset: int, /, *v: Any """ def unpack(format: str | bytes, buffer: ReadableBuffer, /) -> tuple[Any, ...]: - """ - Return a tuple containing values unpacked according to the format string. + """Return a tuple containing values unpacked according to the format string. The buffer's size in bytes must be calcsize(format). @@ -61,8 +58,7 @@ def unpack(format: str | bytes, buffer: ReadableBuffer, /) -> tuple[Any, ...]: """ def unpack_from(format: str | bytes, /, buffer: ReadableBuffer, offset: int = 0) -> tuple[Any, ...]: - """ - Return a tuple containing values unpacked according to the format string. + """Return a tuple containing values unpacked according to the format string. The buffer's size, minus offset, must be at least calcsize(format). @@ -70,8 +66,7 @@ def unpack_from(format: str | bytes, /, buffer: ReadableBuffer, offset: int = 0) """ def iter_unpack(format: str | bytes, buffer: ReadableBuffer, /) -> Iterator[tuple[Any, ...]]: - """ - Return an iterator yielding tuples unpacked from the given bytes. + """Return an iterator yielding tuples unpacked from the given bytes. The bytes are unpacked according to the format string, like a repeated invocation of unpack_from(). @@ -80,31 +75,22 @@ def iter_unpack(format: str | bytes, buffer: ReadableBuffer, /) -> Iterator[tupl """ def calcsize(format: str | bytes, /) -> int: - """ - Return size in bytes of the struct described by the format string. - """ + """Return size in bytes of the struct described by the format string.""" class Struct: - """ - Struct(fmt) --> compiled struct object - """ + """Struct(fmt) --> compiled struct object""" @property def format(self) -> str: - """ - struct format string - """ + """struct format string""" @property def size(self) -> int: - """ - struct size in bytes - """ + """struct size in bytes""" def __init__(self, format: str | bytes) -> None: ... def pack(self, *v: Any) -> bytes: - """ - S.pack(v1, v2, ...) -> bytes + """S.pack(v1, v2, ...) -> bytes Return a bytes object containing values v1, v2, ... packed according to the format string S.format. See help(struct) for more on format @@ -112,8 +98,7 @@ class Struct: """ def pack_into(self, buffer: WriteableBuffer, offset: int, *v: Any) -> None: - """ - S.pack_into(buffer, offset, v1, v2, ...) + """S.pack_into(buffer, offset, v1, v2, ...) Pack the values v1, v2, ... according to the format string S.format and write the packed bytes into the writable buffer buf starting at @@ -122,8 +107,7 @@ class Struct: """ def unpack(self, buffer: ReadableBuffer, /) -> tuple[Any, ...]: - """ - Return a tuple containing unpacked values. + """Return a tuple containing unpacked values. Unpack according to the format string Struct.format. The buffer's size in bytes must be Struct.size. @@ -132,8 +116,7 @@ class Struct: """ def unpack_from(self, buffer: ReadableBuffer, offset: int = 0) -> tuple[Any, ...]: - """ - Return a tuple containing unpacked values. + """Return a tuple containing unpacked values. Values are unpacked according to the format string Struct.format. @@ -144,8 +127,7 @@ class Struct: """ def iter_unpack(self, buffer: ReadableBuffer, /) -> Iterator[tuple[Any, ...]]: - """ - Return an iterator yielding tuples. + """Return an iterator yielding tuples. Tuples are unpacked from the given bytes source, like a repeated invocation of unpack_from(). diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_thread.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_thread.pyi index 6fa32b97d0..e2abe85205 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_thread.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_thread.pyi @@ -17,8 +17,7 @@ _Ts = TypeVarTuple("_Ts") error = RuntimeError def _count() -> int: - """ - Return the number of currently running Python threads, excluding + """Return the number of currently running Python threads, excluding the main thread. The returned number comprises all threads created through `start_new_thread()` as well as `threading.Thread`, and not yet finished. @@ -30,8 +29,7 @@ def _count() -> int: @final class RLock: def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: - """ - Lock the lock. `blocking` indicates whether we should wait + """Lock the lock. `blocking` indicates whether we should wait for the lock to be available or not. If `blocking` is False and another thread holds the lock, the method will return False immediately. If `blocking` is True and another thread holds @@ -46,8 +44,7 @@ class RLock: """ def release(self) -> None: - """ - Release the lock, allowing another thread that is blocked waiting for + """Release the lock, allowing another thread that is blocked waiting for the lock to acquire the lock. The lock must be in the locked state, and must be locked by the same thread that unlocks it; otherwise a `RuntimeError` is raised. @@ -58,13 +55,10 @@ class RLock: """ __enter__ = acquire def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: - """ - Release the lock. - """ + """Release the lock.""" if sys.version_info >= (3, 14): def locked(self) -> bool: - """ - locked() + """locked() Return a boolean indicating whether this object is locked right now. """ @@ -81,8 +75,7 @@ if sys.version_info >= (3, 13): def start_joinable_thread( function: Callable[[], object], handle: _ThreadHandle | None = None, daemon: bool = True ) -> _ThreadHandle: - """ - *For internal use only*: start a new thread. + """*For internal use only*: start a new thread. Like start_new_thread(), this starts a new thread calling the given function. Unlike start_new_thread(), this returns a handle object with methods to join @@ -95,8 +88,7 @@ if sys.version_info >= (3, 13): @final class lock: - """ - A lock object is a synchronization primitive. To create a lock, + """A lock object is a synchronization primitive. To create a lock, call threading.Lock(). Methods are: acquire() -- lock the lock, possibly blocking until it can be obtained @@ -109,8 +101,7 @@ if sys.version_info >= (3, 13): """ def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: - """ - Lock the lock. Without argument, this blocks if the lock is already + """Lock the lock. Without argument, this blocks if the lock is already locked (even by the same thread), waiting for another thread to release the lock, and return True once the lock is acquired. With an argument, this will only block if the argument is true, @@ -119,50 +110,36 @@ if sys.version_info >= (3, 13): """ def release(self) -> None: - """ - Release the lock, allowing another thread that is blocked waiting for + """Release the lock, allowing another thread that is blocked waiting for the lock to acquire the lock. The lock must be in the locked state, but it needn't be locked by the same thread that unlocks it. """ def locked(self) -> bool: - """ - Return whether the lock is in the locked state. - """ + """Return whether the lock is in the locked state.""" def acquire_lock(self, blocking: bool = True, timeout: float = -1) -> bool: - """ - An obsolete synonym of acquire(). - """ + """An obsolete synonym of acquire().""" def release_lock(self) -> None: - """ - An obsolete synonym of release(). - """ + """An obsolete synonym of release().""" def locked_lock(self) -> bool: - """ - An obsolete synonym of locked(). - """ + """An obsolete synonym of locked().""" def __enter__(self) -> bool: - """ - Lock the lock. - """ + """Lock the lock.""" def __exit__( self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: - """ - Release the lock. - """ + """Release the lock.""" LockType = lock else: @final class LockType: - """ - A lock object is a synchronization primitive. To create a lock, + """A lock object is a synchronization primitive. To create a lock, call threading.Lock(). Methods are: acquire() -- lock the lock, possibly blocking until it can be obtained @@ -175,8 +152,7 @@ else: """ def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: - """ - acquire(blocking=True, timeout=-1) -> bool + """acquire(blocking=True, timeout=-1) -> bool (acquire_lock() is an obsolete synonym) Lock the lock. Without argument, this blocks if the lock is already @@ -188,8 +164,7 @@ else: """ def release(self) -> None: - """ - release() + """release() (release_lock() is an obsolete synonym) Release the lock, allowing another thread that is blocked waiting for @@ -198,16 +173,14 @@ else: """ def locked(self) -> bool: - """ - locked() -> bool + """locked() -> bool (locked_lock() is an obsolete synonym) Return whether the lock is in the locked state. """ def acquire_lock(self, blocking: bool = True, timeout: float = -1) -> bool: - """ - acquire(blocking=True, timeout=-1) -> bool + """acquire(blocking=True, timeout=-1) -> bool (acquire_lock() is an obsolete synonym) Lock the lock. Without argument, this blocks if the lock is already @@ -219,8 +192,7 @@ else: """ def release_lock(self) -> None: - """ - release() + """release() (release_lock() is an obsolete synonym) Release the lock, allowing another thread that is blocked waiting for @@ -229,16 +201,14 @@ else: """ def locked_lock(self) -> bool: - """ - locked() -> bool + """locked() -> bool (locked_lock() is an obsolete synonym) Return whether the lock is in the locked state. """ def __enter__(self) -> bool: - """ - acquire(blocking=True, timeout=-1) -> bool + """acquire(blocking=True, timeout=-1) -> bool (acquire_lock() is an obsolete synonym) Lock the lock. Without argument, this blocks if the lock is already @@ -252,8 +222,7 @@ else: def __exit__( self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: - """ - release() + """release() (release_lock() is an obsolete synonym) Release the lock, allowing another thread that is blocked waiting for @@ -263,8 +232,7 @@ else: @overload def start_new_thread(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]], /) -> int: - """ - Start a new thread and return its identifier. + """Start a new thread and return its identifier. The thread will call the function with positional arguments from the tuple args and keyword arguments taken from the optional dictionary @@ -280,17 +248,14 @@ def start_new_thread(function: Callable[..., object], args: tuple[Any, ...], kwa # Obsolete synonym for start_new_thread() @overload def start_new(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]], /) -> int: - """ - An obsolete synonym of start_new_thread(). - """ + """An obsolete synonym of start_new_thread().""" @overload def start_new(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any], /) -> int: ... if sys.version_info >= (3, 10): def interrupt_main(signum: signal.Signals = ..., /) -> None: - """ - Simulate the arrival of the given signal in the main thread, + """Simulate the arrival of the given signal in the main thread, where the corresponding signal handler will be executed. If *signum* is omitted, SIGINT is assumed. A subthread can use this function to interrupt the main thread. @@ -300,38 +265,30 @@ if sys.version_info >= (3, 10): else: def interrupt_main() -> None: - """ - interrupt_main() + """interrupt_main() Raise a KeyboardInterrupt in the main thread. A subthread can use this function to interrupt the main thread. """ def exit() -> NoReturn: - """ - This is synonymous to ``raise SystemExit''. It will cause the current + """This is synonymous to ``raise SystemExit''. It will cause the current thread to exit silently unless the exception is caught. """ def exit_thread() -> NoReturn: # Obsolete synonym for exit() - """ - An obsolete synonym of exit(). - """ + """An obsolete synonym of exit().""" def allocate_lock() -> LockType: - """ - Create a new lock object. See help(type(threading.Lock())) for + """Create a new lock object. See help(type(threading.Lock())) for information about locks. """ def allocate() -> LockType: # Obsolete synonym for allocate_lock() - """ - An obsolete synonym of allocate_lock(). - """ + """An obsolete synonym of allocate_lock().""" def get_ident() -> int: - """ - Return a non-zero integer that uniquely identifies the current thread + """Return a non-zero integer that uniquely identifies the current thread amongst other threads that exist simultaneously. This may be used to identify per-thread resources. Even though on some platforms threads identities may appear to be @@ -341,8 +298,7 @@ def get_ident() -> int: """ def stack_size(size: int = 0, /) -> int: - """ - Return the thread stack size used when creating new threads. The + """Return the thread stack size used when creating new threads. The optional size argument specifies the stack size (in bytes) to be used for subsequently created threads, and must be 0 (use platform or configured default) or a positive integer value of at least 32,768 (32k). @@ -363,16 +319,14 @@ def stack_size(size: int = 0, /) -> int: TIMEOUT_MAX: float def get_native_id() -> int: # only available on some platforms - """ - Return a non-negative integer identifying the thread as reported + """Return a non-negative integer identifying the thread as reported by the OS (kernel). This may be used to uniquely identify a particular thread within a system. """ @final class _ExceptHookArgs(structseq[Any], tuple[type[BaseException], BaseException | None, TracebackType | None, Thread | None]): - """ - ExceptHookArgs + """ExceptHookArgs Type used to pass arguments to threading.excepthook. """ @@ -382,47 +336,34 @@ class _ExceptHookArgs(structseq[Any], tuple[type[BaseException], BaseException | @property def exc_type(self) -> type[BaseException]: - """ - Exception type - """ + """Exception type""" @property def exc_value(self) -> BaseException | None: - """ - Exception value - """ + """Exception value""" @property def exc_traceback(self) -> TracebackType | None: - """ - Exception traceback - """ + """Exception traceback""" @property def thread(self) -> Thread | None: - """ - Thread - """ + """Thread""" _excepthook: Callable[[_ExceptHookArgs], Any] if sys.version_info >= (3, 12): def daemon_threads_allowed() -> bool: - """ - Return True if daemon threads are allowed in the current interpreter, + """Return True if daemon threads are allowed in the current interpreter, and False otherwise. """ if sys.version_info >= (3, 14): def set_name(name: str) -> None: - """ - Set the name of the current thread. - """ + """Set the name of the current thread.""" class _local: - """ - Thread-local data - """ + """Thread-local data""" def __getattribute__(self, name: str, /) -> Any: ... def __setattr__(self, name: str, value: Any, /) -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_threading_local.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_threading_local.pyi index 774c54f1ee..222a9be61e 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_threading_local.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_threading_local.pyi @@ -16,9 +16,7 @@ __all__ = ["local"] _LocalDict: TypeAlias = dict[Any, Any] class _localimpl: - """ - A class managing thread-local dicts - """ + """A class managing thread-local dicts""" key: str dicts: dict[int, tuple[ReferenceType[Any], _LocalDict]] @@ -26,15 +24,12 @@ class _localimpl: localargs: tuple[list[Any], dict[str, Any]] locallock: RLock def get_dict(self) -> _LocalDict: - """ - Return the dict for the current thread. Raises KeyError if none + """Return the dict for the current thread. Raises KeyError if none defined. """ def create_dict(self) -> _LocalDict: - """ - Create a new dict for the current thread, and return it. - """ + """Create a new dict for the current thread, and return it.""" class local: def __new__(cls, /, *args: Any, **kw: Any) -> Self: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_tkinter.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_tkinter.pyi index d20a05e927..001054fd8b 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_tkinter.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_tkinter.pyi @@ -20,15 +20,11 @@ from typing_extensions import TypeAlias class Tcl_Obj: @property def string(self) -> str: - """ - the string representation of this object, either as str or bytes - """ + """the string representation of this object, either as str or bytes""" @property def typename(self) -> str: - """ - name of the Tcl type - """ + """name of the Tcl type""" __hash__: ClassVar[None] # type: ignore[assignment] def __eq__(self, value, /): ... def __ge__(self, value, /): ... @@ -99,14 +95,10 @@ class TkappType: def willdispatch(self): ... if sys.version_info >= (3, 12): def gettrace(self, /) -> _TkinterTraceFunc | None: - """ - Get the tracing function. - """ + """Get the tracing function.""" def settrace(self, func: _TkinterTraceFunc | None, /) -> None: - """ - Set the tracing function. - """ + """Set the tracing function.""" # These should be kept in sync with tkinter.tix constants, except ALL_EVENTS which doesn't match TCL_ALL_EVENTS ALL_EVENTS: Final = -3 @@ -139,8 +131,7 @@ if sys.version_info >= (3, 13): use: str | None = None, /, ): - """ - wantTk + """wantTk if false, then Tk_Init() doesn't get called sync if true, then pass -sync to wish @@ -160,8 +151,7 @@ else: use: str | None = None, /, ): - """ - wantTk + """wantTk if false, then Tk_Init() doesn't get called sync if true, then pass -sync to wish @@ -170,13 +160,10 @@ else: """ def getbusywaitinterval(): - """ - Return the current busy-wait interval between successive calls to Tcl_DoOneEvent in a threaded Python interpreter. - """ + """Return the current busy-wait interval between successive calls to Tcl_DoOneEvent in a threaded Python interpreter.""" def setbusywaitinterval(new_val, /): - """ - Set the busy-wait interval in milliseconds between successive calls to Tcl_DoOneEvent in a threaded Python interpreter. + """Set the busy-wait interval in milliseconds between successive calls to Tcl_DoOneEvent in a threaded Python interpreter. It should be set to a divisor of the maximum time between frames in an animation. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_tracemalloc.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_tracemalloc.pyi index e44a188c21..3f78b39076 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_tracemalloc.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_tracemalloc.pyi @@ -6,8 +6,7 @@ from collections.abc import Sequence from tracemalloc import _FrameTuple, _TraceTuple def _get_object_traceback(obj: object, /) -> Sequence[_FrameTuple] | None: - """ - Get the traceback where the Python object obj was allocated. + """Get the traceback where the Python object obj was allocated. Return a tuple of (filename: str, lineno: int) tuples. Return None if the tracemalloc module is disabled or did not @@ -15,8 +14,7 @@ def _get_object_traceback(obj: object, /) -> Sequence[_FrameTuple] | None: """ def _get_traces() -> Sequence[_TraceTuple]: - """ - Get traces of all memory blocks allocated by Python. + """Get traces of all memory blocks allocated by Python. Return a list of (size: int, traceback: tuple) tuples. traceback is a tuple of (filename: str, lineno: int) tuples. @@ -25,55 +23,45 @@ def _get_traces() -> Sequence[_TraceTuple]: """ def clear_traces() -> None: - """ - Clear traces of memory blocks allocated by Python. - """ + """Clear traces of memory blocks allocated by Python.""" def get_traceback_limit() -> int: - """ - Get the maximum number of frames stored in the traceback of a trace. + """Get the maximum number of frames stored in the traceback of a trace. By default, a trace of an allocated memory block only stores the most recent frame: the limit is 1. """ def get_traced_memory() -> tuple[int, int]: - """ - Get the current size and peak size of memory blocks traced by tracemalloc. + """Get the current size and peak size of memory blocks traced by tracemalloc. Returns a tuple: (current: int, peak: int). """ def get_tracemalloc_memory() -> int: - """ - Get the memory usage in bytes of the tracemalloc module. + """Get the memory usage in bytes of the tracemalloc module. This memory is used internally to trace memory allocations. """ def is_tracing() -> bool: - """ - Return True if the tracemalloc module is tracing Python memory allocations. - """ + """Return True if the tracemalloc module is tracing Python memory allocations.""" def reset_peak() -> None: - """ - Set the peak size of memory blocks traced by tracemalloc to the current size. + """Set the peak size of memory blocks traced by tracemalloc to the current size. Do nothing if the tracemalloc module is not tracing memory allocations. """ def start(nframe: int = 1, /) -> None: - """ - Start tracing Python memory allocations. + """Start tracing Python memory allocations. Also set the maximum number of frames stored in the traceback of a trace to nframe. """ def stop() -> None: - """ - Stop tracing Python memory allocations. + """Stop tracing Python memory allocations. Also clear traces of memory blocks allocated by Python. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_warnings.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_warnings.pyi index f456df1e18..07458b7991 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_warnings.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_warnings.pyi @@ -20,8 +20,7 @@ if sys.version_info >= (3, 12): *, skip_file_prefixes: tuple[str, ...] = (), ) -> None: - """ - Issue a warning, or maybe ignore it or raise an exception. + """Issue a warning, or maybe ignore it or raise an exception. message Text of the warning message. @@ -50,9 +49,7 @@ if sys.version_info >= (3, 12): else: @overload def warn(message: str, category: type[Warning] | None = None, stacklevel: int = 1, source: Any | None = None) -> None: - """ - Issue a warning, or maybe ignore it or raise an exception. - """ + """Issue a warning, or maybe ignore it or raise an exception.""" @overload def warn(message: Warning, category: Any = None, stacklevel: int = 1, source: Any | None = None) -> None: ... @@ -68,9 +65,7 @@ def warn_explicit( module_globals: dict[str, Any] | None = ..., source: Any | None = ..., ) -> None: - """ - Issue a warning, or maybe ignore it or raise an exception. - """ + """Issue a warning, or maybe ignore it or raise an exception.""" @overload def warn_explicit( diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_weakref.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_weakref.pyi index 09cbef9a64..fa21b7e8fd 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_weakref.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_weakref.pyi @@ -10,20 +10,15 @@ _C = TypeVar("_C", bound=Callable[..., Any]) _T = TypeVar("_T") def getweakrefcount(object: Any, /) -> int: - """ - Return the number of weak references to 'object'. - """ + """Return the number of weak references to 'object'.""" def getweakrefs(object: Any, /) -> list[Any]: - """ - Return a list of all weak reference objects pointing to 'object'. - """ + """Return a list of all weak reference objects pointing to 'object'.""" # Return CallableProxyType if object is callable, ProxyType otherwise @overload def proxy(object: _C, callback: Callable[[_C], Any] | None = None, /) -> CallableProxyType[_C]: - """ - Create a proxy object that weakly references 'object'. + """Create a proxy object that weakly references 'object'. 'callback', if given, is called with a reference to the proxy when 'object' is about to be finalized. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_weakrefset.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_weakrefset.pyi index 68b901cf8c..7b5f0af1f7 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_weakrefset.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_weakrefset.pyi @@ -46,8 +46,7 @@ class WeakSet(MutableSet[_T]): def __or__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... def isdisjoint(self, other: Iterable[_T]) -> bool: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_winapi.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_winapi.pyi index 0f71a06877..29c121859d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_winapi.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_winapi.pyi @@ -172,7 +172,9 @@ if sys.platform == "win32": ERROR_ACCESS_DENIED: Final = 5 ERROR_PRIVILEGE_NOT_HELD: Final = 1314 - def CloseHandle(handle: int, /) -> None: ... + def CloseHandle(handle: int, /) -> None: + """Close handle.""" + @overload def ConnectNamedPipe(handle: int, overlapped: Literal[True]) -> Overlapped: ... @overload @@ -201,7 +203,15 @@ if sys.platform == "win32": security_attributes: int, /, ) -> int: ... - def CreatePipe(pipe_attrs: Any, size: int, /) -> tuple[int, int]: ... + def CreatePipe(pipe_attrs: Any, size: int, /) -> tuple[int, int]: + """Create an anonymous pipe. + + pipe_attrs + Ignored internally, can be None. + + Returns a 2-tuple of handles, to the read and write ends of the pipe. + """ + def CreateProcess( application_name: str | None, command_line: str | None, @@ -213,7 +223,20 @@ if sys.platform == "win32": current_directory: str | None, startup_info: Any, /, - ) -> tuple[int, int, int, int]: ... + ) -> tuple[int, int, int, int]: + """Create a new process and its primary thread. + + command_line + Can be str or None + proc_attrs + Ignored internally, can be None. + thread_attrs + Ignored internally, can be None. + + The return value is a tuple of the process handle, thread handle, + process ID, and thread ID. + """ + def DuplicateHandle( source_process_handle: int, source_handle: int, @@ -222,16 +245,49 @@ if sys.platform == "win32": inherit_handle: bool, options: int = 0, /, - ) -> int: ... + ) -> int: + """Return a duplicate handle object. + + The duplicate handle refers to the same object as the original + handle. Therefore, any changes to the object are reflected + through both handles. + """ + def ExitProcess(ExitCode: int, /) -> NoReturn: ... - def GetACP() -> int: ... + def GetACP() -> int: + """Get the current Windows ANSI code page identifier.""" + def GetFileType(handle: int) -> int: ... - def GetCurrentProcess() -> int: ... - def GetExitCodeProcess(process: int, /) -> int: ... + def GetCurrentProcess() -> int: + """Return a handle object for the current process.""" + + def GetExitCodeProcess(process: int, /) -> int: + """Return the termination status of the specified process.""" + def GetLastError() -> int: ... - def GetModuleFileName(module_handle: int, /) -> str: ... - def GetStdHandle(std_handle: int, /) -> int: ... - def GetVersion() -> int: ... + def GetModuleFileName(module_handle: int, /) -> str: + """Return the fully-qualified path for the file that contains module. + + The module must have been loaded by the current process. + + The module parameter should be a handle to the loaded module + whose path is being requested. If this parameter is 0, + GetModuleFileName retrieves the path of the executable file + of the current process. + """ + + def GetStdHandle(std_handle: int, /) -> int: + """Return a handle to the specified standard device. + + std_handle + One of STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, or STD_ERROR_HANDLE. + + The integer associated with the handle object is returned. + """ + + def GetVersion() -> int: + """Return the version number of the current operating system.""" + def OpenProcess(desired_access: int, inherit_handle: bool, process_id: int, /) -> int: ... def PeekNamedPipe(handle: int, size: int = 0, /) -> tuple[int, int] | tuple[bytes, int, int]: ... if sys.version_info >= (3, 10): @@ -247,9 +303,18 @@ if sys.platform == "win32": def SetNamedPipeHandleState( named_pipe: int, mode: int | None, max_collection_count: int | None, collect_data_timeout: int | None, / ) -> None: ... - def TerminateProcess(handle: int, exit_code: int, /) -> None: ... + def TerminateProcess(handle: int, exit_code: int, /) -> None: + """Terminate the specified process and all of its threads.""" + def WaitForMultipleObjects(handle_seq: Sequence[int], wait_flag: bool, milliseconds: int = 0xFFFFFFFF, /) -> int: ... - def WaitForSingleObject(handle: int, milliseconds: int, /) -> int: ... + def WaitForSingleObject(handle: int, milliseconds: int, /) -> int: + """Wait for a single object. + + Wait until the specified object is in the signaled state or + the time-out interval elapses. The timeout value is specified + in milliseconds. + """ + def WaitNamedPipe(name: str, timeout: int, /) -> None: ... @overload def WriteFile(handle: int, buffer: ReadableBuffer, overlapped: Literal[True]) -> tuple[Overlapped, int]: ... @@ -259,19 +324,51 @@ if sys.platform == "win32": def WriteFile(handle: int, buffer: ReadableBuffer, overlapped: int | bool) -> tuple[Any, int]: ... @final class Overlapped: + """OVERLAPPED structure wrapper""" + event: int def GetOverlappedResult(self, wait: bool, /) -> tuple[int, int]: ... def cancel(self) -> None: ... def getbuffer(self) -> bytes | None: ... if sys.version_info >= (3, 13): - def BatchedWaitForMultipleObjects( - handle_seq: Sequence[int], wait_all: bool, milliseconds: int = 0xFFFFFFFF - ) -> list[int]: ... + def BatchedWaitForMultipleObjects(handle_seq: Sequence[int], wait_all: bool, milliseconds: int = 0xFFFFFFFF) -> list[int]: + """Supports a larger number of handles than WaitForMultipleObjects + + Note that the handles may be waited on other threads, which could cause + issues for objects like mutexes that become associated with the thread + that was waiting for them. Objects may also be left signalled, even if + the wait fails. + + It is recommended to use WaitForMultipleObjects whenever possible, and + only switch to BatchedWaitForMultipleObjects for scenarios where you + control all the handles involved, such as your own thread pool or + files, and all wait objects are left unmodified by a wait (for example, + manual reset events, threads, and files/pipes). + + Overlapped handles returned from this module use manual reset events. + """ + def CreateEventW(security_attributes: int, manual_reset: bool, initial_state: bool, name: str | None) -> int: ... def CreateMutexW(security_attributes: int, initial_owner: bool, name: str) -> int: ... - def GetLongPathName(path: str) -> str: ... - def GetShortPathName(path: str) -> str: ... + def GetLongPathName(path: str) -> str: + """Return the long version of the provided path. + + If the path is already in its long form, returns the same value. + + The path must already be a 'str'. If the type is not known, use + os.fsdecode before calling this function. + """ + + def GetShortPathName(path: str) -> str: + """Return the short version of the provided path. + + If the path is already in its short form, returns the same value. + + The path must already be a 'str'. If the type is not known, use + os.fsdecode before calling this function. + """ + def OpenEventW(desired_access: int, inherit_handle: bool, name: str) -> int: ... def OpenMutexW(desired_access: int, inherit_handle: bool, name: str) -> int: ... def ReleaseMutex(mutex: int) -> None: ... @@ -279,5 +376,14 @@ if sys.platform == "win32": def SetEvent(event: int) -> None: ... 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 CopyFile2(existing_file_name: str, new_file_name: str, flags: int, progress_routine: int | None = None) -> int: + """Copies a file from one name to a new name. + + This is implemented using the CopyFile2 API, which preserves all stat + and metadata information apart from security attributes. + + progress_routine is reserved for future use, but is currently not + implemented. Its value is ignored. + """ + def NeedCurrentDirectoryForExePath(exe_name: str, /) -> bool: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/_zstd.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/_zstd.pyi index 635abbee9e..155528e0b7 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/_zstd.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/_zstd.pyi @@ -46,8 +46,7 @@ _ZstdCompressorFlushFrame: TypeAlias = Literal[2] @final class ZstdCompressor: - """ - Create a compressor object for compressing data incrementally. + """Create a compressor object for compressing data incrementally. level The compression level to use. Defaults to COMPRESSION_LEVEL_DEFAULT. @@ -69,8 +68,7 @@ class ZstdCompressor: def compress( self, /, data: ReadableBuffer, mode: _ZstdCompressorContinue | _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 0 ) -> bytes: - """ - Provide data to the compressor object. + """Provide data to the compressor object. mode Can be these 3 values ZstdCompressor.CONTINUE, @@ -82,8 +80,7 @@ class ZstdCompressor: """ def flush(self, /, mode: _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 2) -> bytes: - """ - Finish the compression process. + """Finish the compression process. mode Can be these 2 values ZstdCompressor.FLUSH_FRAME, @@ -95,8 +92,7 @@ class ZstdCompressor: """ def set_pledged_input_size(self, size: int | None, /) -> None: - """ - Set the uncompressed content size to be written into the frame header. + """Set the uncompressed content size to be written into the frame header. size The size of the uncompressed data to be provided to the compressor. @@ -112,8 +108,7 @@ class ZstdCompressor: @property def last_mode(self) -> _ZstdCompressorContinue | _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame: - """ - The last mode used to this compressor object, its value can be .CONTINUE, + """The last mode used to this compressor object, its value can be .CONTINUE, .FLUSH_BLOCK, .FLUSH_FRAME. Initialized to .FLUSH_FRAME. It can be used to get the current state of a compressor, such as, data @@ -122,8 +117,7 @@ class ZstdCompressor: @final class ZstdDecompressor: - """ - Create a decompressor object for decompressing data incrementally. + """Create a decompressor object for decompressing data incrementally. zstd_dict A ZstdDict object, a pre-trained Zstandard dictionary. @@ -136,8 +130,7 @@ class ZstdDecompressor: def __init__(self, zstd_dict: ZstdDict | None = None, options: Mapping[int, int] | None = None) -> None: ... def decompress(self, /, data: ReadableBuffer, max_length: int = -1) -> bytes: - """ - Decompress *data*, returning uncompressed bytes if possible, or b'' otherwise. + """Decompress *data*, returning uncompressed bytes if possible, or b'' otherwise. data A bytes-like object, Zstandard data to be decompressed. @@ -162,15 +155,13 @@ class ZstdDecompressor: @property def eof(self) -> bool: - """ - True means the end of the first frame has been reached. If decompress data + """True means the end of the first frame has been reached. If decompress data after that, an EOFError exception will be raised. """ @property def needs_input(self) -> bool: - """ - If the max_length output limit in .decompress() method has been reached, + """If the max_length output limit in .decompress() method has been reached, and the decompressor has (or may has) unconsumed input data, it will be set to False. In this case, passing b'' to the .decompress() method may output further data. @@ -178,8 +169,7 @@ class ZstdDecompressor: @property def unused_data(self) -> bytes: - """ - A bytes object of un-consumed input data. + """A bytes object of un-consumed input data. When ZstdDecompressor object stops after a frame is decompressed, unused input data after the frame. Otherwise this will be b''. @@ -187,8 +177,7 @@ class ZstdDecompressor: @final class ZstdDict: - """ - Represents a Zstandard dictionary. + """Represents a Zstandard dictionary. dict_content The content of a Zstandard dictionary as a bytes-like object. @@ -203,14 +192,11 @@ class ZstdDict: def __init__(self, dict_content: bytes, /, *, is_raw: bool = False) -> None: ... def __len__(self, /) -> int: - """ - Return len(self). - """ + """Return len(self).""" @property def as_digested_dict(self) -> tuple[Self, int]: - """ - Load as a digested dictionary to compressor. + """Load as a digested dictionary to compressor. Pass this attribute as zstd_dict argument: compress(dat, zstd_dict=zd.as_digested_dict) @@ -225,8 +211,7 @@ class ZstdDict: @property def as_prefix(self) -> tuple[Self, int]: - """ - Load as a prefix to compressor/decompressor. + """Load as a prefix to compressor/decompressor. Pass this attribute as zstd_dict argument: compress(dat, zstd_dict=zd.as_prefix) @@ -239,8 +224,7 @@ class ZstdDict: @property def as_undigested_dict(self) -> tuple[Self, int]: - """ - Load as an undigested dictionary to compressor. + """Load as an undigested dictionary to compressor. Pass this attribute as zstd_dict argument: compress(dat, zstd_dict=zd.as_undigested_dict) @@ -253,14 +237,11 @@ class ZstdDict: @property def dict_content(self) -> bytes: - """ - The content of a Zstandard dictionary, as a bytes object. - """ + """The content of a Zstandard dictionary, as a bytes object.""" @property def dict_id(self) -> int: - """ - the Zstandard dictionary, an int between 0 and 2**32. + """the Zstandard dictionary, an int between 0 and 2**32. A non-zero value represents an ordinary Zstandard dictionary, conforming to the standardised format. @@ -268,15 +249,12 @@ class ZstdDict: """ class ZstdError(Exception): - """ - An error occurred in the zstd library. - """ + """An error occurred in the zstd library.""" def finalize_dict( custom_dict_bytes: bytes, samples_bytes: bytes, samples_sizes: tuple[int, ...], dict_size: int, compression_level: int, / ) -> bytes: - """ - Finalize a Zstandard dictionary. + """Finalize a Zstandard dictionary. custom_dict_bytes Custom dictionary content. @@ -291,16 +269,14 @@ def finalize_dict( """ def get_frame_info(frame_buffer: ReadableBuffer) -> tuple[int, int]: - """ - Get Zstandard frame infomation from a frame header. + """Get Zstandard frame infomation from a frame header. frame_buffer A bytes-like object, containing the header of a Zstandard frame. """ def get_frame_size(frame_buffer: ReadableBuffer) -> int: - """ - Get the size of a Zstandard frame, including the header and optional checksum. + """Get the size of a Zstandard frame, including the header and optional checksum. frame_buffer A bytes-like object, it should start from the beginning of a frame, @@ -308,8 +284,7 @@ def get_frame_size(frame_buffer: ReadableBuffer) -> int: """ def get_param_bounds(parameter: int, is_compress: bool) -> tuple[int, int]: - """ - Get CompressionParameter/DecompressionParameter bounds. + """Get CompressionParameter/DecompressionParameter bounds. parameter The parameter to get bounds. @@ -318,8 +293,7 @@ def get_param_bounds(parameter: int, is_compress: bool) -> tuple[int, int]: """ def set_parameter_types(c_parameter_type: type[CompressionParameter], d_parameter_type: type[DecompressionParameter]) -> None: - """ - Set CompressionParameter and DecompressionParameter types for validity check. + """Set CompressionParameter and DecompressionParameter types for validity check. c_parameter_type CompressionParameter IntEnum type object @@ -328,8 +302,7 @@ def set_parameter_types(c_parameter_type: type[CompressionParameter], d_paramete """ def train_dict(samples_bytes: bytes, samples_sizes: tuple[int, ...], dict_size: int, /) -> bytes: - """ - Train a Zstandard dictionary on sample data. + """Train a Zstandard dictionary on sample data. samples_bytes Concatenation of samples. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/abc.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/abc.pyi index afe9a7a120..fb4cd3efb5 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/abc.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/abc.pyi @@ -16,8 +16,7 @@ _P = ParamSpec("_P") # These definitions have special processing in mypy class ABCMeta(type): - """ - Metaclass for defining Abstract Base Classes (ABCs). + """Metaclass for defining Abstract Base Classes (ABCs). Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register @@ -41,30 +40,22 @@ class ABCMeta(type): ) -> _typeshed.Self: ... def __instancecheck__(cls: ABCMeta, instance: Any) -> bool: - """ - Override for isinstance(instance, cls). - """ + """Override for isinstance(instance, cls).""" def __subclasscheck__(cls: ABCMeta, subclass: type) -> bool: - """ - Override for issubclass(subclass, cls). - """ + """Override for issubclass(subclass, cls).""" def _dump_registry(cls: ABCMeta, file: SupportsWrite[str] | None = None) -> None: - """ - Debug helper to print the ABC registry. - """ + """Debug helper to print the ABC registry.""" def register(cls: ABCMeta, subclass: type[_T]) -> type[_T]: - """ - Register a virtual subclass of an ABC. + """Register a virtual subclass of an ABC. Returns the subclass, to allow usage as a class decorator. """ def abstractmethod(funcobj: _FuncT) -> _FuncT: - """ - A decorator indicating abstract methods. + """A decorator indicating abstract methods. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be @@ -83,8 +74,7 @@ def abstractmethod(funcobj: _FuncT) -> _FuncT: @deprecated("Use 'classmethod' with 'abstractmethod' instead") class abstractclassmethod(classmethod[_T, _P, _R_co]): - """ - A decorator indicating abstract classmethods. + """A decorator indicating abstract classmethods. Deprecated, use 'classmethod' with 'abstractmethod' instead: @@ -100,8 +90,7 @@ class abstractclassmethod(classmethod[_T, _P, _R_co]): @deprecated("Use 'staticmethod' with 'abstractmethod' instead") class abstractstaticmethod(staticmethod[_P, _R_co]): - """ - A decorator indicating abstract staticmethods. + """A decorator indicating abstract staticmethods. Deprecated, use 'staticmethod' with 'abstractmethod' instead: @@ -117,8 +106,7 @@ class abstractstaticmethod(staticmethod[_P, _R_co]): @deprecated("Use 'property' with 'abstractmethod' instead") class abstractproperty(property): - """ - A decorator indicating abstract properties. + """A decorator indicating abstract properties. Deprecated, use 'property' with 'abstractmethod' instead: @@ -132,16 +120,14 @@ class abstractproperty(property): __isabstractmethod__: Literal[True] class ABC(metaclass=ABCMeta): - """ - Helper class that provides a standard way to create an ABC using + """Helper class that provides a standard way to create an ABC using inheritance. """ __slots__ = () def get_cache_token() -> object: - """ - Returns the current ABC cache token. + """Returns the current ABC cache token. The token is an opaque object (supporting equality testing) identifying the current version of the ABC cache for virtual subclasses. The token changes @@ -150,8 +136,7 @@ def get_cache_token() -> object: if sys.version_info >= (3, 10): def update_abstractmethods(cls: type[_T]) -> type[_T]: - """ - Recalculate the set of abstract methods of an abstract class. + """Recalculate the set of abstract methods of an abstract class. If a class has had one of its abstract methods implemented after the class was created, the method will not be considered implemented until diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/aifc.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/aifc.pyi index 5f2a51e379..5acb14c894 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/aifc.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/aifc.pyi @@ -144,9 +144,7 @@ __all__ = ["Error", "open"] class Error(Exception): ... class _aifc_params(NamedTuple): - """ - _aifc_params(nchannels, sampwidth, framerate, nframes, comptype, compname) - """ + """_aifc_params(nchannels, sampwidth, framerate, nframes, comptype, compname)""" nchannels: int sampwidth: int diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/annotationlib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/annotationlib.pyi index 637bbb48fd..1ffdedbea4 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/annotationlib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/annotationlib.pyi @@ -32,8 +32,7 @@ if sys.version_info >= (3, 14): @final class ForwardRef: - """ - Wrapper that holds a forward reference. + """Wrapper that holds a forward reference. Constructor arguments: * arg: a string representing the code to be evaluated. @@ -60,8 +59,7 @@ if sys.version_info >= (3, 14): owner: object = None, format: Literal[Format.STRING], ) -> str: - """ - Evaluate the forward reference and return the value. + """Evaluate the forward reference and return the value. If the forward reference cannot be evaluated, raise an exception. """ @@ -106,8 +104,7 @@ if sys.version_info >= (3, 14): @overload def call_evaluate_function(evaluate: EvaluateFunc, format: Literal[Format.STRING], *, owner: object = None) -> str: - """ - Call an evaluate function. Evaluate functions are normally generated for + """Call an evaluate function. Evaluate functions are normally generated for the value of type aliases and the bounds, constraints, and defaults of type parameter objects. """ @@ -120,8 +117,7 @@ if sys.version_info >= (3, 14): def call_evaluate_function(evaluate: EvaluateFunc, format: Format, *, owner: object = None) -> AnnotationForm: ... @overload def call_annotate_function(annotate: AnnotateFunc, format: Literal[Format.STRING], *, owner: object = None) -> dict[str, str]: - """ - Call an __annotate__ function. __annotate__ functions are normally + """Call an __annotate__ function. __annotate__ functions are normally generated by the compiler to defer the evaluation of annotations. They can be called with any of the format arguments in the Format enum, but compiler-generated __annotate__ functions only support the VALUE format. @@ -147,8 +143,7 @@ if sys.version_info >= (3, 14): @overload def call_annotate_function(annotate: AnnotateFunc, format: Format, *, owner: object = None) -> dict[str, AnnotationForm]: ... def get_annotate_from_class_namespace(obj: Mapping[str, object]) -> AnnotateFunc | None: - """ - Retrieve the annotate function from a class namespace dictionary. + """Retrieve the annotate function from a class namespace dictionary. Return None if the namespace does not contain an annotate function. This is useful in metaclass ``__new__`` methods to retrieve the annotate function. @@ -163,8 +158,7 @@ if sys.version_info >= (3, 14): eval_str: bool = False, format: Literal[Format.STRING], ) -> dict[str, str]: - """ - Compute the annotations dict for an object. + """Compute the annotations dict for an object. obj may be a callable, class, module, or other object with __annotate__ or __annotations__ attributes. @@ -234,8 +228,7 @@ if sys.version_info >= (3, 14): format: Format = Format.VALUE, # noqa: Y011 ) -> dict[str, AnnotationForm]: ... def type_repr(value: object) -> str: - """ - Convert a Python value to a format suitable for use with the STRING format. + """Convert a Python value to a format suitable for use with the STRING format. This is intended as a helper for tools that support the STRING format but do not have access to the code that originally produced the annotations. It uses @@ -243,8 +236,7 @@ if sys.version_info >= (3, 14): """ def annotations_to_string(annotations: SupportsItems[str, object]) -> dict[str, str]: - """ - Convert an annotation dict containing values to approximately the STRING format. + """Convert an annotation dict containing values to approximately the STRING format. Always returns a fresh a dictionary. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/argparse.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/argparse.pyi index f8f51398ba..5bf371e2b5 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/argparse.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/argparse.pyi @@ -105,8 +105,7 @@ ZERO_OR_MORE: Final = "*" _UNRECOGNIZED_ARGS_ATTR: Final = "_unrecognized_args" # undocumented class ArgumentError(Exception): - """ - An error from creating or using an argument (optional or positional). + """An error from creating or using an argument (optional or positional). The string value of this exception is the message, augmented with information about the argument that caused it. @@ -118,8 +117,7 @@ class ArgumentError(Exception): # undocumented class _AttributeHolder: - """ - Abstract base class that provides __repr__. + """Abstract base class that provides __repr__. The __repr__ method returns a string in the format:: ClassName(attr=name, attr=name, ...) @@ -171,8 +169,7 @@ class _ActionsContainer: version: str = ..., **kwargs: Any, ) -> Action: - """ - add_argument(dest, ..., name=value, ...) + """add_argument(dest, ..., name=value, ...) add_argument(option_string, option_string, ..., name=value, ...) """ @@ -201,8 +198,7 @@ class _FormatterClass(Protocol): def __call__(self, *, prog: str) -> HelpFormatter: ... class ArgumentParser(_AttributeHolder, _ActionsContainer): - """ - Object for parsing command line strings into Python objects. + """Object for parsing command line strings into Python objects. Keyword Arguments: - prog -- The name of the program (default: @@ -331,8 +327,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): 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: - """ - error(message: string) + """error(message: string) Prints a usage message incorporating the message to stderr and exits. @@ -378,8 +373,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): def _print_message(self, message: str, file: SupportsWrite[str] | None = None) -> None: ... class HelpFormatter: - """ - Formatter for generating usage messages and argument help strings. + """Formatter for generating usage messages and argument help strings. Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail. @@ -446,32 +440,28 @@ class HelpFormatter: def _get_default_metavar_for_positional(self, action: Action) -> str: ... class RawDescriptionHelpFormatter(HelpFormatter): - """ - Help message formatter which retains any formatting in descriptions. + """Help message formatter which retains any formatting in descriptions. Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail. """ class RawTextHelpFormatter(RawDescriptionHelpFormatter): - """ - Help message formatter which retains formatting of all help text. + """Help message formatter which retains formatting of all help text. Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail. """ class ArgumentDefaultsHelpFormatter(HelpFormatter): - """ - Help message formatter which adds default values to argument help. + """Help message formatter which adds default values to argument help. Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail. """ class MetavarTypeHelpFormatter(HelpFormatter): - """ - Help message formatter which uses the argument 'type' as the default + """Help message formatter which uses the argument 'type' as the default metavar value (instead of the argument 'dest') Only the name of this class is considered a public API. All the methods @@ -479,8 +469,7 @@ class MetavarTypeHelpFormatter(HelpFormatter): """ class Action(_AttributeHolder): - """ - Information about how to convert command line strings to Python objects. + """Information about how to convert command line strings to Python objects. Action objects are used by an ArgumentParser to represent the information needed to parse a single argument from one or more strings from the @@ -665,8 +654,7 @@ else: ) -> None: ... class Namespace(_AttributeHolder): - """ - Simple object for storing attributes. + """Simple object for storing attributes. Implements equality by attribute names and values, and provides a simple string representation. @@ -682,8 +670,7 @@ class Namespace(_AttributeHolder): if sys.version_info >= (3, 14): @deprecated("Deprecated in Python 3.14; Simply open files after parsing arguments") class FileType: - """ - Deprecated factory for creating file object types + """Deprecated factory for creating file object types Instances of FileType are typically passed as type= arguments to the ArgumentParser add_argument() method. @@ -711,8 +698,7 @@ if sys.version_info >= (3, 14): else: class FileType: - """ - Factory for creating file object types + """Factory for creating file object types Instances of FileType are typically passed as type= arguments to the ArgumentParser add_argument() method. @@ -1044,9 +1030,7 @@ class _SubParsersAction(Action, Generic[_ArgumentParserT]): # undocumented class ArgumentTypeError(Exception): - """ - An error from trying to convert a command line string to a type. - """ + """An error from trying to convert a command line string to a type.""" # undocumented def _get_action_name(argument: Action | None) -> str | None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/array.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/array.pyi index cf730a856e..c0f7bfd833 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/array.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/array.pyi @@ -22,8 +22,7 @@ _T = TypeVar("_T", int, float, str) typecodes: str class array(MutableSequence[_T]): - """ - array(typecode [, initializer]) -> array + """array(typecode [, initializer]) -> array Return a new array whose items are restricted by typecode, and initialized from the optional initializer value, which must be a list, @@ -83,15 +82,11 @@ class array(MutableSequence[_T]): @property def typecode(self) -> _TypeCode: - """ - the typecode character used to create the array - """ + """the typecode character used to create the array""" @property def itemsize(self) -> int: - """ - the size, in bytes, of one array item - """ + """the size, in bytes, of one array item""" @overload def __new__( @@ -110,54 +105,39 @@ class array(MutableSequence[_T]): @overload def __new__(cls, typecode: str, initializer: bytes | bytearray = ..., /) -> Self: ... def append(self, v: _T, /) -> None: - """ - Append new value v to the end of the array. - """ + """Append new value v to the end of the array.""" def buffer_info(self) -> tuple[int, int]: - """ - Return a tuple (address, length) giving the current memory address and the length in items of the buffer used to hold array's contents. + """Return a tuple (address, length) giving the current memory address and the length in items of the buffer used to hold array's contents. The length should be multiplied by the itemsize attribute to calculate the buffer length in bytes. """ def byteswap(self) -> None: - """ - Byteswap all items of the array. + """Byteswap all items of the array. If the items in the array are not 1, 2, 4, or 8 bytes in size, RuntimeError is raised. """ def count(self, v: _T, /) -> int: - """ - Return number of occurrences of v in the array. - """ + """Return number of occurrences of v in the array.""" def extend(self, bb: Iterable[_T], /) -> None: - """ - Append items to the end of the array. - """ + """Append items to the end of the array.""" def frombytes(self, buffer: ReadableBuffer, /) -> None: - """ - Appends items from the string, interpreting it as an array of machine values, as if it had been read from a file using the fromfile() method. - """ + """Appends items from the string, interpreting it as an array of machine values, as if it had been read from a file using the fromfile() method.""" def fromfile(self, f: SupportsRead[bytes], n: int, /) -> None: - """ - Read n objects from the file object f and append them to the end of the array. - """ + """Read n objects from the file object f and append them to the end of the array.""" def fromlist(self, list: list[_T], /) -> None: - """ - Append items to array from list. - """ + """Append items to array from list.""" def fromunicode(self, ustr: str, /) -> None: - """ - Extends this array with data from the unicode string ustr. + """Extends this array with data from the unicode string ustr. The array must be a unicode type array; otherwise a ValueError is raised. Use array.frombytes(ustr.encode(...)) to append Unicode data to an array of @@ -165,54 +145,40 @@ class array(MutableSequence[_T]): """ if sys.version_info >= (3, 10): def index(self, v: _T, start: int = 0, stop: int = sys.maxsize, /) -> int: - """ - Return index of first occurrence of v in the array. + """Return index of first occurrence of v in the array. Raise ValueError if the value is not present. """ else: def index(self, v: _T, /) -> int: # type: ignore[override] - """ - Return index of first occurrence of v in the array. + """Return index of first occurrence of v in the array. Raise ValueError if the value is not present. """ def insert(self, i: int, v: _T, /) -> None: - """ - Insert a new item v into the array before position i. - """ + """Insert a new item v into the array before position i.""" def pop(self, i: int = -1, /) -> _T: - """ - Return the i-th element and delete it from the array. + """Return the i-th element and delete it from the array. i defaults to -1. """ def remove(self, v: _T, /) -> None: - """ - Remove the first occurrence of v in the array. - """ + """Remove the first occurrence of v in the array.""" def tobytes(self) -> bytes: - """ - Convert the array to an array of machine values and return the bytes representation. - """ + """Convert the array to an array of machine values and return the bytes representation.""" def tofile(self, f: SupportsWrite[bytes], /) -> None: - """ - Write all items (as machine values) to the file object f. - """ + """Write all items (as machine values) to the file object f.""" def tolist(self) -> list[_T]: - """ - Convert array to an ordinary list with the same items. - """ + """Convert array to an ordinary list with the same items.""" def tounicode(self) -> str: - """ - Extends this array with data from the unicode string ustr. + """Extends this array with data from the unicode string ustr. Convert the array to a unicode string. The array must be a unicode type array; otherwise a ValueError is raised. Use array.tobytes().decode() to obtain a @@ -220,84 +186,56 @@ class array(MutableSequence[_T]): """ __hash__: ClassVar[None] # type: ignore[assignment] def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" @overload def __getitem__(self, key: SupportsIndex, /) -> _T: - """ - Return self[key]. - """ + """Return self[key].""" @overload def __getitem__(self, key: slice, /) -> array[_T]: ... @overload # type: ignore[override] def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: - """ - Set self[key] to value. - """ + """Set self[key] to value.""" @overload def __setitem__(self, key: slice, value: array[_T], /) -> None: ... def __delitem__(self, key: SupportsIndex | slice, /) -> None: - """ - Delete self[key]. - """ + """Delete self[key].""" def __add__(self, value: array[_T], /) -> array[_T]: - """ - Return self+value. - """ + """Return self+value.""" def __eq__(self, value: object, /) -> bool: ... def __ge__(self, value: array[_T], /) -> bool: ... def __gt__(self, value: array[_T], /) -> bool: ... def __iadd__(self, value: array[_T], /) -> Self: # type: ignore[override] - """ - Implement self+=value. - """ + """Implement self+=value.""" def __imul__(self, value: int, /) -> Self: - """ - Implement self*=value. - """ + """Implement self*=value.""" def __le__(self, value: array[_T], /) -> bool: ... def __lt__(self, value: array[_T], /) -> bool: ... def __mul__(self, value: int, /) -> array[_T]: - """ - Return self*value. - """ + """Return self*value.""" def __rmul__(self, value: int, /) -> array[_T]: - """ - Return value*self. - """ + """Return value*self.""" def __copy__(self) -> array[_T]: - """ - Return a copy of the array. - """ + """Return a copy of the array.""" def __deepcopy__(self, unused: Any, /) -> array[_T]: - """ - Return a copy of the array. - """ + """Return a copy of the array.""" def __buffer__(self, flags: int, /) -> memoryview: - """ - Return a buffer object that exposes the underlying memory of the object. - """ + """Return a buffer object that exposes the underlying memory of the object.""" def __release_buffer__(self, buffer: memoryview, /) -> None: - """ - Release the buffer object that exposes the underlying memory of the object. - """ + """Release the buffer object that exposes the underlying memory of the object.""" if sys.version_info >= (3, 12): def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" ArrayType = array diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/ast.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/ast.pyi index d2baaba214..392bc9d4d7 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/ast.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/ast.pyi @@ -1,4 +1,5 @@ """ + The `ast` module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python release; this module helps to find out programmatically what @@ -62,22 +63,17 @@ class AST: if sys.version_info >= (3, 14): def __replace__(self) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class mod(AST): - """ - mod = Module(stmt* body, type_ignore* type_ignores) + """mod = Module(stmt* body, type_ignore* type_ignores) | Interactive(stmt* body) | Expression(expr body) | FunctionType(expr* argtypes, expr returns) """ class Module(mod): - """ - Module(stmt* body, type_ignore* type_ignores) - """ + """Module(stmt* body, type_ignore* type_ignores)""" if sys.version_info >= (3, 10): __match_args__ = ("body", "type_ignores") @@ -90,14 +86,10 @@ class Module(mod): if sys.version_info >= (3, 14): def __replace__(self, *, body: list[stmt] = ..., type_ignores: list[TypeIgnore] = ...) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Interactive(mod): - """ - Interactive(stmt* body) - """ + """Interactive(stmt* body)""" if sys.version_info >= (3, 10): __match_args__ = ("body",) @@ -109,14 +101,10 @@ class Interactive(mod): if sys.version_info >= (3, 14): def __replace__(self, *, body: list[stmt] = ...) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Expression(mod): - """ - Expression(expr body) - """ + """Expression(expr body)""" if sys.version_info >= (3, 10): __match_args__ = ("body",) @@ -125,14 +113,10 @@ class Expression(mod): if sys.version_info >= (3, 14): def __replace__(self, *, body: expr = ...) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class FunctionType(mod): - """ - FunctionType(expr* argtypes, expr returns) - """ + """FunctionType(expr* argtypes, expr returns)""" if sys.version_info >= (3, 10): __match_args__ = ("argtypes", "returns") @@ -148,13 +132,10 @@ class FunctionType(mod): if sys.version_info >= (3, 14): def __replace__(self, *, argtypes: list[expr] = ..., returns: expr = ...) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class stmt(AST): - """ - stmt = FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment, type_param* type_params) + """stmt = FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment, type_param* type_params) | AsyncFunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment, type_param* type_params) | ClassDef(identifier name, expr* bases, keyword* keywords, stmt* body, expr* decorator_list, type_param* type_params) | Return(expr? value) @@ -192,14 +173,10 @@ class stmt(AST): if sys.version_info >= (3, 14): def __replace__(self, **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class FunctionDef(stmt): - """ - FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment, type_param* type_params) - """ + """FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment, type_param* type_params)""" if sys.version_info >= (3, 12): __match_args__ = ("name", "args", "body", "decorator_list", "returns", "type_comment", "type_params") @@ -276,14 +253,10 @@ class FunctionDef(stmt): type_params: list[type_param] = ..., **kwargs: Unpack[_Attributes], ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class AsyncFunctionDef(stmt): - """ - AsyncFunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment, type_param* type_params) - """ + """AsyncFunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns, string? type_comment, type_param* type_params)""" if sys.version_info >= (3, 12): __match_args__ = ("name", "args", "body", "decorator_list", "returns", "type_comment", "type_params") @@ -360,14 +333,10 @@ class AsyncFunctionDef(stmt): type_params: list[type_param] = ..., **kwargs: Unpack[_Attributes], ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class ClassDef(stmt): - """ - ClassDef(identifier name, expr* bases, keyword* keywords, stmt* body, expr* decorator_list, type_param* type_params) - """ + """ClassDef(identifier name, expr* bases, keyword* keywords, stmt* body, expr* decorator_list, type_param* type_params)""" if sys.version_info >= (3, 12): __match_args__ = ("name", "bases", "keywords", "body", "decorator_list", "type_params") @@ -425,14 +394,10 @@ class ClassDef(stmt): type_params: list[type_param] = ..., **kwargs: Unpack[_Attributes], ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Return(stmt): - """ - Return(expr? value) - """ + """Return(expr? value)""" if sys.version_info >= (3, 10): __match_args__ = ("value",) @@ -441,14 +406,10 @@ class Return(stmt): if sys.version_info >= (3, 14): def __replace__(self, *, value: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Delete(stmt): - """ - Delete(expr* targets) - """ + """Delete(expr* targets)""" if sys.version_info >= (3, 10): __match_args__ = ("targets",) @@ -460,14 +421,10 @@ class Delete(stmt): if sys.version_info >= (3, 14): def __replace__(self, *, targets: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Assign(stmt): - """ - Assign(expr* targets, expr value, string? type_comment) - """ + """Assign(expr* targets, expr value, string? type_comment)""" if sys.version_info >= (3, 10): __match_args__ = ("targets", "value", "type_comment") @@ -492,15 +449,11 @@ class Assign(stmt): def __replace__( self, *, targets: list[expr] = ..., value: expr = ..., type_comment: str | None = ..., **kwargs: Unpack[_Attributes] ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" if sys.version_info >= (3, 12): class TypeAlias(stmt): - """ - TypeAlias(expr name, type_param* type_params, expr value) - """ + """TypeAlias(expr name, type_param* type_params, expr value)""" __match_args__ = ("name", "type_params", "value") name: Name @@ -529,14 +482,10 @@ if sys.version_info >= (3, 12): value: expr = ..., **kwargs: Unpack[_Attributes[int]], ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class AugAssign(stmt): - """ - AugAssign(expr target, operator op, expr value) - """ + """AugAssign(expr target, operator op, expr value)""" if sys.version_info >= (3, 10): __match_args__ = ("target", "op", "value") @@ -556,14 +505,10 @@ class AugAssign(stmt): value: expr = ..., **kwargs: Unpack[_Attributes], ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class AnnAssign(stmt): - """ - AnnAssign(expr target, expr annotation, expr? value, int simple) - """ + """AnnAssign(expr target, expr annotation, expr? value, int simple)""" if sys.version_info >= (3, 10): __match_args__ = ("target", "annotation", "value", "simple") @@ -601,14 +546,10 @@ class AnnAssign(stmt): simple: int = ..., **kwargs: Unpack[_Attributes], ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class For(stmt): - """ - For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment) - """ + """For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)""" if sys.version_info >= (3, 10): __match_args__ = ("target", "iter", "body", "orelse", "type_comment") @@ -649,14 +590,10 @@ class For(stmt): type_comment: str | None = ..., **kwargs: Unpack[_Attributes], ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class AsyncFor(stmt): - """ - AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment) - """ + """AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)""" if sys.version_info >= (3, 10): __match_args__ = ("target", "iter", "body", "orelse", "type_comment") @@ -697,14 +634,10 @@ class AsyncFor(stmt): type_comment: str | None = ..., **kwargs: Unpack[_Attributes], ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class While(stmt): - """ - While(expr test, stmt* body, stmt* orelse) - """ + """While(expr test, stmt* body, stmt* orelse)""" if sys.version_info >= (3, 10): __match_args__ = ("test", "body", "orelse") @@ -722,14 +655,10 @@ class While(stmt): def __replace__( self, *, test: expr = ..., body: list[stmt] = ..., orelse: list[stmt] = ..., **kwargs: Unpack[_Attributes] ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class If(stmt): - """ - If(expr test, stmt* body, stmt* orelse) - """ + """If(expr test, stmt* body, stmt* orelse)""" if sys.version_info >= (3, 10): __match_args__ = ("test", "body", "orelse") @@ -747,14 +676,10 @@ class If(stmt): def __replace__( self, *, test: expr = ..., body: list[stmt] = ..., orelse: list[stmt] = ..., **kwargs: Unpack[_Attributes] ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class With(stmt): - """ - With(withitem* items, stmt* body, string? type_comment) - """ + """With(withitem* items, stmt* body, string? type_comment)""" if sys.version_info >= (3, 10): __match_args__ = ("items", "body", "type_comment") @@ -783,14 +708,10 @@ class With(stmt): type_comment: str | None = ..., **kwargs: Unpack[_Attributes], ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class AsyncWith(stmt): - """ - AsyncWith(withitem* items, stmt* body, string? type_comment) - """ + """AsyncWith(withitem* items, stmt* body, string? type_comment)""" if sys.version_info >= (3, 10): __match_args__ = ("items", "body", "type_comment") @@ -819,14 +740,10 @@ class AsyncWith(stmt): type_comment: str | None = ..., **kwargs: Unpack[_Attributes], ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Raise(stmt): - """ - Raise(expr? exc, expr? cause) - """ + """Raise(expr? exc, expr? cause)""" if sys.version_info >= (3, 10): __match_args__ = ("exc", "cause") @@ -836,14 +753,10 @@ class Raise(stmt): if sys.version_info >= (3, 14): def __replace__(self, *, exc: expr | None = ..., cause: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Try(stmt): - """ - Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody) - """ + """Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)""" if sys.version_info >= (3, 10): __match_args__ = ("body", "handlers", "orelse", "finalbody") @@ -880,15 +793,11 @@ class Try(stmt): finalbody: list[stmt] = ..., **kwargs: Unpack[_Attributes], ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" if sys.version_info >= (3, 11): class TryStar(stmt): - """ - TryStar(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody) - """ + """TryStar(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)""" __match_args__ = ("body", "handlers", "orelse", "finalbody") body: list[stmt] @@ -924,14 +833,10 @@ if sys.version_info >= (3, 11): finalbody: list[stmt] = ..., **kwargs: Unpack[_Attributes], ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Assert(stmt): - """ - Assert(expr test, expr? msg) - """ + """Assert(expr test, expr? msg)""" if sys.version_info >= (3, 10): __match_args__ = ("test", "msg") @@ -941,14 +846,10 @@ class Assert(stmt): if sys.version_info >= (3, 14): def __replace__(self, *, test: expr = ..., msg: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Import(stmt): - """ - Import(alias* names) - """ + """Import(alias* names)""" if sys.version_info >= (3, 10): __match_args__ = ("names",) @@ -960,14 +861,10 @@ class Import(stmt): if sys.version_info >= (3, 14): def __replace__(self, *, names: list[alias] = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class ImportFrom(stmt): - """ - ImportFrom(identifier? module, alias* names, int? level) - """ + """ImportFrom(identifier? module, alias* names, int? level)""" if sys.version_info >= (3, 10): __match_args__ = ("module", "names", "level") @@ -993,14 +890,10 @@ class ImportFrom(stmt): def __replace__( self, *, module: str | None = ..., names: list[alias] = ..., level: int = ..., **kwargs: Unpack[_Attributes] ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Global(stmt): - """ - Global(identifier* names) - """ + """Global(identifier* names)""" if sys.version_info >= (3, 10): __match_args__ = ("names",) @@ -1012,14 +905,10 @@ class Global(stmt): if sys.version_info >= (3, 14): def __replace__(self, *, names: list[str] = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Nonlocal(stmt): - """ - Nonlocal(identifier* names) - """ + """Nonlocal(identifier* names)""" if sys.version_info >= (3, 10): __match_args__ = ("names",) @@ -1031,14 +920,10 @@ class Nonlocal(stmt): if sys.version_info >= (3, 14): def __replace__(self, *, names: list[str] = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Expr(stmt): - """ - Expr(expr value) - """ + """Expr(expr value)""" if sys.version_info >= (3, 10): __match_args__ = ("value",) @@ -1047,28 +932,19 @@ class Expr(stmt): if sys.version_info >= (3, 14): def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Pass(stmt): - """ - Pass - """ + """Pass""" class Break(stmt): - """ - Break - """ + """Break""" class Continue(stmt): - """ - Continue - """ + """Continue""" class expr(AST): - """ - expr = BoolOp(boolop op, expr* values) + """expr = BoolOp(boolop op, expr* values) | NamedExpr(expr target, expr value) | BinOp(expr left, operator op, expr right) | UnaryOp(unaryop op, expr operand) @@ -1107,14 +983,10 @@ class expr(AST): if sys.version_info >= (3, 14): def __replace__(self, **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class BoolOp(expr): - """ - BoolOp(boolop op, expr* values) - """ + """BoolOp(boolop op, expr* values)""" if sys.version_info >= (3, 10): __match_args__ = ("op", "values") @@ -1127,14 +999,10 @@ class BoolOp(expr): if sys.version_info >= (3, 14): def __replace__(self, *, op: boolop = ..., values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class NamedExpr(expr): - """ - NamedExpr(expr target, expr value) - """ + """NamedExpr(expr target, expr value)""" if sys.version_info >= (3, 10): __match_args__ = ("target", "value") @@ -1144,14 +1012,10 @@ class NamedExpr(expr): if sys.version_info >= (3, 14): def __replace__(self, *, target: Name = ..., value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class BinOp(expr): - """ - BinOp(expr left, operator op, expr right) - """ + """BinOp(expr left, operator op, expr right)""" if sys.version_info >= (3, 10): __match_args__ = ("left", "op", "right") @@ -1162,14 +1026,10 @@ class BinOp(expr): if sys.version_info >= (3, 14): def __replace__(self, *, left: expr = ..., op: operator = ..., right: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class UnaryOp(expr): - """ - UnaryOp(unaryop op, expr operand) - """ + """UnaryOp(unaryop op, expr operand)""" if sys.version_info >= (3, 10): __match_args__ = ("op", "operand") @@ -1179,14 +1039,10 @@ class UnaryOp(expr): if sys.version_info >= (3, 14): def __replace__(self, *, op: unaryop = ..., operand: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Lambda(expr): - """ - Lambda(arguments args, expr body) - """ + """Lambda(arguments args, expr body)""" if sys.version_info >= (3, 10): __match_args__ = ("args", "body") @@ -1196,14 +1052,10 @@ class Lambda(expr): if sys.version_info >= (3, 14): def __replace__(self, *, args: arguments = ..., body: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class IfExp(expr): - """ - IfExp(expr test, expr body, expr orelse) - """ + """IfExp(expr test, expr body, expr orelse)""" if sys.version_info >= (3, 10): __match_args__ = ("test", "body", "orelse") @@ -1214,14 +1066,10 @@ class IfExp(expr): if sys.version_info >= (3, 14): def __replace__(self, *, test: expr = ..., body: expr = ..., orelse: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Dict(expr): - """ - Dict(expr?* keys, expr* values) - """ + """Dict(expr?* keys, expr* values)""" if sys.version_info >= (3, 10): __match_args__ = ("keys", "values") @@ -1234,14 +1082,10 @@ class Dict(expr): if sys.version_info >= (3, 14): def __replace__(self, *, keys: list[expr | None] = ..., values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Set(expr): - """ - Set(expr* elts) - """ + """Set(expr* elts)""" if sys.version_info >= (3, 10): __match_args__ = ("elts",) @@ -1253,14 +1097,10 @@ class Set(expr): if sys.version_info >= (3, 14): def __replace__(self, *, elts: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class ListComp(expr): - """ - ListComp(expr elt, comprehension* generators) - """ + """ListComp(expr elt, comprehension* generators)""" if sys.version_info >= (3, 10): __match_args__ = ("elt", "generators") @@ -1273,14 +1113,10 @@ class ListComp(expr): if sys.version_info >= (3, 14): def __replace__(self, *, elt: expr = ..., generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class SetComp(expr): - """ - SetComp(expr elt, comprehension* generators) - """ + """SetComp(expr elt, comprehension* generators)""" if sys.version_info >= (3, 10): __match_args__ = ("elt", "generators") @@ -1293,14 +1129,10 @@ class SetComp(expr): if sys.version_info >= (3, 14): def __replace__(self, *, elt: expr = ..., generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class DictComp(expr): - """ - DictComp(expr key, expr value, comprehension* generators) - """ + """DictComp(expr key, expr value, comprehension* generators)""" if sys.version_info >= (3, 10): __match_args__ = ("key", "value", "generators") @@ -1318,14 +1150,10 @@ class DictComp(expr): def __replace__( self, *, key: expr = ..., value: expr = ..., generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes] ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class GeneratorExp(expr): - """ - GeneratorExp(expr elt, comprehension* generators) - """ + """GeneratorExp(expr elt, comprehension* generators)""" if sys.version_info >= (3, 10): __match_args__ = ("elt", "generators") @@ -1338,14 +1166,10 @@ class GeneratorExp(expr): if sys.version_info >= (3, 14): def __replace__(self, *, elt: expr = ..., generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Await(expr): - """ - Await(expr value) - """ + """Await(expr value)""" if sys.version_info >= (3, 10): __match_args__ = ("value",) @@ -1354,14 +1178,10 @@ class Await(expr): if sys.version_info >= (3, 14): def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Yield(expr): - """ - Yield(expr? value) - """ + """Yield(expr? value)""" if sys.version_info >= (3, 10): __match_args__ = ("value",) @@ -1370,14 +1190,10 @@ class Yield(expr): if sys.version_info >= (3, 14): def __replace__(self, *, value: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class YieldFrom(expr): - """ - YieldFrom(expr value) - """ + """YieldFrom(expr value)""" if sys.version_info >= (3, 10): __match_args__ = ("value",) @@ -1386,14 +1202,10 @@ class YieldFrom(expr): if sys.version_info >= (3, 14): def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Compare(expr): - """ - Compare(expr left, cmpop* ops, expr* comparators) - """ + """Compare(expr left, cmpop* ops, expr* comparators)""" if sys.version_info >= (3, 10): __match_args__ = ("left", "ops", "comparators") @@ -1411,14 +1223,10 @@ class Compare(expr): def __replace__( self, *, left: expr = ..., ops: list[cmpop] = ..., comparators: list[expr] = ..., **kwargs: Unpack[_Attributes] ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Call(expr): - """ - Call(expr func, expr* args, keyword* keywords) - """ + """Call(expr func, expr* args, keyword* keywords)""" if sys.version_info >= (3, 10): __match_args__ = ("func", "args", "keywords") @@ -1436,14 +1244,10 @@ class Call(expr): def __replace__( self, *, func: expr = ..., args: list[expr] = ..., keywords: list[keyword] = ..., **kwargs: Unpack[_Attributes] ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class FormattedValue(expr): - """ - FormattedValue(expr value, int conversion, expr? format_spec) - """ + """FormattedValue(expr value, int conversion, expr? format_spec)""" if sys.version_info >= (3, 10): __match_args__ = ("value", "conversion", "format_spec") @@ -1456,14 +1260,10 @@ class FormattedValue(expr): def __replace__( self, *, value: expr = ..., conversion: int = ..., format_spec: expr | None = ..., **kwargs: Unpack[_Attributes] ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class JoinedStr(expr): - """ - JoinedStr(expr* values) - """ + """JoinedStr(expr* values)""" if sys.version_info >= (3, 10): __match_args__ = ("values",) @@ -1475,28 +1275,20 @@ class JoinedStr(expr): if sys.version_info >= (3, 14): def __replace__(self, *, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" if sys.version_info >= (3, 14): class TemplateStr(expr): - """ - TemplateStr(expr* values) - """ + """TemplateStr(expr* values)""" __match_args__ = ("values",) values: list[expr] def __init__(self, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ... def __replace__(self, *, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Interpolation(expr): - """ - Interpolation(expr value, constant str, int conversion, expr? format_spec) - """ + """Interpolation(expr value, constant str, int conversion, expr? format_spec)""" __match_args__ = ("value", "str", "conversion", "format_spec") value: expr @@ -1520,9 +1312,7 @@ if sys.version_info >= (3, 14): format_spec: expr | None = ..., **kwargs: Unpack[_Attributes], ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" if sys.version_info >= (3, 10): from types import EllipsisType @@ -1533,9 +1323,7 @@ else: _ConstantValue: typing_extensions.TypeAlias = str | bytes | bool | int | float | complex | None | ellipsis # noqa: F821 class Constant(expr): - """ - Constant(constant value, string? kind) - """ + """Constant(constant value, string? kind)""" if sys.version_info >= (3, 10): __match_args__ = ("value", "kind") @@ -1558,14 +1346,10 @@ class Constant(expr): if sys.version_info >= (3, 14): def __replace__(self, *, value: _ConstantValue = ..., kind: str | None = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Attribute(expr): - """ - Attribute(expr value, identifier attr, expr_context ctx) - """ + """Attribute(expr value, identifier attr, expr_context ctx)""" if sys.version_info >= (3, 10): __match_args__ = ("value", "attr", "ctx") @@ -1578,14 +1362,10 @@ class Attribute(expr): def __replace__( self, *, value: expr = ..., attr: str = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes] ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Subscript(expr): - """ - Subscript(expr value, expr slice, expr_context ctx) - """ + """Subscript(expr value, expr slice, expr_context ctx)""" if sys.version_info >= (3, 10): __match_args__ = ("value", "slice", "ctx") @@ -1598,14 +1378,10 @@ class Subscript(expr): def __replace__( self, *, value: expr = ..., slice: expr = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes] ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Starred(expr): - """ - Starred(expr value, expr_context ctx) - """ + """Starred(expr value, expr_context ctx)""" if sys.version_info >= (3, 10): __match_args__ = ("value", "ctx") @@ -1615,14 +1391,10 @@ class Starred(expr): if sys.version_info >= (3, 14): def __replace__(self, *, value: expr = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Name(expr): - """ - Name(identifier id, expr_context ctx) - """ + """Name(identifier id, expr_context ctx)""" if sys.version_info >= (3, 10): __match_args__ = ("id", "ctx") @@ -1632,14 +1404,10 @@ class Name(expr): if sys.version_info >= (3, 14): def __replace__(self, *, id: str = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class List(expr): - """ - List(expr* elts, expr_context ctx) - """ + """List(expr* elts, expr_context ctx)""" if sys.version_info >= (3, 10): __match_args__ = ("elts", "ctx") @@ -1652,14 +1420,10 @@ class List(expr): if sys.version_info >= (3, 14): def __replace__(self, *, elts: list[expr] = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Tuple(expr): - """ - Tuple(expr* elts, expr_context ctx) - """ + """Tuple(expr* elts, expr_context ctx)""" if sys.version_info >= (3, 10): __match_args__ = ("elts", "ctx") @@ -1673,20 +1437,14 @@ class Tuple(expr): if sys.version_info >= (3, 14): def __replace__(self, *, elts: list[expr] = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" @deprecated("Deprecated since Python 3.9.") class slice(AST): - """ - Deprecated AST node class. - """ + """Deprecated AST node class.""" class Slice(expr): - """ - Slice(expr? lower, expr? upper, expr? step) - """ + """Slice(expr? lower, expr? upper, expr? step)""" if sys.version_info >= (3, 10): __match_args__ = ("lower", "upper", "step") @@ -1701,239 +1459,149 @@ class Slice(expr): def __replace__( self, *, lower: expr | None = ..., upper: expr | None = ..., step: expr | None = ..., **kwargs: Unpack[_Attributes] ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" @deprecated("Deprecated since Python 3.9. Use ast.Tuple instead.") class ExtSlice(slice): - """ - Deprecated AST node class. Use ast.Tuple instead. - """ + """Deprecated AST node class. Use ast.Tuple instead.""" def __new__(cls, dims: Iterable[slice] = (), **kwargs: Unpack[_Attributes]) -> Tuple: ... # type: ignore[misc] @deprecated("Deprecated since Python 3.9. Use the index value directly instead.") class Index(slice): - """ - Deprecated AST node class. Use the index value directly instead. - """ + """Deprecated AST node class. Use the index value directly instead.""" def __new__(cls, value: expr, **kwargs: Unpack[_Attributes]) -> expr: ... # type: ignore[misc] class expr_context(AST): - """ - expr_context = Load | Store | Del - """ + """expr_context = Load | Store | Del""" @deprecated("Deprecated since Python 3.9. Unused in Python 3.") class AugLoad(expr_context): - """ - Deprecated AST node class. Unused in Python 3. - """ + """Deprecated AST node class. Unused in Python 3.""" @deprecated("Deprecated since Python 3.9. Unused in Python 3.") class AugStore(expr_context): - """ - Deprecated AST node class. Unused in Python 3. - """ + """Deprecated AST node class. Unused in Python 3.""" @deprecated("Deprecated since Python 3.9. Unused in Python 3.") class Param(expr_context): - """ - Deprecated AST node class. Unused in Python 3. - """ + """Deprecated AST node class. Unused in Python 3.""" @deprecated("Deprecated since Python 3.9. Unused in Python 3.") class Suite(mod): - """ - Deprecated AST node class. Unused in Python 3. - """ + """Deprecated AST node class. Unused in Python 3.""" class Load(expr_context): - """ - Load - """ + """Load""" class Store(expr_context): - """ - Store - """ + """Store""" class Del(expr_context): - """ - Del - """ + """Del""" class boolop(AST): - """ - boolop = And | Or - """ + """boolop = And | Or""" class And(boolop): - """ - And - """ + """And""" class Or(boolop): - """ - Or - """ + """Or""" class operator(AST): - """ - operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift | RShift | BitOr | BitXor | BitAnd | FloorDiv - """ + """operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift | RShift | BitOr | BitXor | BitAnd | FloorDiv""" class Add(operator): - """ - Add - """ + """Add""" class Sub(operator): - """ - Sub - """ + """Sub""" class Mult(operator): - """ - Mult - """ + """Mult""" class MatMult(operator): - """ - MatMult - """ + """MatMult""" class Div(operator): - """ - Div - """ + """Div""" class Mod(operator): - """ - Mod - """ + """Mod""" class Pow(operator): - """ - Pow - """ + """Pow""" class LShift(operator): - """ - LShift - """ + """LShift""" class RShift(operator): - """ - RShift - """ + """RShift""" class BitOr(operator): - """ - BitOr - """ + """BitOr""" class BitXor(operator): - """ - BitXor - """ + """BitXor""" class BitAnd(operator): - """ - BitAnd - """ + """BitAnd""" class FloorDiv(operator): - """ - FloorDiv - """ + """FloorDiv""" class unaryop(AST): - """ - unaryop = Invert | Not | UAdd | USub - """ + """unaryop = Invert | Not | UAdd | USub""" class Invert(unaryop): - """ - Invert - """ + """Invert""" class Not(unaryop): - """ - Not - """ + """Not""" class UAdd(unaryop): - """ - UAdd - """ + """UAdd""" class USub(unaryop): - """ - USub - """ + """USub""" class cmpop(AST): - """ - cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn - """ + """cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn""" class Eq(cmpop): - """ - Eq - """ + """Eq""" class NotEq(cmpop): - """ - NotEq - """ + """NotEq""" class Lt(cmpop): - """ - Lt - """ + """Lt""" class LtE(cmpop): - """ - LtE - """ + """LtE""" class Gt(cmpop): - """ - Gt - """ + """Gt""" class GtE(cmpop): - """ - GtE - """ + """GtE""" class Is(cmpop): - """ - Is - """ + """Is""" class IsNot(cmpop): - """ - IsNot - """ + """IsNot""" class In(cmpop): - """ - In - """ + """In""" class NotIn(cmpop): - """ - NotIn - """ + """NotIn""" class comprehension(AST): - """ - comprehension(expr target, expr iter, expr* ifs, int is_async) - """ + """comprehension(expr target, expr iter, expr* ifs, int is_async)""" if sys.version_info >= (3, 10): __match_args__ = ("target", "iter", "ifs", "is_async") @@ -1951,14 +1619,10 @@ class comprehension(AST): if sys.version_info >= (3, 14): def __replace__(self, *, target: expr = ..., iter: expr = ..., ifs: list[expr] = ..., is_async: int = ...) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class excepthandler(AST): - """ - excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body) - """ + """excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)""" lineno: int col_offset: int @@ -1970,14 +1634,10 @@ class excepthandler(AST): def __replace__( self, *, lineno: int = ..., col_offset: int = ..., end_lineno: int | None = ..., end_col_offset: int | None = ... ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class ExceptHandler(excepthandler): - """ - ExceptHandler(expr? type, identifier? name, stmt* body) - """ + """ExceptHandler(expr? type, identifier? name, stmt* body)""" if sys.version_info >= (3, 10): __match_args__ = ("type", "name", "body") @@ -2000,14 +1660,10 @@ class ExceptHandler(excepthandler): def __replace__( self, *, type: expr | None = ..., name: str | None = ..., body: list[stmt] = ..., **kwargs: Unpack[_Attributes] ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class arguments(AST): - """ - arguments(arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs, expr* kw_defaults, arg? kwarg, expr* defaults) - """ + """arguments(arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs, expr* kw_defaults, arg? kwarg, expr* defaults)""" if sys.version_info >= (3, 10): __match_args__ = ("posonlyargs", "args", "vararg", "kwonlyargs", "kw_defaults", "kwarg", "defaults") @@ -2078,14 +1734,10 @@ class arguments(AST): kwarg: arg | None = ..., defaults: list[expr] = ..., ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class arg(AST): - """ - arg(identifier arg, expr? annotation, string? type_comment) - """ + """arg(identifier arg, expr? annotation, string? type_comment)""" lineno: int col_offset: int @@ -2104,14 +1756,10 @@ class arg(AST): def __replace__( self, *, arg: str = ..., annotation: expr | None = ..., type_comment: str | None = ..., **kwargs: Unpack[_Attributes] ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class keyword(AST): - """ - keyword(identifier? arg, expr value) - """ + """keyword(identifier? arg, expr value)""" lineno: int col_offset: int @@ -2128,14 +1776,10 @@ class keyword(AST): if sys.version_info >= (3, 14): def __replace__(self, *, arg: str | None = ..., value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class alias(AST): - """ - alias(identifier name, identifier? asname) - """ + """alias(identifier name, identifier? asname)""" name: str asname: str | None @@ -2153,14 +1797,10 @@ class alias(AST): if sys.version_info >= (3, 14): def __replace__(self, *, name: str = ..., asname: str | None = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class withitem(AST): - """ - withitem(expr context_expr, expr? optional_vars) - """ + """withitem(expr context_expr, expr? optional_vars)""" if sys.version_info >= (3, 10): __match_args__ = ("context_expr", "optional_vars") @@ -2170,14 +1810,11 @@ class withitem(AST): if sys.version_info >= (3, 14): def __replace__(self, *, context_expr: expr = ..., optional_vars: expr | None = ...) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" if sys.version_info >= (3, 10): class pattern(AST): - """ - pattern = MatchValue(expr value) + """pattern = MatchValue(expr value) | MatchSingleton(constant value) | MatchSequence(pattern* patterns) | MatchMapping(expr* keys, pattern* patterns, identifier? rest) @@ -2197,14 +1834,10 @@ if sys.version_info >= (3, 10): def __replace__( self, *, lineno: int = ..., col_offset: int = ..., end_lineno: int = ..., end_col_offset: int = ... ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class match_case(AST): - """ - match_case(pattern pattern, expr? guard, stmt* body) - """ + """match_case(pattern pattern, expr? guard, stmt* body)""" __match_args__ = ("pattern", "guard", "body") pattern: ast.pattern @@ -2220,14 +1853,10 @@ if sys.version_info >= (3, 10): if sys.version_info >= (3, 14): def __replace__(self, *, pattern: ast.pattern = ..., guard: expr | None = ..., body: list[stmt] = ...) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class Match(stmt): - """ - Match(expr subject, match_case* cases) - """ + """Match(expr subject, match_case* cases)""" __match_args__ = ("subject", "cases") subject: expr @@ -2239,14 +1868,10 @@ if sys.version_info >= (3, 10): if sys.version_info >= (3, 14): def __replace__(self, *, subject: expr = ..., cases: list[match_case] = ..., **kwargs: Unpack[_Attributes]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class MatchValue(pattern): - """ - MatchValue(expr value) - """ + """MatchValue(expr value)""" __match_args__ = ("value",) value: expr @@ -2254,14 +1879,10 @@ if sys.version_info >= (3, 10): if sys.version_info >= (3, 14): def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class MatchSingleton(pattern): - """ - MatchSingleton(constant value) - """ + """MatchSingleton(constant value)""" __match_args__ = ("value",) value: bool | None @@ -2269,14 +1890,10 @@ if sys.version_info >= (3, 10): if sys.version_info >= (3, 14): def __replace__(self, *, value: bool | None = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class MatchSequence(pattern): - """ - MatchSequence(pattern* patterns) - """ + """MatchSequence(pattern* patterns)""" __match_args__ = ("patterns",) patterns: list[pattern] @@ -2287,14 +1904,10 @@ if sys.version_info >= (3, 10): if sys.version_info >= (3, 14): def __replace__(self, *, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class MatchMapping(pattern): - """ - MatchMapping(expr* keys, pattern* patterns, identifier? rest) - """ + """MatchMapping(expr* keys, pattern* patterns, identifier? rest)""" __match_args__ = ("keys", "patterns", "rest") keys: list[expr] @@ -2322,14 +1935,10 @@ if sys.version_info >= (3, 10): rest: str | None = ..., **kwargs: Unpack[_Attributes[int]], ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class MatchClass(pattern): - """ - MatchClass(expr cls, pattern* patterns, identifier* kwd_attrs, pattern* kwd_patterns) - """ + """MatchClass(expr cls, pattern* patterns, identifier* kwd_attrs, pattern* kwd_patterns)""" __match_args__ = ("cls", "patterns", "kwd_attrs", "kwd_patterns") cls: expr @@ -2365,14 +1974,10 @@ if sys.version_info >= (3, 10): kwd_patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]], ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class MatchStar(pattern): - """ - MatchStar(identifier? name) - """ + """MatchStar(identifier? name)""" __match_args__ = ("name",) name: str | None @@ -2380,14 +1985,10 @@ if sys.version_info >= (3, 10): if sys.version_info >= (3, 14): def __replace__(self, *, name: str | None = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class MatchAs(pattern): - """ - MatchAs(pattern? pattern, identifier? name) - """ + """MatchAs(pattern? pattern, identifier? name)""" __match_args__ = ("pattern", "name") pattern: ast.pattern | None @@ -2400,14 +2001,10 @@ if sys.version_info >= (3, 10): def __replace__( self, *, pattern: ast.pattern | None = ..., name: str | None = ..., **kwargs: Unpack[_Attributes[int]] ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class MatchOr(pattern): - """ - MatchOr(pattern* patterns) - """ + """MatchOr(pattern* patterns)""" __match_args__ = ("patterns",) patterns: list[pattern] @@ -2418,19 +2015,13 @@ if sys.version_info >= (3, 10): if sys.version_info >= (3, 14): def __replace__(self, *, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class type_ignore(AST): - """ - type_ignore = TypeIgnore(int lineno, string tag) - """ + """type_ignore = TypeIgnore(int lineno, string tag)""" class TypeIgnore(type_ignore): - """ - TypeIgnore(int lineno, string tag) - """ + """TypeIgnore(int lineno, string tag)""" if sys.version_info >= (3, 10): __match_args__ = ("lineno", "tag") @@ -2440,14 +2031,11 @@ class TypeIgnore(type_ignore): if sys.version_info >= (3, 14): def __replace__(self, *, lineno: int = ..., tag: str = ...) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" if sys.version_info >= (3, 12): class type_param(AST): - """ - type_param = TypeVar(identifier name, expr? bound, expr? default_value) + """type_param = TypeVar(identifier name, expr? bound, expr? default_value) | ParamSpec(identifier name, expr? default_value) | TypeVarTuple(identifier name, expr? default_value) """ @@ -2460,14 +2048,10 @@ if sys.version_info >= (3, 12): if sys.version_info >= (3, 14): def __replace__(self, **kwargs: Unpack[_Attributes[int]]) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class TypeVar(type_param): - """ - TypeVar(identifier name, expr? bound, expr? default_value) - """ + """TypeVar(identifier name, expr? bound, expr? default_value)""" if sys.version_info >= (3, 13): __match_args__ = ("name", "bound", "default_value") @@ -2492,14 +2076,10 @@ if sys.version_info >= (3, 12): default_value: expr | None = ..., **kwargs: Unpack[_Attributes[int]], ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class ParamSpec(type_param): - """ - ParamSpec(identifier name, expr? default_value) - """ + """ParamSpec(identifier name, expr? default_value)""" if sys.version_info >= (3, 13): __match_args__ = ("name", "default_value") @@ -2516,14 +2096,10 @@ if sys.version_info >= (3, 12): def __replace__( self, *, name: str = ..., default_value: expr | None = ..., **kwargs: Unpack[_Attributes[int]] ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class TypeVarTuple(type_param): - """ - TypeVarTuple(identifier name, expr? default_value) - """ + """TypeVarTuple(identifier name, expr? default_value)""" if sys.version_info >= (3, 13): __match_args__ = ("name", "default_value") @@ -2540,9 +2116,7 @@ if sys.version_info >= (3, 12): def __replace__( self, *, name: str = ..., default_value: expr | None = ..., **kwargs: Unpack[_Attributes[int]] ) -> Self: - """ - Return a copy of the AST node with new values for the specified fields. - """ + """Return a copy of the AST node with new values for the specified fields.""" class _ABC(type): def __init__(cls, *args: Unused) -> None: ... @@ -2550,41 +2124,31 @@ class _ABC(type): if sys.version_info < (3, 14): @deprecated("Replaced by ast.Constant; removed in Python 3.14") class Num(Constant, metaclass=_ABC): - """ - Deprecated AST node class. Use ast.Constant instead - """ + """Deprecated AST node class. Use ast.Constant instead""" def __new__(cls, n: complex, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor] @deprecated("Replaced by ast.Constant; removed in Python 3.14") class Str(Constant, metaclass=_ABC): - """ - Deprecated AST node class. Use ast.Constant instead - """ + """Deprecated AST node class. Use ast.Constant instead""" def __new__(cls, s: str, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor] @deprecated("Replaced by ast.Constant; removed in Python 3.14") class Bytes(Constant, metaclass=_ABC): - """ - Deprecated AST node class. Use ast.Constant instead - """ + """Deprecated AST node class. Use ast.Constant instead""" def __new__(cls, s: bytes, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor] @deprecated("Replaced by ast.Constant; removed in Python 3.14") class NameConstant(Constant, metaclass=_ABC): - """ - Deprecated AST node class. Use ast.Constant instead - """ + """Deprecated AST node class. Use ast.Constant instead""" def __new__(cls, value: _ConstantValue, kind: str | None, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor] @deprecated("Replaced by ast.Constant; removed in Python 3.14") class Ellipsis(Constant, metaclass=_ABC): - """ - Deprecated AST node class. Use ast.Constant instead - """ + """Deprecated AST node class. Use ast.Constant instead""" def __new__(cls, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor] @@ -2603,8 +2167,7 @@ if sys.version_info >= (3, 13): feature_version: None | int | tuple[int, int] = None, optimize: Literal[-1, 0, 1, 2] = -1, ) -> Module: - """ - Parse the source into an AST node. + """Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). Pass type_comments=True to get back type comments where the syntax allows. """ @@ -2687,8 +2250,7 @@ else: type_comments: bool = False, feature_version: None | int | tuple[int, int] = None, ) -> Module: - """ - Parse the source into an AST node. + """Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). Pass type_comments=True to get back type comments where the syntax allows. """ @@ -2755,8 +2317,7 @@ else: ) -> mod: ... def literal_eval(node_or_string: str | AST) -> Any: - """ - Evaluate an expression node or a string containing only a Python + """Evaluate an expression node or a string containing only a Python expression. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None. @@ -2773,8 +2334,7 @@ if sys.version_info >= (3, 13): indent: int | str | None = None, show_empty: bool = False, ) -> str: - """ - Return a formatted dump of the tree in node. This is mainly useful for + """Return a formatted dump of the tree in node. This is mainly useful for debugging purposes. If annotate_fields is true (by default), the returned string will show the names and the values for fields. If annotate_fields is false, the result string will be more compact by @@ -2791,8 +2351,7 @@ else: def dump( node: AST, annotate_fields: bool = True, include_attributes: bool = False, *, indent: int | str | None = None ) -> str: - """ - Return a formatted dump of the tree in node. This is mainly useful for + """Return a formatted dump of the tree in node. This is mainly useful for debugging purposes. If annotate_fields is true (by default), the returned string will show the names and the values for fields. If annotate_fields is false, the result string will be more compact by @@ -2804,14 +2363,12 @@ else: """ def copy_location(new_node: _T, old_node: AST) -> _T: - """ - Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset` + """Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset` attributes) from *old_node* to *new_node* if possible, and return *new_node*. """ def fix_missing_locations(node: _T) -> _T: - """ - When you compile a node tree with compile(), the compiler expects lineno and + """When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the @@ -2819,27 +2376,23 @@ def fix_missing_locations(node: _T) -> _T: """ def increment_lineno(node: _T, n: int = 1) -> _T: - """ - Increment the line number and end line number of each node in the tree + """Increment the line number and end line number of each node in the tree starting at *node* by *n*. This is useful to "move code" to a different location in a file. """ def iter_fields(node: AST) -> Iterator[tuple[str, Any]]: - """ - Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` + """Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*. """ def iter_child_nodes(node: AST) -> Iterator[AST]: - """ - Yield all direct child nodes of *node*, that is, all fields that are nodes + """Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes. """ def get_docstring(node: AsyncFunctionDef | FunctionDef | ClassDef | Module, clean: bool = True) -> str | None: - """ - Return the docstring for the given node or None if no docstring can + """Return the docstring for the given node or None if no docstring can be found. If the node provided does not have docstrings a TypeError will be raised. @@ -2848,8 +2401,7 @@ def get_docstring(node: AsyncFunctionDef | FunctionDef | ClassDef | Module, clea """ def get_source_segment(source: str, node: AST, *, padded: bool = False) -> str | None: - """ - Get source code segment of the *source* that generated *node*. + """Get source code segment of the *source* that generated *node*. If some location information (`lineno`, `end_lineno`, `col_offset`, or `end_col_offset`) is missing, return None. @@ -2859,16 +2411,14 @@ def get_source_segment(source: str, node: AST, *, padded: bool = False) -> str | """ def walk(node: AST) -> Iterator[AST]: - """ - Recursively yield all descendant nodes in the tree starting at *node* + """Recursively yield all descendant nodes in the tree starting at *node* (including *node* itself), in no specified order. This is useful if you only want to modify nodes in place and don't care about the context. """ if sys.version_info >= (3, 14): def compare(left: AST, right: AST, /, *, compare_attributes: bool = False) -> bool: - """ - Recursively compares two ASTs. + """Recursively compares two ASTs. compare_attributes affects whether AST attributes are considered in the comparison. If compare_attributes is False (default), then @@ -2878,8 +2428,7 @@ if sys.version_info >= (3, 14): """ class NodeVisitor: - """ - A node visitor base class that walks the abstract syntax tree and calls a + """A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the `visit` method. @@ -2900,14 +2449,10 @@ class NodeVisitor: # All visit methods below can be overwritten by subclasses and return an # arbitrary value, which is passed to the caller. def visit(self, node: AST) -> Any: - """ - Visit a node. - """ + """Visit a node.""" def generic_visit(self, node: AST) -> Any: - """ - Called if no explicit visitor function exists for a node. - """ + """Called if no explicit visitor function exists for a node.""" # The following visit methods are not defined on NodeVisitor, but can # be implemented by subclasses and are called during a visit if defined. def visit_Module(self, node: Module) -> Any: ... @@ -3047,8 +2592,7 @@ class NodeVisitor: def visit_Ellipsis(self, node: Ellipsis) -> Any: ... # type: ignore[deprecated] class NodeTransformer(NodeVisitor): - """ - A :class:`NodeVisitor` subclass that walks the abstract syntax tree and + """A :class:`NodeVisitor` subclass that walks the abstract syntax tree and allows modification of nodes. The `NodeTransformer` will walk the AST and use the return value of the diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asynchat.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asynchat.pyi index 4085219f72..91809b3543 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asynchat.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asynchat.pyi @@ -28,8 +28,7 @@ class simple_producer: def more(self) -> bytes: ... class async_chat(asyncore.dispatcher): - """ - This is an abstract class. You must derive from this class, and add + """This is an abstract class. You must derive from this class, and add the two methods collect_incoming_data() and found_terminator() """ @@ -40,8 +39,7 @@ class async_chat(asyncore.dispatcher): @abstractmethod def found_terminator(self) -> None: ... def set_terminator(self, term: bytes | int | None) -> None: - """ - Set the input delimiter. + """Set the input delimiter. Can be a fixed string of any length, an integer, or None. """ @@ -50,9 +48,7 @@ class async_chat(asyncore.dispatcher): def push(self, data: bytes) -> None: ... def push_with_producer(self, producer: simple_producer) -> None: ... def close_when_done(self) -> None: - """ - automatically close this channel once the outgoing queue is empty - """ + """automatically close this channel once the outgoing queue is empty""" def initiate_send(self) -> None: ... def discard_buffers(self) -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/base_events.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/base_events.pyi index 83208c4c21..df123dbf3d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/base_events.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/base_events.pyi @@ -76,8 +76,7 @@ class Server(AbstractServer): def sockets(self) -> tuple[socket, ...]: ... def close(self) -> None: ... async def wait_closed(self) -> None: - """ - Wait until server is closed and all connections are dropped. + """Wait until server is closed and all connections are dropped. - If the server is not closed, wait. - If it is closed, but there are still active connections, wait. @@ -96,13 +95,10 @@ class Server(AbstractServer): class BaseEventLoop(AbstractEventLoop): def run_forever(self) -> None: - """ - Run until stop() is called. - """ + """Run until stop() is called.""" def run_until_complete(self, future: _AwaitableLike[_T]) -> _T: - """ - Run until the Future is done. + """Run until the Future is done. If the argument is a coroutine, it is wrapped in a Task. @@ -114,26 +110,20 @@ class BaseEventLoop(AbstractEventLoop): """ def stop(self) -> None: - """ - Stop running the event loop. + """Stop running the event loop. Every callback already scheduled will still run. This simply informs run_forever to stop looping after a complete iteration. """ def is_running(self) -> bool: - """ - Returns True if the event loop is running. - """ + """Returns True if the event loop is running.""" def is_closed(self) -> bool: - """ - Returns True if the event loop was closed. - """ + """Returns True if the event loop was closed.""" def close(self) -> None: - """ - Close the event loop. + """Close the event loop. This clears the queues and shuts down the executor, but does not wait for the executor to finish. @@ -142,13 +132,10 @@ class BaseEventLoop(AbstractEventLoop): """ async def shutdown_asyncgens(self) -> None: - """ - Shutdown all active asynchronous generators. - """ + """Shutdown all active asynchronous generators.""" # Methods scheduling callbacks. All these return Handles. def call_soon(self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None) -> Handle: - """ - Arrange for a callback to be called as soon as possible. + """Arrange for a callback to be called as soon as possible. This operates as a FIFO queue: callbacks are called in the order in which they are registered. Each callback will be @@ -161,8 +148,7 @@ class BaseEventLoop(AbstractEventLoop): def call_later( self, delay: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None ) -> TimerHandle: - """ - Arrange for a callback to be called at a given time. + """Arrange for a callback to be called at a given time. Return a Handle: an opaque object with a cancel() method that can be used to cancel the call. @@ -181,15 +167,13 @@ class BaseEventLoop(AbstractEventLoop): def call_at( self, when: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None ) -> TimerHandle: - """ - Like call_later(), but uses an absolute time. + """Like call_later(), but uses an absolute time. Absolute time corresponds to the event loop's time() method. """ def time(self) -> float: - """ - Return the time according to the event loop's clock. + """Return the time according to the event loop's clock. This is a float expressed in seconds since an epoch, but the epoch, precision, accuracy and drift are unspecified and may @@ -197,28 +181,23 @@ class BaseEventLoop(AbstractEventLoop): """ # Future methods def create_future(self) -> Future[Any]: - """ - Create a Future object attached to the loop. - """ + """Create a Future object attached to the loop.""" # Tasks methods if sys.version_info >= (3, 11): def create_task(self, coro: _CoroutineLike[_T], *, name: object = None, context: Context | None = None) -> Task[_T]: - """ - Schedule or begin executing a coroutine object. + """Schedule or begin executing a coroutine object. Return a task object. """ else: def create_task(self, coro: _CoroutineLike[_T], *, name: object = None) -> Task[_T]: - """ - Schedule or begin executing a coroutine object. + """Schedule or begin executing a coroutine object. Return a task object. """ def set_task_factory(self, factory: _TaskFactory | None) -> None: - """ - Set a task factory that will be used by loop.create_task(). + """Set a task factory that will be used by loop.create_task(). If factory is None the default task factory will be set. @@ -230,16 +209,12 @@ class BaseEventLoop(AbstractEventLoop): """ def get_task_factory(self) -> _TaskFactory | None: - """ - Return a task factory, or None if the default one is in use. - """ + """Return a task factory, or None if the default one is in use.""" # Methods for interacting with threads def call_soon_threadsafe( self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None ) -> Handle: - """ - Like call_soon(), but thread-safe. - """ + """Like call_soon(), but thread-safe.""" def run_in_executor(self, executor: Executor | None, func: Callable[[Unpack[_Ts]], _T], *args: Unpack[_Ts]) -> Future[_T]: ... def set_default_executor(self, executor: ThreadPoolExecutor) -> None: ... # type: ignore[override] @@ -276,8 +251,7 @@ class BaseEventLoop(AbstractEventLoop): interleave: int | None = None, all_errors: bool = False, ) -> tuple[Transport, _ProtocolT]: - """ - Connect to a TCP server. + """Connect to a TCP server. Create a streaming transport connection to a given internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or @@ -329,8 +303,7 @@ class BaseEventLoop(AbstractEventLoop): happy_eyeballs_delay: float | None = None, interleave: int | None = None, ) -> tuple[Transport, _ProtocolT]: - """ - Connect to a TCP server. + """Connect to a TCP server. Create a streaming transport connection to a given internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or @@ -380,8 +353,7 @@ class BaseEventLoop(AbstractEventLoop): happy_eyeballs_delay: float | None = None, interleave: int | None = None, ) -> tuple[Transport, _ProtocolT]: - """ - Connect to a TCP server. + """Connect to a TCP server. Create a streaming transport connection to a given internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or @@ -433,8 +405,7 @@ class BaseEventLoop(AbstractEventLoop): ssl_shutdown_timeout: float | None = None, start_serving: bool = True, ) -> Server: - """ - Create a TCP server. + """Create a TCP server. The host parameter can be a string, in that case the TCP server is bound to host and port. @@ -488,8 +459,7 @@ class BaseEventLoop(AbstractEventLoop): ssl_shutdown_timeout: float | None = None, start_serving: bool = True, ) -> Server: - """ - Create a TCP server. + """Create a TCP server. The host parameter can be a string, in that case the TCP server is bound to host and port. @@ -541,8 +511,7 @@ class BaseEventLoop(AbstractEventLoop): ssl_handshake_timeout: float | None = None, start_serving: bool = True, ) -> Server: - """ - Create a TCP server. + """Create a TCP server. The host parameter can be a string, in that case the TCP server is bound to host and port. @@ -588,8 +557,7 @@ class BaseEventLoop(AbstractEventLoop): ssl_handshake_timeout: float | None = None, ssl_shutdown_timeout: float | None = None, ) -> Transport | None: - """ - Upgrade transport to TLS. + """Upgrade transport to TLS. Return a new transport that *protocol* should start using immediately. @@ -604,8 +572,7 @@ class BaseEventLoop(AbstractEventLoop): ssl_handshake_timeout: float | None = None, ssl_shutdown_timeout: float | None = None, ) -> tuple[Transport, _ProtocolT]: - """ - Handle an accepted connection. + """Handle an accepted connection. This is used by servers that accept connections outside of asyncio but that use asyncio to handle connections. @@ -624,8 +591,7 @@ class BaseEventLoop(AbstractEventLoop): server_hostname: str | None = None, ssl_handshake_timeout: float | None = None, ) -> Transport | None: - """ - Upgrade transport to TLS. + """Upgrade transport to TLS. Return a new transport that *protocol* should start using immediately. @@ -639,8 +605,7 @@ class BaseEventLoop(AbstractEventLoop): ssl: _SSLContext = None, ssl_handshake_timeout: float | None = None, ) -> tuple[Transport, _ProtocolT]: - """ - Handle an accepted connection. + """Handle an accepted connection. This is used by servers that accept connections outside of asyncio but that use asyncio to handle connections. @@ -655,8 +620,7 @@ class BaseEventLoop(AbstractEventLoop): async def sendfile( self, transport: WriteTransport, file: IO[bytes], offset: int = 0, count: int | None = None, *, fallback: bool = True ) -> int: - """ - Send a file to transport. + """Send a file to transport. Return the total number of bytes which were sent. @@ -692,9 +656,7 @@ class BaseEventLoop(AbstractEventLoop): allow_broadcast: bool | None = None, sock: socket | None = None, ) -> tuple[DatagramTransport, _ProtocolT]: - """ - Create datagram connection. - """ + """Create datagram connection.""" else: async def create_datagram_endpoint( self, @@ -710,9 +672,7 @@ class BaseEventLoop(AbstractEventLoop): allow_broadcast: bool | None = None, sock: socket | None = None, ) -> tuple[DatagramTransport, _ProtocolT]: - """ - Create datagram connection. - """ + """Create datagram connection.""" # Pipes and subprocesses. async def connect_read_pipe( self, protocol_factory: Callable[[], _ProtocolT], pipe: Any @@ -772,8 +732,7 @@ class BaseEventLoop(AbstractEventLoop): def remove_signal_handler(self, sig: int) -> bool: ... # Error handlers. def set_exception_handler(self, handler: _ExceptionHandler | None) -> None: - """ - Set handler as the new event loop exception handler. + """Set handler as the new event loop exception handler. If handler is None, the default exception handler will be set. @@ -786,13 +745,10 @@ class BaseEventLoop(AbstractEventLoop): """ def get_exception_handler(self) -> _ExceptionHandler | None: - """ - Return an exception handler, or None if the default one is in use. - """ + """Return an exception handler, or None if the default one is in use.""" def default_exception_handler(self, context: _Context) -> None: - """ - Default exception handler. + """Default exception handler. This is called when an exception occurs and no exception handler is set, and can be called by a custom exception @@ -808,8 +764,7 @@ class BaseEventLoop(AbstractEventLoop): """ def call_exception_handler(self, context: _Context) -> None: - """ - Call the current event loop's exception handler. + """Call the current event loop's exception handler. The context argument is a dict containing the following keys: @@ -837,8 +792,7 @@ class BaseEventLoop(AbstractEventLoop): def set_debug(self, enabled: bool) -> None: ... if sys.version_info >= (3, 12): async def shutdown_default_executor(self, timeout: float | None = None) -> None: - """ - Schedule the shutdown of the default executor. + """Schedule the shutdown of the default executor. The timeout parameter specifies the amount of time the executor will be given to finish joining. The default value is None, which means @@ -846,8 +800,7 @@ class BaseEventLoop(AbstractEventLoop): """ else: async def shutdown_default_executor(self) -> None: - """ - Schedule the shutdown of the default executor. + """Schedule the shutdown of the default executor. The timeout parameter specifies the amount of time the executor will be given to finish joining. The default value is None, which means diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/base_futures.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/base_futures.pyi index 82db49dd22..aef35ab1d6 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/base_futures.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/base_futures.pyi @@ -16,11 +16,7 @@ _CANCELLED: Final = "CANCELLED" # undocumented _FINISHED: Final = "FINISHED" # undocumented def _format_callbacks(cb: Sequence[tuple[Callable[[futures.Future[Any]], None], Context]]) -> str: # undocumented - """ - helper function for Future.__repr__ - """ + """helper function for Future.__repr__""" def _future_repr_info(future: futures.Future[Any]) -> list[str]: # undocumented - """ - helper function for Future.__repr__ - """ + """helper function for Future.__repr__""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/base_subprocess.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/base_subprocess.pyi index 5f2b8ae685..989824b610 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/base_subprocess.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/base_subprocess.pyi @@ -53,8 +53,7 @@ class BaseSubprocessTransport(transports.SubprocessTransport): def _pipe_data_received(self, fd: int, data: bytes) -> None: ... # undocumented def _process_exited(self, returncode: int) -> None: ... # undocumented async def _wait(self) -> int: # undocumented - """ - Wait until the process exit and return the process return code. + """Wait until the process exit and return the process return code. This method is a coroutine. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/constants.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/constants.pyi index 43b2dfdb57..61aaf51e02 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/constants.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/constants.pyi @@ -15,9 +15,7 @@ if sys.version_info >= (3, 12): THREAD_JOIN_TIMEOUT: Final = 300 class _SendfileMode(enum.Enum): - """ - An enumeration. - """ + """An enumeration.""" UNSUPPORTED = 1 TRY_NATIVE = 2 diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/coroutines.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/coroutines.pyi index 29897c16dd..2908051fdd 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/coroutines.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/coroutines.pyi @@ -15,8 +15,7 @@ _P = ParamSpec("_P") if sys.version_info < (3, 11): def coroutine(func: _FunctionT) -> _FunctionT: - """ - Decorator to mark coroutines. + """Decorator to mark coroutines. If the coroutine is not yielded from before it is destroyed, an error message is logged. @@ -24,9 +23,7 @@ if sys.version_info < (3, 11): @overload def iscoroutinefunction(func: Callable[..., Coroutine[Any, Any, Any]]) -> bool: - """ - Return True if func is a decorated coroutine function. - """ + """Return True if func is a decorated coroutine function.""" @overload def iscoroutinefunction(func: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, _T]]]: ... @@ -35,6 +32,4 @@ def iscoroutinefunction(func: Callable[_P, object]) -> TypeGuard[Callable[_P, Co @overload def iscoroutinefunction(func: object) -> TypeGuard[Callable[..., Coroutine[Any, Any, Any]]]: ... def iscoroutine(obj: object) -> TypeIs[Coroutine[Any, Any, Any]]: - """ - Return True if obj is a coroutine object. - """ + """Return True if obj is a coroutine object.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/events.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/events.pyi index d089394d73..76432a33db 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/events.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/events.pyi @@ -79,9 +79,7 @@ class _TaskFactory(Protocol): def __call__(self, loop: AbstractEventLoop, factory: _CoroutineLike[_T], /) -> Future[_T]: ... class Handle: - """ - Object returned by callback registration methods. - """ + """Object returned by callback registration methods.""" _cancelled: bool _args: Sequence[Any] @@ -95,9 +93,7 @@ class Handle: def get_context(self) -> Context: ... class TimerHandle(Handle): - """ - Object returned by timed callback registration methods. - """ + """Object returned by timed callback registration methods.""" def __init__( self, @@ -109,8 +105,7 @@ class TimerHandle(Handle): ) -> None: ... def __hash__(self) -> int: ... def when(self) -> float: - """ - Return a scheduled callback time. + """Return a scheduled callback time. The time is an absolute timestamp, using the same time reference as loop.time(). @@ -123,46 +118,33 @@ class TimerHandle(Handle): def __eq__(self, other: object) -> bool: ... class AbstractServer: - """ - Abstract server returned by create_server(). - """ + """Abstract server returned by create_server().""" @abstractmethod def close(self) -> None: - """ - Stop serving. This leaves existing connections open. - """ + """Stop serving. This leaves existing connections open.""" if sys.version_info >= (3, 13): @abstractmethod def close_clients(self) -> None: - """ - Close all active connections. - """ + """Close all active connections.""" @abstractmethod def abort_clients(self) -> None: - """ - Close all active connections immediately. - """ + """Close all active connections immediately.""" async def __aenter__(self) -> Self: ... async def __aexit__(self, *exc: Unused) -> None: ... @abstractmethod def get_loop(self) -> AbstractEventLoop: - """ - Get the event loop the Server object is attached to. - """ + """Get the event loop the Server object is attached to.""" @abstractmethod def is_serving(self) -> bool: - """ - Return True if the server is accepting connections. - """ + """Return True if the server is accepting connections.""" @abstractmethod async def start_serving(self) -> None: - """ - Start accepting connections. + """Start accepting connections. This method is idempotent, so it can be called when the server is already being serving. @@ -170,42 +152,33 @@ class AbstractServer: @abstractmethod async def serve_forever(self) -> None: - """ - Start accepting connections until the coroutine is cancelled. + """Start accepting connections until the coroutine is cancelled. The server is closed when the coroutine is cancelled. """ @abstractmethod async def wait_closed(self) -> None: - """ - Coroutine to wait until service is closed. - """ + """Coroutine to wait until service is closed.""" class AbstractEventLoop: - """ - Abstract event loop. - """ + """Abstract event loop.""" slow_callback_duration: float @abstractmethod def run_forever(self) -> None: - """ - Run the event loop until stop() is called. - """ + """Run the event loop until stop() is called.""" @abstractmethod def run_until_complete(self, future: _AwaitableLike[_T]) -> _T: - """ - Run the event loop until a Future is done. + """Run the event loop until a Future is done. Return the Future's result, or raise its exception. """ @abstractmethod def stop(self) -> None: - """ - Stop the event loop as soon as reasonable. + """Stop the event loop as soon as reasonable. Exactly how soon that is may depend on the implementation, but no more I/O callbacks should be scheduled. @@ -213,20 +186,15 @@ class AbstractEventLoop: @abstractmethod def is_running(self) -> bool: - """ - Return whether the event loop is currently running. - """ + """Return whether the event loop is currently running.""" @abstractmethod def is_closed(self) -> bool: - """ - Returns True if the event loop was closed. - """ + """Returns True if the event loop was closed.""" @abstractmethod def close(self) -> None: - """ - Close the loop. + """Close the loop. The loop should not be running. @@ -237,9 +205,7 @@ class AbstractEventLoop: @abstractmethod async def shutdown_asyncgens(self) -> None: - """ - Shutdown all active asynchronous generators. - """ + """Shutdown all active asynchronous generators.""" # Methods scheduling callbacks. All these return Handles. # "context" added in 3.9.10/3.10.2 for call_* @abstractmethod @@ -400,8 +366,7 @@ class AbstractEventLoop: ssl_shutdown_timeout: float | None = None, start_serving: bool = True, ) -> Server: - """ - A coroutine which creates a TCP server bound to host and port. + """A coroutine which creates a TCP server bound to host and port. The return value is a Server object which can be used to stop the service. @@ -493,8 +458,7 @@ class AbstractEventLoop: ssl_shutdown_timeout: float | None = None, start_serving: bool = True, ) -> Server: - """ - A coroutine which creates a TCP server bound to host and port. + """A coroutine which creates a TCP server bound to host and port. The return value is a Server object which can be used to stop the service. @@ -584,8 +548,7 @@ class AbstractEventLoop: ssl_handshake_timeout: float | None = None, start_serving: bool = True, ) -> Server: - """ - A coroutine which creates a TCP server bound to host and port. + """A coroutine which creates a TCP server bound to host and port. The return value is a Server object which can be used to stop the service. @@ -669,8 +632,7 @@ class AbstractEventLoop: ssl_handshake_timeout: float | None = None, ssl_shutdown_timeout: float | None = None, ) -> Transport | None: - """ - Upgrade a transport to TLS. + """Upgrade a transport to TLS. Return a new transport that *protocol* should start using immediately. @@ -688,8 +650,7 @@ class AbstractEventLoop: ssl_shutdown_timeout: float | None = None, start_serving: bool = True, ) -> Server: - """ - A coroutine which creates a UNIX Domain Socket server. + """A coroutine which creates a UNIX Domain Socket server. The return value is a Server object, which can be used to stop the service. @@ -729,8 +690,7 @@ class AbstractEventLoop: server_hostname: str | None = None, ssl_handshake_timeout: float | None = None, ) -> Transport | None: - """ - Upgrade a transport to TLS. + """Upgrade a transport to TLS. Return a new transport that *protocol* should start using immediately. @@ -747,8 +707,7 @@ class AbstractEventLoop: ssl_handshake_timeout: float | None = None, start_serving: bool = True, ) -> Server: - """ - A coroutine which creates a UNIX Domain Socket server. + """A coroutine which creates a UNIX Domain Socket server. The return value is a Server object, which can be used to stop the service. @@ -786,8 +745,7 @@ class AbstractEventLoop: ssl_handshake_timeout: float | None = None, ssl_shutdown_timeout: float | None = None, ) -> tuple[Transport, _ProtocolT]: - """ - Handle an accepted connection. + """Handle an accepted connection. This is used by servers that accept connections outside of asyncio, but use asyncio to handle connections. @@ -804,8 +762,7 @@ class AbstractEventLoop: ssl: _SSLContext = None, ssl_handshake_timeout: float | None = None, ) -> tuple[Transport, _ProtocolT]: - """ - Handle an accepted connection. + """Handle an accepted connection. This is used by servers that accept connections outside of asyncio, but use asyncio to handle connections. @@ -845,8 +802,7 @@ class AbstractEventLoop: async def sendfile( self, transport: WriteTransport, file: IO[bytes], offset: int = 0, count: int | None = None, *, fallback: bool = True ) -> int: - """ - Send a file through a transport. + """Send a file through a transport. Return an amount of sent bytes. """ @@ -866,8 +822,7 @@ class AbstractEventLoop: allow_broadcast: bool | None = None, sock: socket | None = None, ) -> tuple[DatagramTransport, _ProtocolT]: - """ - A coroutine which creates a datagram endpoint. + """A coroutine which creates a datagram endpoint. This method will try to establish the endpoint in the background. When successful, the coroutine returns a (transport, protocol) pair. @@ -898,8 +853,7 @@ class AbstractEventLoop: # Pipes and subprocesses. @abstractmethod async def connect_read_pipe(self, protocol_factory: Callable[[], _ProtocolT], pipe: Any) -> tuple[ReadTransport, _ProtocolT]: - """ - Register read pipe in event loop. Set the pipe to non-blocking mode. + """Register read pipe in event loop. Set the pipe to non-blocking mode. protocol_factory should instantiate object with Protocol interface. pipe is a file-like object. @@ -911,8 +865,7 @@ class AbstractEventLoop: async def connect_write_pipe( self, protocol_factory: Callable[[], _ProtocolT], pipe: Any ) -> tuple[WriteTransport, _ProtocolT]: - """ - Register write pipe in event loop. + """Register write pipe in event loop. protocol_factory should instantiate object with BaseProtocol interface. Pipe is file-like object already switched to nonblocking. @@ -999,19 +952,14 @@ class AbstractEventLoop: def set_debug(self, enabled: bool) -> None: ... @abstractmethod async def shutdown_default_executor(self) -> None: - """ - Schedule the shutdown of the default executor. - """ + """Schedule the shutdown of the default executor.""" class _AbstractEventLoopPolicy: - """ - Abstract policy for accessing the event loop. - """ + """Abstract policy for accessing the event loop.""" @abstractmethod def get_event_loop(self) -> AbstractEventLoop: - """ - Get the event loop for the current context. + """Get the event loop for the current context. Returns an event loop object implementing the AbstractEventLoop interface, or raises an exception in case no event loop has been set for the @@ -1022,14 +970,11 @@ class _AbstractEventLoopPolicy: @abstractmethod def set_event_loop(self, loop: AbstractEventLoop | None) -> None: - """ - Set the event loop for the current context to loop. - """ + """Set the event loop for the current context to loop.""" @abstractmethod def new_event_loop(self) -> AbstractEventLoop: - """ - Create and return a new event loop object according to this + """Create and return a new event loop object according to this policy's rules. If there's need to set this loop as the event loop for the current context, set_event_loop must be called explicitly. """ @@ -1053,8 +998,7 @@ if sys.version_info < (3, 14): if sys.version_info >= (3, 14): class _BaseDefaultEventLoopPolicy(_AbstractEventLoopPolicy, metaclass=ABCMeta): - """ - Default policy implementation for accessing the event loop. + """Default policy implementation for accessing the event loop. In this policy, each thread has its own event loop. However, we only automatically create an event loop by default for the main @@ -1067,20 +1011,16 @@ if sys.version_info >= (3, 14): """ def get_event_loop(self) -> AbstractEventLoop: - """ - Get the event loop for the current context. + """Get the event loop for the current context. Returns an instance of EventLoop or raises an exception. """ def set_event_loop(self, loop: AbstractEventLoop | None) -> None: - """ - Set the event loop. - """ + """Set the event loop.""" def new_event_loop(self) -> AbstractEventLoop: - """ - Create a new event loop. + """Create a new event loop. You must call set_event_loop() to make this the current event loop. @@ -1088,8 +1028,7 @@ if sys.version_info >= (3, 14): else: class BaseDefaultEventLoopPolicy(_AbstractEventLoopPolicy, metaclass=ABCMeta): - """ - Default policy implementation for accessing the event loop. + """Default policy implementation for accessing the event loop. In this policy, each thread has its own event loop. However, we only automatically create an event loop by default for the main @@ -1102,20 +1041,16 @@ else: """ def get_event_loop(self) -> AbstractEventLoop: - """ - Get the event loop for the current context. + """Get the event loop for the current context. Returns an instance of EventLoop or raises an exception. """ def set_event_loop(self, loop: AbstractEventLoop | None) -> None: - """ - Set the event loop. - """ + """Set the event loop.""" def new_event_loop(self) -> AbstractEventLoop: - """ - Create a new event loop. + """Create a new event loop. You must call set_event_loop() to make this the current event loop. @@ -1123,13 +1058,10 @@ else: if sys.version_info >= (3, 14): def _get_event_loop_policy() -> _AbstractEventLoopPolicy: - """ - Get the current event loop policy. - """ + """Get the current event loop policy.""" def _set_event_loop_policy(policy: _AbstractEventLoopPolicy | None) -> None: - """ - Set the current event loop policy. + """Set the current event loop policy. If policy is None, the default policy is restored. """ @@ -1141,49 +1073,36 @@ if sys.version_info >= (3, 14): else: def get_event_loop_policy() -> _AbstractEventLoopPolicy: - """ - Get the current event loop policy. - """ + """Get the current event loop policy.""" def set_event_loop_policy(policy: _AbstractEventLoopPolicy | None) -> None: - """ - Set the current event loop policy. + """Set the current event loop policy. If policy is None, the default policy is restored. """ def set_event_loop(loop: AbstractEventLoop | None) -> None: - """ - Equivalent to calling get_event_loop_policy().set_event_loop(loop). - """ + """Equivalent to calling get_event_loop_policy().set_event_loop(loop).""" def new_event_loop() -> AbstractEventLoop: - """ - Equivalent to calling get_event_loop_policy().new_event_loop(). - """ + """Equivalent to calling get_event_loop_policy().new_event_loop().""" if sys.version_info < (3, 14): if sys.version_info >= (3, 12): @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") def get_child_watcher() -> AbstractChildWatcher: - """ - Equivalent to calling get_event_loop_policy().get_child_watcher(). - """ + """Equivalent to calling get_event_loop_policy().get_child_watcher().""" @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") def set_child_watcher(watcher: AbstractChildWatcher) -> None: - """ - Equivalent to calling + """Equivalent to calling get_event_loop_policy().set_child_watcher(watcher). """ else: def get_child_watcher() -> AbstractChildWatcher: - """ - Equivalent to calling get_event_loop_policy().get_child_watcher(). - """ + """Equivalent to calling get_event_loop_policy().get_child_watcher().""" def set_child_watcher(watcher: AbstractChildWatcher) -> None: - """ - Equivalent to calling + """Equivalent to calling get_event_loop_policy().set_child_watcher(watcher). """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/exceptions.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/exceptions.pyi index 554575fa69..fd92ed03d3 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/exceptions.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/exceptions.pyi @@ -26,34 +26,26 @@ else: ) class CancelledError(BaseException): - """ - The Future or Task was cancelled. - """ + """The Future or Task was cancelled.""" if sys.version_info >= (3, 11): from builtins import TimeoutError as TimeoutError else: class TimeoutError(Exception): - """ - The operation exceeded the given deadline. - """ + """The operation exceeded the given deadline.""" class InvalidStateError(Exception): - """ - The operation is not allowed in this state. - """ + """The operation is not allowed in this state.""" class SendfileNotAvailableError(RuntimeError): - """ - Sendfile syscall is not available. + """Sendfile syscall is not available. Raised if OS does not support sendfile syscall for given socket or file type. """ class IncompleteReadError(EOFError): - """ - Incomplete read error. Attributes: + """Incomplete read error. Attributes: - partial: read bytes string before the end of stream was reached - expected: total number of expected bytes (or None if unknown) @@ -64,8 +56,7 @@ class IncompleteReadError(EOFError): def __init__(self, partial: bytes, expected: int | None) -> None: ... class LimitOverrunError(Exception): - """ - Reached the buffer limit while looking for a separator. + """Reached the buffer limit while looking for a separator. Attributes: - consumed: total number of to be consumed bytes. @@ -76,6 +67,4 @@ class LimitOverrunError(Exception): if sys.version_info >= (3, 11): class BrokenBarrierError(RuntimeError): - """ - Barrier is broken by barrier.abort() call. - """ + """Barrier is broken by barrier.abort() call.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/format_helpers.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/format_helpers.pyi index c0ddc470ad..d9550f1134 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/format_helpers.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/format_helpers.pyi @@ -19,8 +19,7 @@ def _get_function_source(func: object) -> tuple[str, int] | None: ... if sys.version_info >= (3, 13): def _format_callback_source(func: object, args: Iterable[Any], *, debug: bool = False) -> str: ... def _format_args_and_kwargs(args: Iterable[Any], kwargs: dict[str, Any], *, debug: bool = False) -> str: - """ - Format function arguments and keyword arguments. + """Format function arguments and keyword arguments. Special case for a single parameter: ('hello',) is formatted as ('hello'). @@ -36,8 +35,7 @@ if sys.version_info >= (3, 13): else: def _format_callback_source(func: object, args: Iterable[Any]) -> str: ... def _format_args_and_kwargs(args: Iterable[Any], kwargs: dict[str, Any]) -> str: - """ - Format function arguments and keyword arguments. + """Format function arguments and keyword arguments. Special case for a single parameter: ('hello',) is formatted as ('hello'). """ @@ -45,7 +43,6 @@ else: def _format_callback(func: object, args: Iterable[Any], kwargs: dict[str, Any], suffix: str = "") -> str: ... def extract_stack(f: FrameType | None = None, limit: int | None = None) -> traceback.StackSummary: - """ - Replacement for traceback.extract_stack() that only does the + """Replacement for traceback.extract_stack() that only does the necessary work for asyncio debug mode. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/futures.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/futures.pyi index e239e85f1e..dee7874ea0 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/futures.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/futures.pyi @@ -24,8 +24,7 @@ _T = TypeVar("_T") # but it leads to circular import error in pytype tool. # That's why the import order is reversed. def isfuture(obj: object) -> TypeIs[Future[Any]]: - """ - Check for a Future. + """Check for a Future. This returns True when obj is a Future instance or is advertising itself as duck-type compatible by setting _asyncio_future_blocking. @@ -33,6 +32,4 @@ def isfuture(obj: object) -> TypeIs[Future[Any]]: """ def wrap_future(future: _ConcurrentFuture[_T] | Future[_T], *, loop: AbstractEventLoop | None = None) -> Future[_T]: - """ - Wrap concurrent.futures.Future object. - """ + """Wrap concurrent.futures.Future object.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/graph.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/graph.pyi index 200a34359b..efe49315b1 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/graph.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/graph.pyi @@ -12,17 +12,13 @@ __all__ = ("capture_call_graph", "format_call_graph", "print_call_graph", "Frame @dataclass(frozen=True) class FrameCallGraphEntry: - """ - FrameCallGraphEntry(frame: frame) - """ + """FrameCallGraphEntry(frame: frame)""" frame: FrameType @dataclass(frozen=True) class FutureCallGraph: - """ - FutureCallGraph(future: _asyncio.Future, call_stack: tuple['FrameCallGraphEntry', ...], awaited_by: tuple['FutureCallGraph', ...]) - """ + """FutureCallGraph(future: _asyncio.Future, call_stack: tuple['FrameCallGraphEntry', ...], awaited_by: tuple['FutureCallGraph', ...])""" future: Future[Any] call_stack: tuple[FrameCallGraphEntry, ...] @@ -30,8 +26,7 @@ class FutureCallGraph: @overload def capture_call_graph(future: None = None, /, *, depth: int = 1, limit: int | None = None) -> FutureCallGraph | None: - """ - Capture the async call graph for the current task or the provided Future. + """Capture the async call graph for the current task or the provided Future. The graph is represented with three data structures: @@ -68,8 +63,7 @@ def capture_call_graph(future: None = None, /, *, depth: int = 1, limit: int | N @overload def capture_call_graph(future: Future[Any], /, *, depth: int = 1, limit: int | None = None) -> FutureCallGraph | None: ... def format_call_graph(future: Future[Any] | None = None, /, *, depth: int = 1, limit: int | None = None) -> str: - """ - Return the async call graph as a string for `future`. + """Return the async call graph as a string for `future`. If `future` is not provided, format the call graph for the current task. """ @@ -77,6 +71,4 @@ def format_call_graph(future: Future[Any] | None = None, /, *, depth: int = 1, l def print_call_graph( future: Future[Any] | None = None, /, *, file: SupportsWrite[str] | None = None, depth: int = 1, limit: int | None = None ) -> None: - """ - Print the async call graph for the current task or the provided Future. - """ + """Print the async call graph for the current task or the provided Future.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/locks.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/locks.pyi index 805acc3ef9..fbc766bce7 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/locks.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/locks.pyi @@ -34,8 +34,7 @@ class _ContextManagerMixin: ) -> None: ... class Lock(_ContextManagerMixin, _LoopBoundMixin): - """ - Primitive lock objects. + """Primitive lock objects. A primitive lock is a synchronization primitive that is not owned by a particular task when locked. A primitive lock is in one @@ -92,21 +91,17 @@ class Lock(_ContextManagerMixin, _LoopBoundMixin): def __init__(self, *, loop: AbstractEventLoop | None = None) -> None: ... def locked(self) -> bool: - """ - Return True if lock is acquired. - """ + """Return True if lock is acquired.""" async def acquire(self) -> Literal[True]: - """ - Acquire a lock. + """Acquire a lock. This method blocks until the lock is unlocked, then sets it to locked and returns True. """ def release(self) -> None: - """ - Release a lock. + """Release a lock. When the lock is locked, reset it to unlocked, and return. If any other tasks are blocked waiting for the lock to become @@ -118,8 +113,7 @@ class Lock(_ContextManagerMixin, _LoopBoundMixin): """ class Event(_LoopBoundMixin): - """ - Asynchronous equivalent to threading.Event. + """Asynchronous equivalent to threading.Event. Class implementing event objects. An event manages a flag that can be set to true with the set() method and reset to false with the clear() method. @@ -134,27 +128,22 @@ class Event(_LoopBoundMixin): def __init__(self, *, loop: AbstractEventLoop | None = None) -> None: ... def is_set(self) -> bool: - """ - Return True if and only if the internal flag is true. - """ + """Return True if and only if the internal flag is true.""" def set(self) -> None: - """ - Set the internal flag to true. All tasks waiting for it to + """Set the internal flag to true. All tasks waiting for it to become true are awakened. Tasks that call wait() once the flag is true will not block at all. """ def clear(self) -> None: - """ - Reset the internal flag to false. Subsequently, tasks calling + """Reset the internal flag to false. Subsequently, tasks calling wait() will block until set() is called to set the internal flag to true again. """ async def wait(self) -> Literal[True]: - """ - Block until the internal flag is true. + """Block until the internal flag is true. If the internal flag is true on entry, return True immediately. Otherwise, block until another task calls @@ -162,8 +151,7 @@ class Event(_LoopBoundMixin): """ class Condition(_ContextManagerMixin, _LoopBoundMixin): - """ - Asynchronous equivalent to threading.Condition. + """Asynchronous equivalent to threading.Condition. This class implements condition variable objects. A condition variable allows one or more tasks to wait until they are notified by another @@ -182,8 +170,7 @@ class Condition(_ContextManagerMixin, _LoopBoundMixin): async def acquire(self) -> Literal[True]: ... def release(self) -> None: ... async def wait(self) -> Literal[True]: - """ - Wait until notified. + """Wait until notified. If the calling task has not acquired the lock when this method is called, a RuntimeError is raised. @@ -199,8 +186,7 @@ class Condition(_ContextManagerMixin, _LoopBoundMixin): """ async def wait_for(self, predicate: Callable[[], _T]) -> _T: - """ - Wait until a predicate becomes true. + """Wait until a predicate becomes true. The predicate should be a callable whose result will be interpreted as a boolean value. The method will repeatedly @@ -209,8 +195,7 @@ class Condition(_ContextManagerMixin, _LoopBoundMixin): """ def notify(self, n: int = 1) -> None: - """ - By default, wake up one task waiting on this condition, if any. + """By default, wake up one task waiting on this condition, if any. If the calling task has not acquired the lock when this method is called, a RuntimeError is raised. @@ -223,16 +208,14 @@ class Condition(_ContextManagerMixin, _LoopBoundMixin): """ def notify_all(self) -> None: - """ - Wake up all tasks waiting on this condition. This method acts + """Wake up all tasks waiting on this condition. This method acts like notify(), but wakes up all waiting tasks instead of one. If the calling task has not acquired the lock when this method is called, a RuntimeError is raised. """ class Semaphore(_ContextManagerMixin, _LoopBoundMixin): - """ - A Semaphore implementation. + """A Semaphore implementation. A semaphore manages an internal counter which is decremented by each acquire() call and incremented by each release() call. The counter @@ -254,13 +237,10 @@ class Semaphore(_ContextManagerMixin, _LoopBoundMixin): def __init__(self, value: int = 1, *, loop: AbstractEventLoop | None = None) -> None: ... def locked(self) -> bool: - """ - Returns True if semaphore cannot be acquired immediately. - """ + """Returns True if semaphore cannot be acquired immediately.""" async def acquire(self) -> Literal[True]: - """ - Acquire a semaphore. + """Acquire a semaphore. If the internal counter is larger than zero on entry, decrement it by one and return True immediately. If it is @@ -270,21 +250,17 @@ class Semaphore(_ContextManagerMixin, _LoopBoundMixin): """ def release(self) -> None: - """ - Release a semaphore, incrementing the internal counter by one. + """Release a semaphore, incrementing the internal counter by one. When it was zero on entry and another task is waiting for it to become larger than zero again, wake up that task. """ def _wake_up_next(self) -> None: - """ - Wake up the first waiter that isn't done. - """ + """Wake up the first waiter that isn't done.""" class BoundedSemaphore(Semaphore): - """ - A bounded semaphore implementation. + """A bounded semaphore implementation. This raises ValueError in release() if it would increase the value above the initial value. @@ -298,8 +274,7 @@ if sys.version_info >= (3, 11): BROKEN = "broken" class Barrier(_LoopBoundMixin): - """ - Asyncio equivalent to threading.Barrier + """Asyncio equivalent to threading.Barrier Implements a Barrier primitive. Useful for synchronizing a fixed number of tasks at known synchronization @@ -308,15 +283,12 @@ if sys.version_info >= (3, 11): """ def __init__(self, parties: int) -> None: - """ - Create a barrier, initialised to 'parties' tasks. - """ + """Create a barrier, initialised to 'parties' tasks.""" async def __aenter__(self) -> Self: ... async def __aexit__(self, *args: Unused) -> None: ... async def wait(self) -> int: - """ - Wait for the barrier. + """Wait for the barrier. When the specified number of tasks have started waiting, they are all simultaneously awoken. @@ -324,16 +296,14 @@ if sys.version_info >= (3, 11): """ async def abort(self) -> None: - """ - Place the barrier into a 'broken' state. + """Place the barrier into a 'broken' state. Useful in case of error. Any currently waiting tasks and tasks attempting to 'wait()' will have BrokenBarrierError raised. """ async def reset(self) -> None: - """ - Reset the barrier to the initial state. + """Reset the barrier to the initial state. Any tasks currently waiting will get the BrokenBarrier exception raised. @@ -341,18 +311,12 @@ if sys.version_info >= (3, 11): @property def parties(self) -> int: - """ - Return the number of tasks required to trip the barrier. - """ + """Return the number of tasks required to trip the barrier.""" @property def n_waiting(self) -> int: - """ - Return the number of tasks currently waiting at the barrier. - """ + """Return the number of tasks currently waiting at the barrier.""" @property def broken(self) -> bool: - """ - Return True if the barrier is in a broken state. - """ + """Return True if the barrier is in a broken state.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/proactor_events.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/proactor_events.pyi index 8b7931a1da..3891d6d5f4 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/proactor_events.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/proactor_events.pyi @@ -15,9 +15,7 @@ from . import base_events, constants, events, futures, streams, transports __all__ = ("BaseProactorEventLoop",) class _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTransport): - """ - Base class for pipe and socket transports. - """ + """Base class for pipe and socket transports.""" def __init__( self, @@ -31,9 +29,7 @@ class _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTr def __del__(self) -> None: ... class _ProactorReadPipeTransport(_ProactorBasePipeTransport, transports.ReadTransport): - """ - Transport for read pipes. - """ + """Transport for read pipes.""" if sys.version_info >= (3, 10): def __init__( @@ -58,21 +54,15 @@ class _ProactorReadPipeTransport(_ProactorBasePipeTransport, transports.ReadTran ) -> None: ... class _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport, transports.WriteTransport): - """ - Transport for write pipes. - """ + """Transport for write pipes.""" class _ProactorWritePipeTransport(_ProactorBaseWritePipeTransport): ... class _ProactorDuplexPipeTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport): - """ - Transport for duplex pipes. - """ + """Transport for duplex pipes.""" class _ProactorSocketTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport): - """ - Transport for connected sockets. - """ + """Transport for connected sockets.""" _sendfile_compatible: ClassVar[constants._SendfileMode] def __init__( diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/protocols.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/protocols.pyi index cab1519f5d..2ca567db8d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/protocols.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/protocols.pyi @@ -10,8 +10,7 @@ from typing import Any __all__ = ("BaseProtocol", "Protocol", "DatagramProtocol", "SubprocessProtocol", "BufferedProtocol") class BaseProtocol: - """ - Common base class for protocol interfaces. + """Common base class for protocol interfaces. Usually user implements protocols that derived from BaseProtocol like Protocol or ProcessProtocol. @@ -21,8 +20,7 @@ class BaseProtocol: """ def connection_made(self, transport: transports.BaseTransport) -> None: - """ - Called when a connection is made. + """Called when a connection is made. The argument is the transport representing the pipe connection. To receive data, wait for data_received() calls. @@ -30,8 +28,7 @@ class BaseProtocol: """ def connection_lost(self, exc: Exception | None) -> None: - """ - Called when the connection is lost or closed. + """Called when the connection is lost or closed. The argument is an exception object or None (the latter meaning a regular EOF is received or the connection was @@ -39,8 +36,7 @@ class BaseProtocol: """ def pause_writing(self) -> None: - """ - Called when the transport's buffer goes over the high-water mark. + """Called when the transport's buffer goes over the high-water mark. Pause and resume calls are paired -- pause_writing() is called once when the buffer goes strictly over the high-water mark @@ -62,15 +58,13 @@ class BaseProtocol: """ def resume_writing(self) -> None: - """ - Called when the transport's buffer drains below the low-water mark. + """Called when the transport's buffer drains below the low-water mark. See pause_writing() for details. """ class Protocol(BaseProtocol): - """ - Interface for stream protocol. + """Interface for stream protocol. The user should implement this interface. They can inherit from this class but don't need to. The implementations here do @@ -96,15 +90,13 @@ class Protocol(BaseProtocol): """ def data_received(self, data: bytes) -> None: - """ - Called when some data is received. + """Called when some data is received. The argument is a bytes object. """ def eof_received(self) -> bool | None: - """ - Called when the other end calls write_eof() or equivalent. + """Called when the other end calls write_eof() or equivalent. If this returns a false value (including None), the transport will close itself. If it returns a true value, closing the @@ -112,8 +104,7 @@ class Protocol(BaseProtocol): """ class BufferedProtocol(BaseProtocol): - """ - Interface for stream protocol with manual buffer control. + """Interface for stream protocol with manual buffer control. Event methods, such as `create_server` and `create_connection`, accept factories that return protocols that implement this interface. @@ -137,8 +128,7 @@ class BufferedProtocol(BaseProtocol): """ def get_buffer(self, sizehint: int) -> ReadableBuffer: - """ - Called to allocate a new receive buffer. + """Called to allocate a new receive buffer. *sizehint* is a recommended minimal size for the returned buffer. When set to -1, the buffer size can be arbitrary. @@ -149,16 +139,14 @@ class BufferedProtocol(BaseProtocol): """ def buffer_updated(self, nbytes: int) -> None: - """ - Called when the buffer was updated with the received data. + """Called when the buffer was updated with the received data. *nbytes* is the total number of bytes that were written to the buffer. """ def eof_received(self) -> bool | None: - """ - Called when the other end calls write_eof() or equivalent. + """Called when the other end calls write_eof() or equivalent. If this returns a false value (including None), the transport will close itself. If it returns a true value, closing the @@ -166,13 +154,10 @@ class BufferedProtocol(BaseProtocol): """ class DatagramProtocol(BaseProtocol): - """ - Interface for datagram protocol. - """ + """Interface for datagram protocol.""" def connection_made(self, transport: transports.DatagramTransport) -> None: # type: ignore[override] - """ - Called when a connection is made. + """Called when a connection is made. The argument is the transport representing the pipe connection. To receive data, wait for data_received() calls. @@ -183,39 +168,30 @@ class DatagramProtocol(BaseProtocol): # This could be improved by using tuple[AnyOf[str, int], int] if the AnyOf feature is accepted. # See https://github.com/python/typing/issues/566 def datagram_received(self, data: bytes, addr: tuple[str | Any, int]) -> None: - """ - Called when some datagram is received. - """ + """Called when some datagram is received.""" def error_received(self, exc: Exception) -> None: - """ - Called when a send or receive operation raises an OSError. + """Called when a send or receive operation raises an OSError. (Other than BlockingIOError or InterruptedError.) """ class SubprocessProtocol(BaseProtocol): - """ - Interface for protocol for subprocess calls. - """ + """Interface for protocol for subprocess calls.""" def pipe_data_received(self, fd: int, data: bytes) -> None: - """ - Called when the subprocess writes data into stdout/stderr pipe. + """Called when the subprocess writes data into stdout/stderr pipe. fd is int file descriptor. data is bytes object. """ def pipe_connection_lost(self, fd: int, exc: Exception | None) -> None: - """ - Called when a file descriptor associated with the child process is + """Called when a file descriptor associated with the child process is closed. fd is the int file descriptor that was closed. """ def process_exited(self) -> None: - """ - Called when subprocess has exited. - """ + """Called when subprocess has exited.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/queues.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/queues.pyi index 40eb83c0be..6473838979 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/queues.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/queues.pyi @@ -9,14 +9,10 @@ else: _LoopBoundMixin = object class QueueEmpty(Exception): - """ - Raised when Queue.get_nowait() is called on an empty Queue. - """ + """Raised when Queue.get_nowait() is called on an empty Queue.""" class QueueFull(Exception): - """ - Raised when the Queue.put_nowait() method is called on a full Queue. - """ + """Raised when the Queue.put_nowait() method is called on a full Queue.""" # Keep asyncio.__all__ updated with any changes to __all__ here if sys.version_info >= (3, 13): @@ -29,15 +25,12 @@ _T = TypeVar("_T") if sys.version_info >= (3, 13): class QueueShutDown(Exception): - """ - Raised when putting on to or getting from a shut-down Queue. - """ + """Raised when putting on to or getting from a shut-down Queue.""" # If Generic[_T] is last and _LoopBoundMixin is object, pyright is unhappy. # We can remove the noqa pragma when dropping 3.9 support. class Queue(Generic[_T], _LoopBoundMixin): # noqa: Y059 - """ - A queue, useful for coordinating producer and consumer coroutines. + """A queue, useful for coordinating producer and consumer coroutines. If maxsize is less than or equal to zero, the queue size is infinite. If it is an integer greater than 0, then "await put()" will block when the @@ -58,32 +51,24 @@ class Queue(Generic[_T], _LoopBoundMixin): # noqa: Y059 def _put(self, item: _T) -> None: ... def _format(self) -> str: ... def qsize(self) -> int: - """ - Number of items in the queue. - """ + """Number of items in the queue.""" @property def maxsize(self) -> int: - """ - Number of items allowed in the queue. - """ + """Number of items allowed in the queue.""" def empty(self) -> bool: - """ - Return True if the queue is empty, False otherwise. - """ + """Return True if the queue is empty, False otherwise.""" def full(self) -> bool: - """ - Return True if there are maxsize items in the queue. + """Return True if there are maxsize items in the queue. Note: if the Queue was initialized with maxsize=0 (the default), then full() is never True. """ async def put(self, item: _T) -> None: - """ - Put an item into the queue. + """Put an item into the queue. Put an item into the queue. If the queue is full, wait until a free slot is available before adding item. @@ -92,8 +77,7 @@ class Queue(Generic[_T], _LoopBoundMixin): # noqa: Y059 """ def put_nowait(self, item: _T) -> None: - """ - Put an item into the queue without blocking. + """Put an item into the queue without blocking. If no free slot is immediately available, raise QueueFull. @@ -101,8 +85,7 @@ class Queue(Generic[_T], _LoopBoundMixin): # noqa: Y059 """ async def get(self) -> _T: - """ - Remove and return an item from the queue. + """Remove and return an item from the queue. If queue is empty, wait until an item is available. @@ -111,8 +94,7 @@ class Queue(Generic[_T], _LoopBoundMixin): # noqa: Y059 """ def get_nowait(self) -> _T: - """ - Remove and return an item from the queue. + """Remove and return an item from the queue. Return an item if one is immediately available, else raise QueueEmpty. @@ -121,8 +103,7 @@ class Queue(Generic[_T], _LoopBoundMixin): # noqa: Y059 """ async def join(self) -> None: - """ - Block until all items in the queue have been gotten and processed. + """Block until all items in the queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer calls task_done() to @@ -131,8 +112,7 @@ class Queue(Generic[_T], _LoopBoundMixin): # noqa: Y059 """ def task_done(self) -> None: - """ - Indicate that a formerly enqueued task is complete. + """Indicate that a formerly enqueued task is complete. Used by queue consumers. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing @@ -150,15 +130,13 @@ class Queue(Generic[_T], _LoopBoundMixin): # noqa: Y059 """ def __class_getitem__(cls, type: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ if sys.version_info >= (3, 13): def shutdown(self, immediate: bool = False) -> None: - """ - Shut-down the queue, making queue gets and puts raise QueueShutDown. + """Shut-down the queue, making queue gets and puts raise QueueShutDown. By default, gets will only raise once the queue is empty. Set 'immediate' to True to make gets raise immediately instead. @@ -169,13 +147,10 @@ class Queue(Generic[_T], _LoopBoundMixin): # noqa: Y059 """ class PriorityQueue(Queue[_T]): - """ - A subclass of Queue; retrieves entries in priority order (lowest first). + """A subclass of Queue; retrieves entries in priority order (lowest first). Entries are typically tuples of the form: (priority number, data). """ class LifoQueue(Queue[_T]): - """ - A subclass of Queue that retrieves most recently added entries first. - """ + """A subclass of Queue that retrieves most recently added entries first.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/runners.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/runners.pyi index 981c5e073b..f9e3956398 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/runners.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/runners.pyi @@ -17,8 +17,7 @@ _T = TypeVar("_T") if sys.version_info >= (3, 11): @final class Runner: - """ - A context manager that controls event loop life cycle. + """A context manager that controls event loop life cycle. The context manager always creates a new event loop, allows to run async functions inside it, @@ -46,26 +45,19 @@ if sys.version_info >= (3, 11): def __enter__(self) -> Self: ... def __exit__(self, exc_type: Unused, exc_val: Unused, exc_tb: Unused) -> None: ... def close(self) -> None: - """ - Shutdown and close event loop. - """ + """Shutdown and close event loop.""" def get_loop(self) -> AbstractEventLoop: - """ - Return embedded event loop. - """ + """Return embedded event loop.""" def run(self, coro: Coroutine[Any, Any, _T], *, context: Context | None = None) -> _T: - """ - Run code in the embedded event loop. - """ + """Run code in the embedded event loop.""" if sys.version_info >= (3, 12): def run( main: Coroutine[Any, Any, _T], *, debug: bool | None = ..., loop_factory: Callable[[], AbstractEventLoop] | None = ... ) -> _T: - """ - Execute the coroutine and return the result. + """Execute the coroutine and return the result. This function runs the passed coroutine, taking care of managing the asyncio event loop, finalizing asynchronous @@ -96,8 +88,7 @@ if sys.version_info >= (3, 12): else: def run(main: Coroutine[Any, Any, _T], *, debug: bool | None = None) -> _T: - """ - Execute the coroutine and return the result. + """Execute the coroutine and return the result. This function runs the passed coroutine, taking care of managing the asyncio event loop and finalizing asynchronous diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/selector_events.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/selector_events.pyi index 76888fd2cd..4aa3a074e3 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/selector_events.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/selector_events.pyi @@ -13,16 +13,14 @@ from . import base_events __all__ = ("BaseSelectorEventLoop",) class BaseSelectorEventLoop(base_events.BaseEventLoop): - """ - Selector event loop. + """Selector event loop. See events.EventLoop for API specification. """ def __init__(self, selector: selectors.BaseSelector | None = None) -> None: ... async def sock_recv(self, sock: socket, n: int) -> bytes: - """ - Receive data from the socket. + """Receive data from the socket. The return value is a bytes object representing the data received. The maximum amount of data to be received at once is specified by diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/sslproto.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/sslproto.pyi index 8c944d0da6..dbc65ab9f8 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/sslproto.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/sslproto.pyi @@ -36,8 +36,7 @@ else: if sys.version_info < (3, 11): class _SSLPipe: - """ - An SSL "Pipe". + """An SSL "Pipe". An SSL pipe allows you to communicate with an SSL/TLS protocol instance through memory buffers. It can be used to implement a security layer for an @@ -67,8 +66,7 @@ if sys.version_info < (3, 11): _handshake_cb: Callable[[BaseException | None], None] | None _shutdown_cb: Callable[[], None] | None def __init__(self, context: ssl.SSLContext, server_side: bool, server_hostname: str | None = None) -> None: - """ - The *context* argument specifies the ssl.SSLContext to use. + """The *context* argument specifies the ssl.SSLContext to use. The *server_side* argument indicates whether this is a server side or client side transport. @@ -80,36 +78,30 @@ if sys.version_info < (3, 11): @property def context(self) -> ssl.SSLContext: - """ - The SSL context passed to the constructor. - """ + """The SSL context passed to the constructor.""" @property def ssl_object(self) -> ssl.SSLObject | None: - """ - The internal ssl.SSLObject instance. + """The internal ssl.SSLObject instance. Return None if the pipe is not wrapped. """ @property def need_ssldata(self) -> bool: - """ - Whether more record level data is needed to complete a handshake + """Whether more record level data is needed to complete a handshake that is currently in progress. """ @property def wrapped(self) -> bool: - """ - Whether a security layer is currently in effect. + """Whether a security layer is currently in effect. Return False during handshake. """ def do_handshake(self, callback: Callable[[BaseException | None], object] | None = None) -> list[bytes]: - """ - Start the SSL handshake. + """Start the SSL handshake. Return a list of ssldata. A ssldata element is a list of buffers @@ -119,8 +111,7 @@ if sys.version_info < (3, 11): """ def shutdown(self, callback: Callable[[], object] | None = None) -> list[bytes]: - """ - Start the SSL shutdown sequence. + """Start the SSL shutdown sequence. Return a list of ssldata. A ssldata element is a list of buffers @@ -130,16 +121,14 @@ if sys.version_info < (3, 11): """ def feed_eof(self) -> None: - """ - Send a potentially "ragged" EOF. + """Send a potentially "ragged" EOF. This method will raise an SSL_ERROR_EOF exception if the EOF is unexpected. """ def feed_ssldata(self, data: bytes, only_handshake: bool = False) -> tuple[list[bytes], list[bytes]]: - """ - Feed SSL record level data into the pipe. + """Feed SSL record level data into the pipe. The data must be a bytes instance. It is OK to send an empty bytes instance. This can be used to get ssldata for a handshake initiated by @@ -155,8 +144,7 @@ if sys.version_info < (3, 11): """ def feed_appdata(self, data: bytes, offset: int = 0) -> tuple[list[bytes], int]: - """ - Feed plaintext data into the pipe. + """Feed plaintext data into the pipe. Return an (ssldata, offset) tuple. The ssldata element is a list of buffers containing record level data that needs to be sent to the @@ -182,36 +170,29 @@ class _SSLProtocolTransport(transports._FlowControlMixin, transports.Transport): _closed: bool def __init__(self, loop: events.AbstractEventLoop, ssl_protocol: SSLProtocol) -> None: ... def get_extra_info(self, name: str, default: Any | None = None) -> dict[str, Any]: - """ - Get optional transport information. - """ + """Get optional transport information.""" @property def _protocol_paused(self) -> bool: ... def write(self, data: bytes | bytearray | memoryview[Any]) -> None: # any memoryview format or shape - """ - Write some data bytes to the transport. + """Write some data bytes to the transport. This does not block; it buffers the data and arranges for it to be sent out asynchronously. """ def can_write_eof(self) -> Literal[False]: - """ - Return True if this transport supports write_eof(), False if not. - """ + """Return True if this transport supports write_eof(), False if not.""" if sys.version_info >= (3, 11): def get_write_buffer_limits(self) -> tuple[int, int]: - """ - Get the high and low watermarks for write flow control. + """Get the high and low watermarks for write flow control. Return a tuple (low, high) where low and high are positive number of bytes. """ def get_read_buffer_limits(self) -> tuple[int, int]: ... def set_read_buffer_limits(self, high: int | None = None, low: int | None = None) -> None: - """ - Set the high- and low-water limits for read flow control. + """Set the high- and low-water limits for read flow control. These two values control when to call the upstream transport's pause_reading() and resume_reading() methods. If specified, @@ -231,9 +212,7 @@ class _SSLProtocolTransport(transports._FlowControlMixin, transports.Transport): """ def get_read_buffer_size(self) -> int: - """ - Return the current size of the read buffer. - """ + """Return the current size of the read buffer.""" def __del__(self) -> None: ... @@ -243,8 +222,7 @@ else: _SSLProtocolBase: TypeAlias = protocols.Protocol class SSLProtocol(_SSLProtocolBase): - """ - SSL protocol. + """SSL protocol. Implementation of SSL on top of a socket using incoming and outgoing buffers which are ssl.MemoryBIO objects. @@ -302,8 +280,7 @@ class SSLProtocol(_SSLProtocolBase): def _set_app_protocol(self, app_protocol: protocols.BaseProtocol) -> None: ... def _wakeup_waiter(self, exc: BaseException | None = None) -> None: ... def connection_lost(self, exc: BaseException | None) -> None: - """ - Called when the low-level connection is lost or closed. + """Called when the low-level connection is lost or closed. The argument is an exception object or None (the latter meaning a regular EOF is received or the connection was @@ -311,8 +288,7 @@ class SSLProtocol(_SSLProtocolBase): """ def eof_received(self) -> None: - """ - Called when the other end of the low-level stream + """Called when the other end of the low-level stream is half-closed. If this returns a false value (including None), the transport diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/staggered.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/staggered.pyi index c9b9a7ed4a..2db77e069d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/staggered.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/staggered.pyi @@ -12,8 +12,7 @@ __all__ = ("staggered_race",) async def staggered_race( coro_fns: Iterable[Callable[[], Awaitable[Any]]], delay: float | None, *, loop: events.AbstractEventLoop | None = None ) -> tuple[Any, int | None, list[Exception | None]]: - """ - Run coroutines with staggered start times and take the first to finish. + """Run coroutines with staggered start times and take the first to finish. This method takes an iterable of coroutine functions. The first one is started immediately. From then on, whenever the immediately preceding one diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/streams.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/streams.pyi index d242b68cf7..880e9de2ef 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/streams.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/streams.pyi @@ -36,8 +36,7 @@ if sys.version_info >= (3, 10): ssl_handshake_timeout: float | None = ..., **kwds: Any, ) -> tuple[StreamReader, StreamWriter]: - """ - A wrapper for create_connection() returning a (reader, writer) pair. + """A wrapper for create_connection() returning a (reader, writer) pair. The reader returned is a StreamReader instance; the writer is a StreamWriter instance. @@ -64,8 +63,7 @@ if sys.version_info >= (3, 10): ssl_handshake_timeout: float | None = ..., **kwds: Any, ) -> Server: - """ - Start a socket server, call back for each client connected. + """Start a socket server, call back for each client connected. The first parameter, `client_connected_cb`, takes two parameters: client_reader, client_writer. client_reader is a StreamReader @@ -96,8 +94,7 @@ else: ssl_handshake_timeout: float | None = ..., **kwds: Any, ) -> tuple[StreamReader, StreamWriter]: - """ - A wrapper for create_connection() returning a (reader, writer) pair. + """A wrapper for create_connection() returning a (reader, writer) pair. The reader returned is a StreamReader instance; the writer is a StreamWriter instance. @@ -125,8 +122,7 @@ else: ssl_handshake_timeout: float | None = ..., **kwds: Any, ) -> Server: - """ - Start a socket server, call back for each client connected. + """Start a socket server, call back for each client connected. The first parameter, `client_connected_cb`, takes two parameters: client_reader, client_writer. client_reader is a StreamReader @@ -153,23 +149,17 @@ if sys.platform != "win32": async def open_unix_connection( path: StrPath | None = None, *, limit: int = 65536, **kwds: Any ) -> tuple[StreamReader, StreamWriter]: - """ - Similar to `open_connection` but works with UNIX Domain Sockets. - """ + """Similar to `open_connection` but works with UNIX Domain Sockets.""" async def start_unix_server( client_connected_cb: _ClientConnectedCallback, path: StrPath | None = None, *, limit: int = 65536, **kwds: Any ) -> Server: - """ - Similar to `start_server` but works with UNIX Domain Sockets. - """ + """Similar to `start_server` but works with UNIX Domain Sockets.""" else: async def open_unix_connection( path: StrPath | None = None, *, loop: events.AbstractEventLoop | None = None, limit: int = 65536, **kwds: Any ) -> tuple[StreamReader, StreamWriter]: - """ - Similar to `open_connection` but works with UNIX Domain Sockets. - """ + """Similar to `open_connection` but works with UNIX Domain Sockets.""" async def start_unix_server( client_connected_cb: _ClientConnectedCallback, @@ -179,13 +169,10 @@ if sys.platform != "win32": limit: int = 65536, **kwds: Any, ) -> Server: - """ - Similar to `start_server` but works with UNIX Domain Sockets. - """ + """Similar to `start_server` but works with UNIX Domain Sockets.""" class FlowControlMixin(protocols.Protocol): - """ - Reusable flow control logic for StreamWriter.drain(). + """Reusable flow control logic for StreamWriter.drain(). This implements the protocol methods pause_writing(), resume_writing() and connection_lost(). If the subclass overrides @@ -197,8 +184,7 @@ class FlowControlMixin(protocols.Protocol): def __init__(self, loop: events.AbstractEventLoop | None = None) -> None: ... class StreamReaderProtocol(FlowControlMixin, protocols.Protocol): - """ - Helper class to adapt between Protocol and StreamReader. + """Helper class to adapt between Protocol and StreamReader. (This is a helper class instead of making StreamReader itself a Protocol subclass, because the StreamReader has other potential @@ -215,8 +201,7 @@ class StreamReaderProtocol(FlowControlMixin, protocols.Protocol): def __del__(self) -> None: ... class StreamWriter: - """ - Wraps a Transport. + """Wraps a Transport. This exposes write(), writelines(), [can_]write_eof(), get_extra_info() and close(). It adds drain() which returns an @@ -243,8 +228,7 @@ class StreamWriter: async def wait_closed(self) -> None: ... def get_extra_info(self, name: str, default: Any = None) -> Any: ... async def drain(self) -> None: - """ - Flush the write buffer. + """Flush the write buffer. The intended use is to write @@ -260,16 +244,12 @@ class StreamWriter: ssl_handshake_timeout: float | None = None, ssl_shutdown_timeout: float | None = None, ) -> None: - """ - Upgrade an existing stream-based connection to TLS. - """ + """Upgrade an existing stream-based connection to TLS.""" elif sys.version_info >= (3, 11): async def start_tls( self, sslcontext: ssl.SSLContext, *, server_hostname: str | None = None, ssl_handshake_timeout: float | None = None ) -> None: - """ - Upgrade an existing stream-based connection to TLS. - """ + """Upgrade an existing stream-based connection to TLS.""" if sys.version_info >= (3, 13): def __del__(self, warnings: ModuleType = ...) -> None: ... elif sys.version_info >= (3, 11): @@ -282,14 +262,11 @@ class StreamReader: def set_transport(self, transport: transports.BaseTransport) -> None: ... def feed_eof(self) -> None: ... def at_eof(self) -> bool: - """ - Return True if the buffer is empty and 'feed_eof' was called. - """ + """Return True if the buffer is empty and 'feed_eof' was called.""" def feed_data(self, data: Iterable[SupportsIndex]) -> None: ... async def readline(self) -> bytes: - """ - Read chunk of data from the stream until newline (b' + """Read chunk of data from the stream until newline (b' ') is found. On success, return chunk that ends with newline. If only partial @@ -307,8 +284,7 @@ class StreamReader: """ if sys.version_info >= (3, 13): async def readuntil(self, separator: _ReaduntilBuffer | tuple[_ReaduntilBuffer, ...] = b"\n") -> bytes: - """ - Read data from the stream until ``separator`` is found. + """Read data from the stream until ``separator`` is found. On success, the data and separator will be removed from the internal buffer (consumed). Returned data will include the @@ -335,8 +311,7 @@ class StreamReader: """ else: async def readuntil(self, separator: _ReaduntilBuffer = b"\n") -> bytes: - """ - Read data from the stream until ``separator`` is found. + """Read data from the stream until ``separator`` is found. On success, the data and separator will be removed from the internal buffer (consumed). Returned data will include the @@ -363,8 +338,7 @@ class StreamReader: """ async def read(self, n: int = -1) -> bytes: - """ - Read up to `n` bytes from the stream. + """Read up to `n` bytes from the stream. If `n` is not provided or set to -1, read until EOF, then return all read bytes. @@ -386,8 +360,7 @@ class StreamReader: """ async def readexactly(self, n: int) -> bytes: - """ - Read exactly `n` bytes. + """Read exactly `n` bytes. Raise an IncompleteReadError if EOF is reached before `n` bytes can be read. The IncompleteReadError.partial attribute of the exception will diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/subprocess.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/subprocess.pyi index a7d1dc7531..c870fc1ef0 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/subprocess.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/subprocess.pyi @@ -13,9 +13,7 @@ STDOUT: int DEVNULL: int class SubprocessStreamProtocol(streams.FlowControlMixin, protocols.SubprocessProtocol): - """ - Like StreamReaderProtocol, but for a subprocess. - """ + """Like StreamReaderProtocol, but for a subprocess.""" stdin: streams.StreamWriter | None stdout: streams.StreamReader | None @@ -34,9 +32,7 @@ class Process: @property def returncode(self) -> int | None: ... async def wait(self) -> int: - """ - Wait until the process exit and return the process return code. - """ + """Wait until the process exit and return the process return code.""" def send_signal(self, signal: int) -> None: ... def terminate(self) -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/taskgroups.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/taskgroups.pyi index a5b41a8cdb..fe720da9ab 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/taskgroups.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/taskgroups.pyi @@ -17,8 +17,7 @@ else: _T = TypeVar("_T") class TaskGroup: - """ - Asynchronous context manager for managing groups of tasks. + """Asynchronous context manager for managing groups of tasks. Example use: @@ -40,8 +39,7 @@ class TaskGroup: async def __aenter__(self) -> Self: ... async def __aexit__(self, et: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... def create_task(self, coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None) -> Task[_T]: - """ - Create a new task in this group and return it. + """Create a new task in this group and return it. Similar to `asyncio.create_task`. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/tasks.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/tasks.pyi index b02670c409..616c1c201b 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/tasks.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/tasks.pyi @@ -94,8 +94,7 @@ if sys.version_info >= (3, 13): class _SyncAndAsyncIterator(Iterator[_T_co], AsyncIterator[_T_co], Protocol[_T_co]): ... def as_completed(fs: Iterable[_FutureLike[_T]], *, timeout: float | None = None) -> _SyncAndAsyncIterator[Future[_T]]: - """ - Create an iterator of awaitables or their results in completion order. + """Create an iterator of awaitables or their results in completion order. Run the supplied awaitables concurrently. The returned object can be iterated to obtain the results of the awaitables as they finish. @@ -143,8 +142,7 @@ if sys.version_info >= (3, 13): elif sys.version_info >= (3, 10): def as_completed(fs: Iterable[_FutureLike[_T]], *, timeout: float | None = None) -> Iterator[Future[_T]]: - """ - Return an iterator whose values are coroutines. + """Return an iterator whose values are coroutines. When waiting for the yielded coroutines you'll get the results (or exceptions!) of the original Futures (or coroutines), in the order @@ -166,8 +164,7 @@ else: def as_completed( fs: Iterable[_FutureLike[_T]], *, loop: AbstractEventLoop | None = None, timeout: float | None = None ) -> Iterator[Future[_T]]: - """ - Return an iterator whose values are coroutines. + """Return an iterator whose values are coroutines. When waiting for the yielded coroutines you'll get the results (or exceptions!) of the original Futures (or coroutines), in the order @@ -187,8 +184,7 @@ else: @overload def ensure_future(coro_or_future: _FT, *, loop: AbstractEventLoop | None = None) -> _FT: # type: ignore[overload-overlap] - """ - Wrap a coroutine or an awaitable in a future. + """Wrap a coroutine or an awaitable in a future. If the argument is a Future, it is returned directly. """ @@ -205,8 +201,7 @@ def ensure_future(coro_or_future: Awaitable[_T], *, loop: AbstractEventLoop | No if sys.version_info >= (3, 10): @overload def gather(coro_or_future1: _FutureLike[_T1], /, *, return_exceptions: Literal[False] = False) -> Future[tuple[_T1]]: # type: ignore[overload-overlap] - """ - Return a future aggregating results from the given coroutines/futures. + """Return a future aggregating results from the given coroutines/futures. Coroutines will be wrapped in a future and scheduled in the event loop. They will not necessarily be scheduled in the same order as @@ -351,8 +346,7 @@ else: def gather( # type: ignore[overload-overlap] coro_or_future1: _FutureLike[_T1], /, *, loop: AbstractEventLoop | None = None, return_exceptions: Literal[False] = False ) -> Future[tuple[_T1]]: - """ - Return a future aggregating results from the given coroutines/futures. + """Return a future aggregating results from the given coroutines/futures. Coroutines will be wrapped in a future and scheduled in the event loop. They will not necessarily be scheduled in the same order as @@ -504,16 +498,14 @@ else: # unlike some asyncio apis, This does strict runtime checking of actually being a coroutine, not of any future-like. def run_coroutine_threadsafe(coro: Coroutine[Any, Any, _T], loop: AbstractEventLoop) -> concurrent.futures.Future[_T]: - """ - Submit a coroutine object to a given event loop. + """Submit a coroutine object to a given event loop. Return a concurrent.futures.Future to access the result. """ if sys.version_info >= (3, 10): def shield(arg: _FutureLike[_T]) -> Future[_T]: - """ - Wait for a future, shielding it from cancellation. + """Wait for a future, shielding it from cancellation. The statement @@ -548,15 +540,12 @@ if sys.version_info >= (3, 10): @overload async def sleep(delay: float) -> None: - """ - Coroutine that completes after a given time (in seconds). - """ + """Coroutine that completes after a given time (in seconds).""" @overload async def sleep(delay: float, result: _T) -> _T: ... async def wait_for(fut: _FutureLike[_T], timeout: float | None) -> _T: - """ - Wait for the single Future or coroutine to complete, with timeout. + """Wait for the single Future or coroutine to complete, with timeout. Coroutine will be wrapped in Task. @@ -574,8 +563,7 @@ if sys.version_info >= (3, 10): else: def shield(arg: _FutureLike[_T], *, loop: AbstractEventLoop | None = None) -> Future[_T]: - """ - Wait for a future, shielding it from cancellation. + """Wait for a future, shielding it from cancellation. The statement @@ -603,15 +591,12 @@ else: @overload async def sleep(delay: float, *, loop: AbstractEventLoop | None = None) -> None: - """ - Coroutine that completes after a given time (in seconds). - """ + """Coroutine that completes after a given time (in seconds).""" @overload async def sleep(delay: float, result: _T, *, loop: AbstractEventLoop | None = None) -> _T: ... async def wait_for(fut: _FutureLike[_T], timeout: float | None, *, loop: AbstractEventLoop | None = None) -> _T: - """ - Wait for the single Future or coroutine to complete, with timeout. + """Wait for the single Future or coroutine to complete, with timeout. Coroutine will be wrapped in Task. @@ -629,8 +614,7 @@ if sys.version_info >= (3, 11): async def wait( fs: Iterable[_FT], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED" ) -> tuple[set[_FT], set[_FT]]: - """ - Wait for the Futures or Tasks given by fs to complete. + """Wait for the Futures or Tasks given by fs to complete. The fs iterable must not be empty. @@ -654,8 +638,7 @@ elif sys.version_info >= (3, 10): async def wait( # type: ignore[overload-overlap] fs: Iterable[_FT], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED" ) -> tuple[set[_FT], set[_FT]]: - """ - Wait for the Futures and coroutines given by fs to complete. + """Wait for the Futures and coroutines given by fs to complete. The fs iterable must not be empty. @@ -685,8 +668,7 @@ else: timeout: float | None = None, return_when: str = "ALL_COMPLETED", ) -> tuple[set[_FT], set[_FT]]: - """ - Wait for the Futures and coroutines given by fs to complete. + """Wait for the Futures and coroutines given by fs to complete. The fs iterable must not be empty. @@ -717,22 +699,18 @@ else: _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Coroutine[Any, Any, _T_co] def all_tasks(loop: AbstractEventLoop | None = None) -> set[Task[Any]]: - """ - Return a set of all tasks for the loop. - """ + """Return a set of all tasks for the loop.""" if sys.version_info >= (3, 11): def create_task(coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None) -> Task[_T]: - """ - Schedule the execution of a coroutine object in a spawn task. + """Schedule the execution of a coroutine object in a spawn task. Return a Task object. """ else: def create_task(coro: _CoroutineLike[_T], *, name: str | None = None) -> Task[_T]: - """ - Schedule the execution of a coroutine object in a spawn task. + """Schedule the execution of a coroutine object in a spawn task. Return a Task object. """ @@ -741,9 +719,7 @@ if sys.version_info >= (3, 12): from _asyncio import current_task as current_task else: def current_task(loop: AbstractEventLoop | None = None) -> Task[Any] | None: - """ - Return a currently executed task. - """ + """Return a currently executed task.""" if sys.version_info >= (3, 14): def eager_task_factory( @@ -790,8 +766,7 @@ if sys.version_info >= (3, 12): ) -> _TaskT_co: ... def create_eager_task_factory(custom_task_constructor: _CustomTaskConstructor[_TaskT_co]) -> _EagerTaskFactoryType[_TaskT_co]: - """ - Create a function suitable for use as a task factory on an event-loop. + """Create a function suitable for use as a task factory on an event-loop. Example usage: diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/threads.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/threads.pyi index 10af53f7b6..621ea14d79 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/threads.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/threads.pyi @@ -12,8 +12,7 @@ _P = ParamSpec("_P") _R = TypeVar("_R") async def to_thread(func: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> _R: - """ - Asynchronously run function *func* in a separate thread. + """Asynchronously run function *func* in a separate thread. Any *args and **kwargs supplied for this function are directly passed to *func*. Also, the current :class:`contextvars.Context` is propagated, diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/timeouts.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/timeouts.pyi index 7fb1c664da..06d2eac5b0 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/timeouts.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/timeouts.pyi @@ -7,15 +7,13 @@ __all__ = ("Timeout", "timeout", "timeout_at") @final class Timeout: - """ - Asynchronous context manager for cancelling overdue coroutines. + """Asynchronous context manager for cancelling overdue coroutines. Use `timeout()` or `timeout_at()` rather than instantiating this class directly. """ def __init__(self, when: float | None) -> None: - """ - Schedule a timeout that will trigger at a given loop time. + """Schedule a timeout that will trigger at a given loop time. - If `when` is `None`, the timeout will never trigger. - If `when < loop.time()`, the timeout will trigger on the next @@ -23,19 +21,13 @@ class Timeout: """ def when(self) -> float | None: - """ - Return the current deadline. - """ + """Return the current deadline.""" def reschedule(self, when: float | None) -> None: - """ - Reschedule the timeout. - """ + """Reschedule the timeout.""" def expired(self) -> bool: - """ - Is timeout expired during execution? - """ + """Is timeout expired during execution?""" async def __aenter__(self) -> Self: ... async def __aexit__( @@ -43,8 +35,7 @@ class Timeout: ) -> None: ... def timeout(delay: float | None) -> Timeout: - """ - Timeout async context manager. + """Timeout async context manager. Useful in cases when you want to apply timeout logic around block of code or in cases when asyncio.wait_for is not suitable. For example: @@ -61,8 +52,7 @@ def timeout(delay: float | None) -> Timeout: """ def timeout_at(when: float | None) -> Timeout: - """ - Schedule the timeout at absolute time. + """Schedule the timeout at absolute time. Like timeout() but argument gives absolute time in the same clock system as loop.time(). diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/tools.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/tools.pyi index f81dce7a0e..8ae065ce78 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/tools.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/tools.pyi @@ -34,9 +34,7 @@ class NodeType(Enum): TASK = 2 class CycleFoundException(Exception): - """ - Raised when there is a cycle when drawing the call tree. - """ + """Raised when there is a cycle when drawing the call tree.""" cycles: list[list[int]] id2name: dict[int, str] @@ -44,8 +42,7 @@ class CycleFoundException(Exception): def get_all_awaited_by(pid: SupportsIndex) -> list[_AwaitedInfo]: ... def build_async_tree(result: Iterable[_AwaitedInfo], task_emoji: str = "(T)", cor_emoji: str = "") -> list[list[str]]: - """ - Build a list of strings for pretty-print an async call tree. + """Build a list of strings for pretty-print an async call tree. The call tree is produced by `get_all_async_stacks()`, prefixing tasks with `task_emoji` and coroutine frames with `cor_emoji`. @@ -53,11 +50,7 @@ def build_async_tree(result: Iterable[_AwaitedInfo], task_emoji: str = "(T)", co def build_task_table(result: Iterable[_AwaitedInfo]) -> list[list[int | str]]: ... def display_awaited_by_tasks_table(pid: SupportsIndex) -> None: - """ - Build and print a table of all pending tasks under `pid`. - """ + """Build and print a table of all pending tasks under `pid`.""" def display_awaited_by_tasks_tree(pid: SupportsIndex) -> None: - """ - Build and print a tree of all pending tasks under `pid`. - """ + """Build and print a tree of all pending tasks under `pid`.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/transports.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/transports.pyi index 21792fb617..927043f8e0 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/transports.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/transports.pyi @@ -12,24 +12,17 @@ from typing import Any __all__ = ("BaseTransport", "ReadTransport", "WriteTransport", "Transport", "DatagramTransport", "SubprocessTransport") class BaseTransport: - """ - Base class for transports. - """ + """Base class for transports.""" def __init__(self, extra: Mapping[str, Any] | None = None) -> None: ... def get_extra_info(self, name: str, default: Any = None) -> Any: - """ - Get optional transport information. - """ + """Get optional transport information.""" def is_closing(self) -> bool: - """ - Return True if the transport is closing or closed. - """ + """Return True if the transport is closing or closed.""" def close(self) -> None: - """ - Close the transport. + """Close the transport. Buffered data will be flushed asynchronously. No more data will be received. After all buffered data is flushed, the @@ -38,49 +31,36 @@ class BaseTransport: """ def set_protocol(self, protocol: BaseProtocol) -> None: - """ - Set a new protocol. - """ + """Set a new protocol.""" def get_protocol(self) -> BaseProtocol: - """ - Return the current protocol. - """ + """Return the current protocol.""" class ReadTransport(BaseTransport): - """ - Interface for read-only transports. - """ + """Interface for read-only transports.""" def is_reading(self) -> bool: - """ - Return True if the transport is receiving. - """ + """Return True if the transport is receiving.""" def pause_reading(self) -> None: - """ - Pause the receiving end. + """Pause the receiving end. No data will be passed to the protocol's data_received() method until resume_reading() is called. """ def resume_reading(self) -> None: - """ - Resume the receiving end. + """Resume the receiving end. Data received will once again be passed to the protocol's data_received() method. """ class WriteTransport(BaseTransport): - """ - Interface for write-only transports. - """ + """Interface for write-only transports.""" def set_write_buffer_limits(self, high: int | None = None, low: int | None = None) -> None: - """ - Set the high- and low-water limits for write flow control. + """Set the high- and low-water limits for write flow control. These two values control when to call the protocol's pause_writing() and resume_writing() methods. If specified, @@ -100,36 +80,30 @@ class WriteTransport(BaseTransport): """ def get_write_buffer_size(self) -> int: - """ - Return the current size of the write buffer. - """ + """Return the current size of the write buffer.""" def get_write_buffer_limits(self) -> tuple[int, int]: - """ - Get the high and low watermarks for write flow control. + """Get the high and low watermarks for write flow control. Return a tuple (low, high) where low and high are positive number of bytes. """ def write(self, data: bytes | bytearray | memoryview[Any]) -> None: # any memoryview format or shape - """ - Write some data bytes to the transport. + """Write some data bytes to the transport. This does not block; it buffers the data and arranges for it to be sent out asynchronously. """ def writelines(self, list_of_data: Iterable[bytes | bytearray | memoryview[Any]]) -> None: # any memoryview format or shape - """ - Write a list (or any iterable) of data bytes to the transport. + """Write a list (or any iterable) of data bytes to the transport. The default implementation concatenates the arguments and calls write() on the result. """ def write_eof(self) -> None: - """ - Close the write end after flushing buffered data. + """Close the write end after flushing buffered data. (This is like typing ^D into a UNIX program reading from stdin.) @@ -137,13 +111,10 @@ class WriteTransport(BaseTransport): """ def can_write_eof(self) -> bool: - """ - Return True if this transport supports write_eof(), False if not. - """ + """Return True if this transport supports write_eof(), False if not.""" def abort(self) -> None: - """ - Close the transport immediately. + """Close the transport immediately. Buffered data will be lost. No more data will be received. The protocol's connection_lost() method will (eventually) be @@ -151,8 +122,7 @@ class WriteTransport(BaseTransport): """ class Transport(ReadTransport, WriteTransport): - """ - Interface representing a bidirectional transport. + """Interface representing a bidirectional transport. There may be several implementations, but typically, the user does not implement new transports; rather, the platform provides some @@ -173,13 +143,10 @@ class Transport(ReadTransport, WriteTransport): """ class DatagramTransport(BaseTransport): - """ - Interface for datagram (UDP) transports. - """ + """Interface for datagram (UDP) transports.""" def sendto(self, data: bytes | bytearray | memoryview, addr: _Address | None = None) -> None: - """ - Send data to the transport. + """Send data to the transport. This does not block; it buffers the data and arranges for it to be sent out asynchronously. @@ -190,8 +157,7 @@ class DatagramTransport(BaseTransport): """ def abort(self) -> None: - """ - Close the transport immediately. + """Close the transport immediately. Buffered data will be lost. No more data will be received. The protocol's connection_lost() method will (eventually) be @@ -200,34 +166,27 @@ class DatagramTransport(BaseTransport): class SubprocessTransport(BaseTransport): def get_pid(self) -> int: - """ - Get subprocess id. - """ + """Get subprocess id.""" def get_returncode(self) -> int | None: - """ - Get subprocess returncode. + """Get subprocess returncode. See also http://docs.python.org/3/library/subprocess#subprocess.Popen.returncode """ def get_pipe_transport(self, fd: int) -> BaseTransport | None: - """ - Get transport for pipe with number fd. - """ + """Get transport for pipe with number fd.""" def send_signal(self, signal: int) -> None: - """ - Send signal to subprocess. + """Send signal to subprocess. See also: docs.python.org/3/library/subprocess#subprocess.Popen.send_signal """ def terminate(self) -> None: - """ - Stop the subprocess. + """Stop the subprocess. Alias for close() method. @@ -240,8 +199,7 @@ class SubprocessTransport(BaseTransport): """ def kill(self) -> None: - """ - Kill the subprocess. + """Kill the subprocess. On Posix OSs the function sends SIGKILL to the subprocess. On Windows kill() is an alias for terminate(). @@ -251,8 +209,7 @@ class SubprocessTransport(BaseTransport): """ class _FlowControlMixin(Transport): - """ - All the logic for (write) flow control in a mix-in base class. + """All the logic for (write) flow control in a mix-in base class. The subclass must implement get_write_buffer_size(). It must call _maybe_pause_protocol() whenever the write buffer size increases, diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/trsock.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/trsock.pyi index a9b97b59a6..0832062a9a 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/trsock.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/trsock.pyi @@ -14,8 +14,7 @@ _WriteBuffer: TypeAlias = bytearray | memoryview _CMSG: TypeAlias = tuple[int, int, bytes] class TransportSocket: - """ - A socket-like wrapper for exposing real transport sockets. + """A socket-like wrapper for exposing real transport sockets. These objects can be safely returned by APIs like `transport.get_extra_info('socket')`. All potentially disruptive diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/unix_events.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/unix_events.pyi index 51e1ab0c07..2a505c87de 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/unix_events.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/unix_events.pyi @@ -54,8 +54,7 @@ if sys.version_info < (3, 14): if sys.version_info >= (3, 12): @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") class AbstractChildWatcher: - """ - Abstract base class for monitoring child processes. + """Abstract base class for monitoring child processes. Objects derived from this class monitor a collection of subprocesses and report their termination or interruption by a signal. @@ -81,8 +80,7 @@ if sys.version_info < (3, 14): def add_child_handler( self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] ) -> None: - """ - Register a new child handler. + """Register a new child handler. Arrange for callback(pid, returncode, *args) to be called when process 'pid' terminates. Specifying another callback for the same @@ -93,8 +91,7 @@ if sys.version_info < (3, 14): @abstractmethod def remove_child_handler(self, pid: int) -> bool: - """ - Removes the handler for process 'pid'. + """Removes the handler for process 'pid'. The function returns True if the handler was successfully removed, False if there was nothing to remove. @@ -102,8 +99,7 @@ if sys.version_info < (3, 14): @abstractmethod def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: - """ - Attach the watcher to an event loop. + """Attach the watcher to an event loop. If the watcher was previously attached to an event loop, then it is first detached before attaching to the new loop. @@ -113,16 +109,14 @@ if sys.version_info < (3, 14): @abstractmethod def close(self) -> None: - """ - Close the watcher. + """Close the watcher. This must be called to make sure that any underlying resource is freed. """ @abstractmethod def __enter__(self) -> Self: - """ - Enter the watcher's context and allow starting new processes + """Enter the watcher's context and allow starting new processes This function must return self """ @@ -131,14 +125,11 @@ if sys.version_info < (3, 14): def __exit__( self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None ) -> None: - """ - Exit the watcher's context - """ + """Exit the watcher's context""" @abstractmethod def is_active(self) -> bool: - """ - Return ``True`` if the watcher is active and is used by the event loop. + """Return ``True`` if the watcher is active and is used by the event loop. Return True if the watcher is installed and ready to handle process exit notifications. @@ -146,8 +137,7 @@ if sys.version_info < (3, 14): else: class AbstractChildWatcher: - """ - Abstract base class for monitoring child processes. + """Abstract base class for monitoring child processes. Objects derived from this class monitor a collection of subprocesses and report their termination or interruption by a signal. @@ -173,8 +163,7 @@ if sys.version_info < (3, 14): def add_child_handler( self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] ) -> None: - """ - Register a new child handler. + """Register a new child handler. Arrange for callback(pid, returncode, *args) to be called when process 'pid' terminates. Specifying another callback for the same @@ -185,8 +174,7 @@ if sys.version_info < (3, 14): @abstractmethod def remove_child_handler(self, pid: int) -> bool: - """ - Removes the handler for process 'pid'. + """Removes the handler for process 'pid'. The function returns True if the handler was successfully removed, False if there was nothing to remove. @@ -194,8 +182,7 @@ if sys.version_info < (3, 14): @abstractmethod def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: - """ - Attach the watcher to an event loop. + """Attach the watcher to an event loop. If the watcher was previously attached to an event loop, then it is first detached before attaching to the new loop. @@ -205,16 +192,14 @@ if sys.version_info < (3, 14): @abstractmethod def close(self) -> None: - """ - Close the watcher. + """Close the watcher. This must be called to make sure that any underlying resource is freed. """ @abstractmethod def __enter__(self) -> Self: - """ - Enter the watcher's context and allow starting new processes + """Enter the watcher's context and allow starting new processes This function must return self """ @@ -223,14 +208,11 @@ if sys.version_info < (3, 14): def __exit__( self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None ) -> None: - """ - Exit the watcher's context - """ + """Exit the watcher's context""" @abstractmethod def is_active(self) -> bool: - """ - Return ``True`` if the watcher is active and is used by the event loop. + """Return ``True`` if the watcher is active and is used by the event loop. Return True if the watcher is installed and ready to handle process exit notifications. @@ -248,8 +230,7 @@ if sys.platform != "win32": @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") class SafeChildWatcher(BaseChildWatcher): - """ - 'Safe' child watcher implementation. + """'Safe' child watcher implementation. This implementation avoids disrupting other code spawning processes by polling explicitly each process in the SIGCHLD handler instead of calling @@ -270,8 +251,7 @@ if sys.platform != "win32": @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") class FastChildWatcher(BaseChildWatcher): - """ - 'Fast' child watcher implementation. + """'Fast' child watcher implementation. This implementation reaps every terminated processes by calling os.waitpid(-1) directly, possibly breaking other code spawning processes @@ -299,8 +279,7 @@ if sys.platform != "win32": def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... class SafeChildWatcher(BaseChildWatcher): - """ - 'Safe' child watcher implementation. + """'Safe' child watcher implementation. This implementation avoids disrupting other code spawning processes by polling explicitly each process in the SIGCHLD handler instead of calling @@ -320,8 +299,7 @@ if sys.platform != "win32": def remove_child_handler(self, pid: int) -> bool: ... class FastChildWatcher(BaseChildWatcher): - """ - 'Fast' child watcher implementation. + """'Fast' child watcher implementation. This implementation reaps every terminated processes by calling os.waitpid(-1) directly, possibly breaking other code spawning processes @@ -341,8 +319,7 @@ if sys.platform != "win32": def remove_child_handler(self, pid: int) -> bool: ... class _UnixSelectorEventLoop(BaseSelectorEventLoop): - """ - Unix event loop. + """Unix event loop. Adds signal handling and UNIX Domain Socket support to SelectorEventLoop. """ @@ -364,42 +341,32 @@ if sys.platform != "win32": if sys.version_info >= (3, 14): class _UnixDefaultEventLoopPolicy(events._BaseDefaultEventLoopPolicy): - """ - UNIX event loop policy - """ + """UNIX event loop policy""" else: class _UnixDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy): - """ - UNIX event loop policy with a watcher for child processes. - """ + """UNIX event loop policy with a watcher for child processes.""" if sys.version_info >= (3, 12): @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") def get_child_watcher(self) -> AbstractChildWatcher: - """ - Get the watcher for child processes. + """Get the watcher for child processes. If not yet set, a ThreadedChildWatcher object is automatically created. """ @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: - """ - Set the watcher for child processes. - """ + """Set the watcher for child processes.""" else: def get_child_watcher(self) -> AbstractChildWatcher: - """ - Get the watcher for child processes. + """Get the watcher for child processes. If not yet set, a ThreadedChildWatcher object is automatically created. """ def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: - """ - Set the watcher for child processes. - """ + """Set the watcher for child processes.""" SelectorEventLoop = _UnixSelectorEventLoop @@ -415,8 +382,7 @@ if sys.platform != "win32": if sys.version_info >= (3, 12): @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") class MultiLoopChildWatcher(AbstractChildWatcher): - """ - A watcher that doesn't require running loop in the main thread. + """A watcher that doesn't require running loop in the main thread. This implementation registers a SIGCHLD signal handler on instantiation (which may conflict with other code that @@ -441,8 +407,7 @@ if sys.platform != "win32": else: class MultiLoopChildWatcher(AbstractChildWatcher): - """ - A watcher that doesn't require running loop in the main thread. + """A watcher that doesn't require running loop in the main thread. This implementation registers a SIGCHLD signal handler on instantiation (which may conflict with other code that @@ -467,8 +432,7 @@ if sys.platform != "win32": if sys.version_info < (3, 14): class ThreadedChildWatcher(AbstractChildWatcher): - """ - Threaded child watcher implementation. + """Threaded child watcher implementation. The watcher uses a thread per process for waiting for the process finish. @@ -494,8 +458,7 @@ if sys.platform != "win32": def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... class PidfdChildWatcher(AbstractChildWatcher): - """ - Child watcher implementation using Linux's pid file descriptors. + """Child watcher implementation using Linux's pid file descriptors. This child watcher polls process file descriptors (pidfds) to await child process termination. In some respects, PidfdChildWatcher is a "Goldilocks" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/windows_events.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/windows_events.pyi index b454aca1f2..181931bb97 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/windows_events.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/windows_events.pyi @@ -1,3 +1,7 @@ +""" +Selector and proactor event loops for Windows. +""" + import socket import sys from _typeshed import Incomplete, ReadableBuffer, WriteableBuffer @@ -47,14 +51,22 @@ if sys.platform == "win32": CONNECT_PIPE_MAX_DELAY: float class PipeServer: + """Class representing a pipe server. + + This is much like a bound, listening socket. + """ + def __init__(self, address: str) -> None: ... def __del__(self) -> None: ... def closed(self) -> bool: ... def close(self) -> None: ... - class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop): ... + class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop): + """Windows version of selector event loop.""" class ProactorEventLoop(proactor_events.BaseProactorEventLoop): + """Windows version of proactor event loop using IOCP.""" + def __init__(self, proactor: IocpProactor | None = None) -> None: ... async def create_pipe_connection( self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str @@ -64,6 +76,8 @@ if sys.platform == "win32": ) -> list[PipeServer]: ... class IocpProactor: + """Proactor implementation using IOCP.""" + def __init__(self, concurrency: int = 0xFFFFFFFF) -> None: ... def __del__(self) -> None: ... def set_loop(self, loop: events.AbstractEventLoop) -> None: ... @@ -86,7 +100,13 @@ if sys.platform == "win32": def sendfile(self, sock: socket.socket, file: IO[bytes], offset: int, count: int) -> futures.Future[Any]: ... def accept_pipe(self, pipe: socket.socket) -> futures.Future[Any]: ... async def connect_pipe(self, address: str) -> windows_utils.PipeHandle: ... - def wait_for_handle(self, handle: windows_utils.PipeHandle, timeout: int | None = None) -> bool: ... + def wait_for_handle(self, handle: windows_utils.PipeHandle, timeout: int | None = None) -> bool: + """Wait for a handle. + + Return a Future object. The result of the future is True if the wait + completed, or False if the wait did not complete (on timeout). + """ + def close(self) -> None: ... if sys.version_info >= (3, 11): def recvfrom_into( @@ -105,13 +125,19 @@ 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) -> NoReturn: + """Get the watcher for child processes.""" + + def set_child_watcher(self, watcher: Any) -> NoReturn: + """Set the watcher for child processes.""" 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) -> NoReturn: + """Get the watcher for child processes.""" + + def set_child_watcher(self, watcher: Any) -> NoReturn: + """Set the watcher for child processes.""" if sys.version_info >= (3, 14): _DefaultEventLoopPolicy = _WindowsProactorEventLoopPolicy diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/windows_utils.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/windows_utils.pyi index 4fa0145323..12553c2ce0 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/windows_utils.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/asyncio/windows_utils.pyi @@ -1,3 +1,7 @@ +""" +Various Windows specific bits and pieces. +""" + import subprocess import sys from collections.abc import Callable @@ -11,9 +15,15 @@ if sys.platform == "win32": BUFSIZE: Final = 8192 PIPE = subprocess.PIPE STDOUT = subprocess.STDOUT - def pipe(*, duplex: bool = False, overlapped: tuple[bool, bool] = (True, True), bufsize: int = 8192) -> tuple[int, int]: ... + def pipe(*, duplex: bool = False, overlapped: tuple[bool, bool] = (True, True), bufsize: int = 8192) -> tuple[int, int]: + """Like os.pipe() but with overlapped support and using handles not fds.""" class PipeHandle: + """Wrapper for an overlapped pipe handle which is vaguely file-object like. + + The IOCP event loop can use these instead of socket objects. + """ + def __init__(self, handle: int) -> None: ... def __del__(self) -> None: ... def __enter__(self) -> Self: ... @@ -24,6 +34,11 @@ if sys.platform == "win32": def close(self, *, CloseHandle: Callable[[int], object] = ...) -> None: ... class Popen(subprocess.Popen[AnyStr]): + """Replacement for subprocess.Popen using overlapped pipe handles. + + The stdin, stdout, stderr are None or instances of PipeHandle. + """ + stdin: PipeHandle | None # type: ignore[assignment] stdout: PipeHandle | None # type: ignore[assignment] stderr: PipeHandle | None # type: ignore[assignment] diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/atexit.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/atexit.pyi index ca325edf40..7dc5eb395f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/atexit.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/atexit.pyi @@ -13,25 +13,19 @@ _T = TypeVar("_T") _P = ParamSpec("_P") def _clear() -> None: - """ - Clear the list of previously registered exit functions. - """ + """Clear the list of previously registered exit functions.""" def _ncallbacks() -> int: - """ - Return the number of registered exit functions. - """ + """Return the number of registered exit functions.""" def _run_exitfuncs() -> None: - """ - Run all registered exit functions. + """Run all registered exit functions. If a callback raises an exception, it is logged with sys.unraisablehook. """ def register(func: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Callable[_P, _T]: - """ - Register a function to be executed upon normal program termination + """Register a function to be executed upon normal program termination func - function to be called at exit args - optional arguments to pass to func @@ -41,8 +35,7 @@ def register(func: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> """ def unregister(func: Callable[..., object], /) -> None: - """ - Unregister an exit function which was previously registered using + """Unregister an exit function which was previously registered using atexit.register func - function to be unregistered diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/audioop.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/audioop.pyi index 3be2482263..fdfbc7d2cd 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/audioop.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/audioop.pyi @@ -6,104 +6,64 @@ _RatecvState: TypeAlias = tuple[int, tuple[tuple[int, int], ...]] class error(Exception): ... def add(fragment1: Buffer, fragment2: Buffer, width: int, /) -> bytes: - """ - Return a fragment which is the addition of the two samples passed as parameters. - """ + """Return a fragment which is the addition of the two samples passed as parameters.""" def adpcm2lin(fragment: Buffer, width: int, state: _AdpcmState | None, /) -> tuple[bytes, _AdpcmState]: - """ - Decode an Intel/DVI ADPCM coded fragment to a linear fragment. - """ + """Decode an Intel/DVI ADPCM coded fragment to a linear fragment.""" def alaw2lin(fragment: Buffer, width: int, /) -> bytes: - """ - Convert sound fragments in a-LAW encoding to linearly encoded sound fragments. - """ + """Convert sound fragments in a-LAW encoding to linearly encoded sound fragments.""" def avg(fragment: Buffer, width: int, /) -> int: - """ - Return the average over all samples in the fragment. - """ + """Return the average over all samples in the fragment.""" def avgpp(fragment: Buffer, width: int, /) -> int: - """ - Return the average peak-peak value over all samples in the fragment. - """ + """Return the average peak-peak value over all samples in the fragment.""" def bias(fragment: Buffer, width: int, bias: int, /) -> bytes: - """ - Return a fragment that is the original fragment with a bias added to each sample. - """ + """Return a fragment that is the original fragment with a bias added to each sample.""" def byteswap(fragment: Buffer, width: int, /) -> bytes: - """ - Convert big-endian samples to little-endian and vice versa. - """ + """Convert big-endian samples to little-endian and vice versa.""" def cross(fragment: Buffer, width: int, /) -> int: - """ - Return the number of zero crossings in the fragment passed as an argument. - """ + """Return the number of zero crossings in the fragment passed as an argument.""" def findfactor(fragment: Buffer, reference: Buffer, /) -> float: - """ - Return a factor F such that rms(add(fragment, mul(reference, -F))) is minimal. - """ + """Return a factor F such that rms(add(fragment, mul(reference, -F))) is minimal.""" def findfit(fragment: Buffer, reference: Buffer, /) -> tuple[int, float]: - """ - Try to match reference as well as possible to a portion of fragment. - """ + """Try to match reference as well as possible to a portion of fragment.""" def findmax(fragment: Buffer, length: int, /) -> int: - """ - Search fragment for a slice of specified number of samples with maximum energy. - """ + """Search fragment for a slice of specified number of samples with maximum energy.""" def getsample(fragment: Buffer, width: int, index: int, /) -> int: - """ - Return the value of sample index from the fragment. - """ + """Return the value of sample index from the fragment.""" def lin2adpcm(fragment: Buffer, width: int, state: _AdpcmState | None, /) -> tuple[bytes, _AdpcmState]: - """ - Convert samples to 4 bit Intel/DVI ADPCM encoding. - """ + """Convert samples to 4 bit Intel/DVI ADPCM encoding.""" def lin2alaw(fragment: Buffer, width: int, /) -> bytes: - """ - Convert samples in the audio fragment to a-LAW encoding. - """ + """Convert samples in the audio fragment to a-LAW encoding.""" def lin2lin(fragment: Buffer, width: int, newwidth: int, /) -> bytes: - """ - Convert samples between 1-, 2-, 3- and 4-byte formats. - """ + """Convert samples between 1-, 2-, 3- and 4-byte formats.""" def lin2ulaw(fragment: Buffer, width: int, /) -> bytes: - """ - Convert samples in the audio fragment to u-LAW encoding. - """ + """Convert samples in the audio fragment to u-LAW encoding.""" def max(fragment: Buffer, width: int, /) -> int: - """ - Return the maximum of the absolute value of all samples in a fragment. - """ + """Return the maximum of the absolute value of all samples in a fragment.""" def maxpp(fragment: Buffer, width: int, /) -> int: - """ - Return the maximum peak-peak value in the sound fragment. - """ + """Return the maximum peak-peak value in the sound fragment.""" def minmax(fragment: Buffer, width: int, /) -> tuple[int, int]: - """ - Return the minimum and maximum values of all samples in the sound fragment. - """ + """Return the minimum and maximum values of all samples in the sound fragment.""" def mul(fragment: Buffer, width: int, factor: float, /) -> bytes: - """ - Return a fragment that has all samples in the original fragment multiplied by the floating-point value factor. - """ + """Return a fragment that has all samples in the original fragment multiplied by the floating-point value factor.""" def ratecv( fragment: Buffer, @@ -116,31 +76,19 @@ def ratecv( weightB: int = 0, /, ) -> tuple[bytes, _RatecvState]: - """ - Convert the frame rate of the input fragment. - """ + """Convert the frame rate of the input fragment.""" def reverse(fragment: Buffer, width: int, /) -> bytes: - """ - Reverse the samples in a fragment and returns the modified fragment. - """ + """Reverse the samples in a fragment and returns the modified fragment.""" def rms(fragment: Buffer, width: int, /) -> int: - """ - Return the root-mean-square of the fragment, i.e. sqrt(sum(S_i^2)/n). - """ + """Return the root-mean-square of the fragment, i.e. sqrt(sum(S_i^2)/n).""" def tomono(fragment: Buffer, width: int, lfactor: float, rfactor: float, /) -> bytes: - """ - Convert a stereo fragment to a mono fragment. - """ + """Convert a stereo fragment to a mono fragment.""" def tostereo(fragment: Buffer, width: int, lfactor: float, rfactor: float, /) -> bytes: - """ - Generate a stereo fragment from a mono fragment. - """ + """Generate a stereo fragment from a mono fragment.""" def ulaw2lin(fragment: Buffer, width: int, /) -> bytes: - """ - Convert sound fragments in u-LAW encoding to linearly encoded sound fragments. - """ + """Convert sound fragments in u-LAW encoding to linearly encoded sound fragments.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/base64.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/base64.pyi index e5c5b45496..774c6e3f90 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/base64.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/base64.pyi @@ -33,8 +33,7 @@ if sys.version_info >= (3, 13): __all__ += ["z85decode", "z85encode"] def b64encode(s: ReadableBuffer, altchars: ReadableBuffer | None = None) -> bytes: - """ - Encode the bytes-like object s using Base64 and return a bytes object. + """Encode the bytes-like object s using Base64 and return a bytes object. Optional altchars should be a byte string of length 2 which specifies an alternative alphabet for the '+' and '/' characters. This allows an @@ -42,8 +41,7 @@ def b64encode(s: ReadableBuffer, altchars: ReadableBuffer | None = None) -> byte """ def b64decode(s: str | ReadableBuffer, altchars: str | ReadableBuffer | None = None, validate: bool = False) -> bytes: - """ - Decode the Base64 encoded bytes-like object or ASCII string s. + """Decode the Base64 encoded bytes-like object or ASCII string s. Optional altchars must be a bytes-like object or ASCII string of length 2 which specifies the alternative alphabet used instead of the '+' and '/' @@ -62,15 +60,13 @@ def b64decode(s: str | ReadableBuffer, altchars: str | ReadableBuffer | None = N """ def standard_b64encode(s: ReadableBuffer) -> bytes: - """ - Encode bytes-like object s using the standard Base64 alphabet. + """Encode bytes-like object s using the standard Base64 alphabet. The result is returned as a bytes object. """ def standard_b64decode(s: str | ReadableBuffer) -> bytes: - """ - Decode bytes encoded with the standard Base64 alphabet. + """Decode bytes encoded with the standard Base64 alphabet. Argument s is a bytes-like object or ASCII string to decode. The result is returned as a bytes object. A binascii.Error is raised if the input @@ -79,8 +75,7 @@ def standard_b64decode(s: str | ReadableBuffer) -> bytes: """ def urlsafe_b64encode(s: ReadableBuffer) -> bytes: - """ - Encode bytes using the URL- and filesystem-safe Base64 alphabet. + """Encode bytes using the URL- and filesystem-safe Base64 alphabet. Argument s is a bytes-like object to encode. The result is returned as a bytes object. The alphabet uses '-' instead of '+' and '_' instead of @@ -88,8 +83,7 @@ def urlsafe_b64encode(s: ReadableBuffer) -> bytes: """ def urlsafe_b64decode(s: str | ReadableBuffer) -> bytes: - """ - Decode bytes using the URL- and filesystem-safe Base64 alphabet. + """Decode bytes using the URL- and filesystem-safe Base64 alphabet. Argument s is a bytes-like object or ASCII string to decode. The result is returned as a bytes object. A binascii.Error is raised if the input @@ -101,13 +95,10 @@ def urlsafe_b64decode(s: str | ReadableBuffer) -> bytes: """ def b32encode(s: ReadableBuffer) -> bytes: - """ - Encode the bytes-like objects using base32 and return a bytes object. - """ + """Encode the bytes-like objects using base32 and return a bytes object.""" def b32decode(s: str | ReadableBuffer, casefold: bool = False, map01: str | ReadableBuffer | None = None) -> bytes: - """ - Decode the base32 encoded bytes-like object or ASCII string s. + """Decode the base32 encoded bytes-like object or ASCII string s. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. @@ -126,13 +117,10 @@ def b32decode(s: str | ReadableBuffer, casefold: bool = False, map01: str | Read """ def b16encode(s: ReadableBuffer) -> bytes: - """ - Encode the bytes-like object s using Base16 and return a bytes object. - """ + """Encode the bytes-like object s using Base16 and return a bytes object.""" def b16decode(s: str | ReadableBuffer, casefold: bool = False) -> bytes: - """ - Decode the Base16 encoded bytes-like object or ASCII string s. + """Decode the Base16 encoded bytes-like object or ASCII string s. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. @@ -144,13 +132,10 @@ def b16decode(s: str | ReadableBuffer, casefold: bool = False) -> bytes: if sys.version_info >= (3, 10): def b32hexencode(s: ReadableBuffer) -> bytes: - """ - Encode the bytes-like objects using base32hex and return a bytes object. - """ + """Encode the bytes-like objects using base32hex and return a bytes object.""" def b32hexdecode(s: str | ReadableBuffer, casefold: bool = False) -> bytes: - """ - Decode the base32hex encoded bytes-like object or ASCII string s. + """Decode the base32hex encoded bytes-like object or ASCII string s. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. @@ -161,8 +146,7 @@ if sys.version_info >= (3, 10): """ def a85encode(b: ReadableBuffer, *, foldspaces: bool = False, wrapcol: int = 0, pad: bool = False, adobe: bool = False) -> bytes: - """ - Encode bytes-like object b using Ascii85 and return a bytes object. + """Encode bytes-like object b using Ascii85 and return a bytes object. foldspaces is an optional flag that uses the special short sequence 'y' instead of 4 consecutive spaces (ASCII 0x20) as supported by 'btoa'. This @@ -182,8 +166,7 @@ def a85encode(b: ReadableBuffer, *, foldspaces: bool = False, wrapcol: int = 0, def a85decode( b: str | ReadableBuffer, *, foldspaces: bool = False, adobe: bool = False, ignorechars: bytearray | bytes = b" \t\n\r\x0b" ) -> bytes: - """ - Decode the Ascii85 encoded bytes-like object or ASCII string b. + """Decode the Ascii85 encoded bytes-like object or ASCII string b. foldspaces is a flag that specifies whether the 'y' short sequence should be accepted as shorthand for 4 consecutive spaces (ASCII 0x20). This feature is @@ -200,50 +183,38 @@ def a85decode( """ def b85encode(b: ReadableBuffer, pad: bool = False) -> bytes: - """ - Encode bytes-like object b in base85 format and return a bytes object. + """Encode bytes-like object b in base85 format and return a bytes object. If pad is true, the input is padded with b'\\0' so its length is a multiple of 4 bytes before encoding. """ def b85decode(b: str | ReadableBuffer) -> bytes: - """ - Decode the base85-encoded bytes-like object or ASCII string b + """Decode the base85-encoded bytes-like object or ASCII string b The result is returned as a bytes object. """ def decode(input: IO[bytes], output: IO[bytes]) -> None: - """ - Decode a file; input and output are binary files. - """ + """Decode a file; input and output are binary files.""" def encode(input: IO[bytes], output: IO[bytes]) -> None: - """ - Encode a file; input and output are binary files. - """ + """Encode a file; input and output are binary files.""" def encodebytes(s: ReadableBuffer) -> bytes: - """ - Encode a bytestring into a bytes object containing multiple lines + """Encode a bytestring into a bytes object containing multiple lines of base-64 data. """ def decodebytes(s: ReadableBuffer) -> bytes: - """ - Decode a bytestring of base-64 data into a bytes object. - """ + """Decode a bytestring of base-64 data into a bytes object.""" if sys.version_info >= (3, 13): def z85encode(s: ReadableBuffer) -> bytes: - """ - Encode bytes-like object b in z85 format and return a bytes object. - """ + """Encode bytes-like object b in z85 format and return a bytes object.""" def z85decode(s: str | ReadableBuffer) -> bytes: - """ - Decode the z85-encoded bytes-like object or ASCII string b + """Decode the z85-encoded bytes-like object or ASCII string b The result is returned as a bytes object. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/bdb.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/bdb.pyi index ec835d1212..9b1c40ee49 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/bdb.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/bdb.pyi @@ -22,13 +22,10 @@ _Backend: TypeAlias = Literal["settrace", "monitoring"] GENERATOR_AND_COROUTINE_FLAGS: Final[int] class BdbQuit(Exception): - """ - Exception to give up completely. - """ + """Exception to give up completely.""" class Bdb: - """ - Generic Python debugger base class. + """Generic Python debugger base class. This class takes care of details of the trace facility; a derived class should implement user interaction. @@ -57,8 +54,7 @@ class Bdb: def __init__(self, skip: Iterable[str] | None = None) -> None: ... def canonic(self, filename: str) -> str: - """ - Return canonical form of filename. + """Return canonical form of filename. For real filenames, the canonical form is a case-normalized (on case insensitive filesystems) absolute path. 'Filenames' with @@ -67,16 +63,13 @@ class Bdb: """ def reset(self) -> None: - """ - Set values of attributes as ready to start debugging. - """ + """Set values of attributes as ready to start debugging.""" if sys.version_info >= (3, 12): @contextmanager def set_enterframe(self, frame: FrameType) -> Iterator[None]: ... def trace_dispatch(self, frame: FrameType, event: str, arg: Any) -> TraceFunction: - """ - Dispatch a trace function for debugged frames based on the event. + """Dispatch a trace function for debugged frames based on the event. This function is installed as the trace function for debugged frames. Its return value is the new trace function, which is @@ -101,8 +94,7 @@ class Bdb: """ def dispatch_line(self, frame: FrameType) -> TraceFunction: - """ - Invoke user function and return trace function for line event. + """Invoke user function and return trace function for line event. If the debugger stops on the current line, invoke self.user_line(). Raise BdbQuit if self.quitting is set. @@ -110,8 +102,7 @@ class Bdb: """ def dispatch_call(self, frame: FrameType, arg: None) -> TraceFunction: - """ - Invoke user function and return trace function for call event. + """Invoke user function and return trace function for call event. If the debugger stops on this function call, invoke self.user_call(). Raise BdbQuit if self.quitting is set. @@ -119,8 +110,7 @@ class Bdb: """ def dispatch_return(self, frame: FrameType, arg: Any) -> TraceFunction: - """ - Invoke user function and return trace function for return event. + """Invoke user function and return trace function for return event. If the debugger stops on this function return, invoke self.user_return(). Raise BdbQuit if self.quitting is set. @@ -128,8 +118,7 @@ class Bdb: """ def dispatch_exception(self, frame: FrameType, arg: ExcInfo) -> TraceFunction: - """ - Invoke user function and return trace function for exception event. + """Invoke user function and return trace function for exception event. If the debugger stops on this exception, invoke self.user_exception(). Raise BdbQuit if self.quitting is set. @@ -137,8 +126,7 @@ class Bdb: """ if sys.version_info >= (3, 13): def dispatch_opcode(self, frame: FrameType, arg: Unused) -> Callable[[FrameType, str, Any], TraceFunction]: - """ - Invoke user function and return trace function for opcode event. + """Invoke user function and return trace function for opcode event. If the debugger stops on the current opcode, invoke self.user_opcode(). Raise BdbQuit if self.quitting is set. Return self.trace_dispatch to continue tracing in this scope. @@ -149,103 +137,73 @@ class Bdb: """ def is_skipped_module(self, module_name: str) -> bool: - """ - Return True if module_name matches any skip pattern. - """ + """Return True if module_name matches any skip pattern.""" def stop_here(self, frame: FrameType) -> bool: - """ - Return True if frame is below the starting frame in the stack. - """ + """Return True if frame is below the starting frame in the stack.""" def break_here(self, frame: FrameType) -> bool: - """ - Return True if there is an effective breakpoint for this line. + """Return True if there is an effective breakpoint for this line. Check for line or function breakpoint and if in effect. Delete temporary breakpoints if effective() says to. """ def do_clear(self, arg: Any) -> bool | None: - """ - Remove temporary breakpoint. + """Remove temporary breakpoint. Must implement in derived classes or get NotImplementedError. """ def break_anywhere(self, frame: FrameType) -> bool: - """ - Return True if there is any breakpoint in that frame - """ + """Return True if there is any breakpoint in that frame""" def user_call(self, frame: FrameType, argument_list: None) -> None: - """ - Called if we might stop in a function. - """ + """Called if we might stop in a function.""" def user_line(self, frame: FrameType) -> None: - """ - Called when we stop or break at a line. - """ + """Called when we stop or break at a line.""" def user_return(self, frame: FrameType, return_value: Any) -> None: - """ - Called when a return trap is set here. - """ + """Called when a return trap is set here.""" def user_exception(self, frame: FrameType, exc_info: ExcInfo) -> None: - """ - Called when we stop on an exception. - """ + """Called when we stop on an exception.""" def set_until(self, frame: FrameType, lineno: int | None = None) -> None: - """ - Stop when the line with the lineno greater than the current one is + """Stop when the line with the lineno greater than the current one is reached or when returning from current frame. """ if sys.version_info >= (3, 13): def user_opcode(self, frame: FrameType) -> None: # undocumented - """ - Called when we are about to execute an opcode. - """ + """Called when we are about to execute an opcode.""" def set_step(self) -> None: - """ - Stop after one line of code. - """ + """Stop after one line of code.""" if sys.version_info >= (3, 13): def set_stepinstr(self) -> None: # undocumented - """ - Stop before the next instruction. - """ + """Stop before the next instruction.""" def set_next(self, frame: FrameType) -> None: - """ - Stop on the next line in or below the given frame. - """ + """Stop on the next line in or below the given frame.""" def set_return(self, frame: FrameType) -> None: - """ - Stop when returning from the given frame. - """ + """Stop when returning from the given frame.""" def set_trace(self, frame: FrameType | None = None) -> None: - """ - Start debugging from frame. + """Start debugging from frame. If frame is not specified, debugging starts from caller's frame. """ def set_continue(self) -> None: - """ - Stop only at breakpoints or when finished. + """Stop only at breakpoints or when finished. If there are no breakpoints, set the system trace function to None. """ def set_quit(self) -> None: - """ - Set quitting attribute to True. + """Set quitting attribute to True. Raises BdbQuit exception in the next call to a dispatch_*() method. """ @@ -253,84 +211,70 @@ class Bdb: def set_break( self, filename: str, lineno: int, temporary: bool = False, cond: str | None = None, funcname: str | None = None ) -> str | None: - """ - Set a new breakpoint for filename:lineno. + """Set a new breakpoint for filename:lineno. If lineno doesn't exist for the filename, return an error message. The filename should be in canonical form. """ def clear_break(self, filename: str, lineno: int) -> str | None: - """ - Delete breakpoints for filename:lineno. + """Delete breakpoints for filename:lineno. If no breakpoints were set, return an error message. """ def clear_bpbynumber(self, arg: SupportsInt) -> str | None: - """ - Delete a breakpoint by its index in Breakpoint.bpbynumber. + """Delete a breakpoint by its index in Breakpoint.bpbynumber. If arg is invalid, return an error message. """ def clear_all_file_breaks(self, filename: str) -> str | None: - """ - Delete all breakpoints in filename. + """Delete all breakpoints in filename. If none were set, return an error message. """ def clear_all_breaks(self) -> str | None: - """ - Delete all existing breakpoints. + """Delete all existing breakpoints. If none were set, return an error message. """ def get_bpbynumber(self, arg: SupportsInt) -> Breakpoint: - """ - Return a breakpoint by its index in Breakpoint.bybpnumber. + """Return a breakpoint by its index in Breakpoint.bybpnumber. For invalid arg values or if the breakpoint doesn't exist, raise a ValueError. """ def get_break(self, filename: str, lineno: int) -> bool: - """ - Return True if there is a breakpoint for filename:lineno. - """ + """Return True if there is a breakpoint for filename:lineno.""" def get_breaks(self, filename: str, lineno: int) -> list[Breakpoint]: - """ - Return all breakpoints for filename:lineno. + """Return all breakpoints for filename:lineno. If no breakpoints are set, return an empty list. """ def get_file_breaks(self, filename: str) -> list[Breakpoint]: - """ - Return all lines with breakpoints for filename. + """Return all lines with breakpoints for filename. If no breakpoints are set, return an empty list. """ def get_all_breaks(self) -> list[Breakpoint]: - """ - Return all breakpoints that are set. - """ + """Return all breakpoints that are set.""" def get_stack(self, f: FrameType | None, t: TracebackType | None) -> tuple[list[tuple[FrameType, int]], int]: - """ - Return a list of (frame, lineno) in a stack trace and a size. + """Return a list of (frame, lineno) in a stack trace and a size. List starts with original calling frame, if there is one. Size may be number of frames above or below f. """ def format_stack_entry(self, frame_lineno: tuple[FrameType, int], lprefix: str = ": ") -> str: - """ - Return a string with information about a stack entry. + """Return a string with information about a stack entry. The stack entry frame_lineno is a (frame, lineno) tuple. The return string contains the canonical filename, the function name @@ -339,27 +283,22 @@ class Bdb: """ def run(self, cmd: str | CodeType, globals: dict[str, Any] | None = None, locals: Mapping[str, Any] | None = None) -> None: - """ - Debug a statement executed via the exec() function. + """Debug a statement executed via the exec() function. globals defaults to __main__.dict; locals defaults to globals. """ def runeval(self, expr: str, globals: dict[str, Any] | None = None, locals: Mapping[str, Any] | None = None) -> None: - """ - Debug an expression executed via the eval() function. + """Debug an expression executed via the eval() function. globals defaults to __main__.dict; locals defaults to globals. """ def runctx(self, cmd: str | CodeType, globals: dict[str, Any] | None, locals: Mapping[str, Any] | None) -> None: - """ - For backwards-compatibility. Defers to run(). - """ + """For backwards-compatibility. Defers to run().""" def runcall(self, func: Callable[_P, _T], /, *args: _P.args, **kwds: _P.kwargs) -> _T | None: - """ - Debug a single function call. + """Debug a single function call. Return the result of the function call. """ @@ -367,18 +306,13 @@ class Bdb: def start_trace(self) -> None: ... def stop_trace(self) -> None: ... def disable_current_event(self) -> None: - """ - Disable the current event. - """ + """Disable the current event.""" def restart_events(self) -> None: - """ - Restart all events. - """ + """Restart all events.""" class Breakpoint: - """ - Breakpoint class. + """Breakpoint class. Implements temporary breakpoints, ignore counts, disabling and (re)-enabling, and conditionals. @@ -417,34 +351,27 @@ class Breakpoint: def clearBreakpoints() -> None: ... def deleteMe(self) -> None: - """ - Delete the breakpoint from the list associated to a file:line. + """Delete the breakpoint from the list associated to a file:line. If it is the last breakpoint in that position, it also deletes the entry for the file:line. """ def enable(self) -> None: - """ - Mark the breakpoint as enabled. - """ + """Mark the breakpoint as enabled.""" def disable(self) -> None: - """ - Mark the breakpoint as disabled. - """ + """Mark the breakpoint as disabled.""" def bpprint(self, out: IO[str] | None = None) -> None: - """ - Print the output of bpformat(). + """Print the output of bpformat(). The optional out argument directs where the output is sent and defaults to standard output. """ def bpformat(self) -> str: - """ - Return a string with information about the breakpoint. + """Return a string with information about the breakpoint. The information includes the breakpoint number, temporary status, file:line position, break condition, number of times to @@ -452,8 +379,7 @@ class Breakpoint: """ def checkfuncname(b: Breakpoint, frame: FrameType) -> bool: - """ - Return True if break should happen here. + """Return True if break should happen here. Whether a break should happen depends on the way that b (the breakpoint) was set. If it was set via line number, check if b.line is the same as @@ -462,8 +388,7 @@ def checkfuncname(b: Breakpoint, frame: FrameType) -> bool: """ def effective(file: str, line: int, frame: FrameType) -> tuple[Breakpoint, bool] | tuple[None, None]: - """ - Return (active breakpoint, delete temporary flag) or (None, None) as + """Return (active breakpoint, delete temporary flag) or (None, None) as breakpoint to act upon. The "active breakpoint" is the first entry in bplist[line, file] (which @@ -477,6 +402,4 @@ def effective(file: str, line: int, frame: FrameType) -> tuple[Breakpoint, bool] """ def set_trace() -> None: - """ - Start debugging with a Bdb instance from the caller's frame. - """ + """Start debugging with a Bdb instance from the caller's frame.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/binascii.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/binascii.pyi index e9cd654139..ef41da12c7 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/binascii.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/binascii.pyi @@ -11,19 +11,14 @@ from typing_extensions import TypeAlias _AsciiBuffer: TypeAlias = str | ReadableBuffer def a2b_uu(data: _AsciiBuffer, /) -> bytes: - """ - Decode a line of uuencoded data. - """ + """Decode a line of uuencoded data.""" def b2a_uu(data: ReadableBuffer, /, *, backtick: bool = False) -> bytes: - """ - Uuencode line of data. - """ + """Uuencode line of data.""" if sys.version_info >= (3, 11): def a2b_base64(data: _AsciiBuffer, /, *, strict_mode: bool = False) -> bytes: - """ - Decode a line of base64 data. + """Decode a line of base64 data. strict_mode When set to True, bytes that are not part of the base64 standard are not allowed. @@ -32,23 +27,16 @@ if sys.version_info >= (3, 11): else: def a2b_base64(data: _AsciiBuffer, /) -> bytes: - """ - Decode a line of base64 data. - """ + """Decode a line of base64 data.""" def b2a_base64(data: ReadableBuffer, /, *, newline: bool = True) -> bytes: - """ - Base64-code line of data. - """ + """Base64-code line of data.""" def a2b_qp(data: _AsciiBuffer, header: bool = False) -> bytes: - """ - Decode a string of qp-encoded data. - """ + """Decode a string of qp-encoded data.""" def b2a_qp(data: ReadableBuffer, quotetabs: bool = False, istext: bool = True, header: bool = False) -> bytes: - """ - Encode a string using quoted-printable encoding. + """Encode a string using quoted-printable encoding. On encoding, when istext is set, newlines are not encoded, and white space at end of lines is. When istext is not set, \\r and \\n (CR/LF) @@ -57,38 +45,25 @@ def b2a_qp(data: ReadableBuffer, quotetabs: bool = False, istext: bool = True, h if sys.version_info < (3, 11): def a2b_hqx(data: _AsciiBuffer, /) -> bytes: - """ - Decode .hqx coding. - """ + """Decode .hqx coding.""" def rledecode_hqx(data: ReadableBuffer, /) -> bytes: - """ - Decode hexbin RLE-coded string. - """ + """Decode hexbin RLE-coded string.""" def rlecode_hqx(data: ReadableBuffer, /) -> bytes: - """ - Binhex RLE-code binary data. - """ + """Binhex RLE-code binary data.""" def b2a_hqx(data: ReadableBuffer, /) -> bytes: - """ - Encode .hqx data. - """ + """Encode .hqx data.""" def crc_hqx(data: ReadableBuffer, crc: int, /) -> int: - """ - Compute CRC-CCITT incrementally. - """ + """Compute CRC-CCITT incrementally.""" def crc32(data: ReadableBuffer, crc: int = 0, /) -> int: - """ - Compute CRC-32 incrementally. - """ + """Compute CRC-32 incrementally.""" def b2a_hex(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = ...) -> bytes: - """ - Hexadecimal representation of binary data. + """Hexadecimal representation of binary data. sep An optional single character or byte to separate hex bytes. @@ -109,8 +84,7 @@ def b2a_hex(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = . """ def hexlify(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = ...) -> bytes: - """ - Hexadecimal representation of binary data. + """Hexadecimal representation of binary data. sep An optional single character or byte to separate hex bytes. @@ -123,16 +97,14 @@ def hexlify(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = . """ def a2b_hex(hexstr: _AsciiBuffer, /) -> bytes: - """ - Binary data of hexadecimal representation. + """Binary data of hexadecimal representation. hexstr must contain an even number of hex digits (upper or lower case). This function is also available as "unhexlify()". """ def unhexlify(hexstr: _AsciiBuffer, /) -> bytes: - """ - Binary data of hexadecimal representation. + """Binary data of hexadecimal representation. hexstr must contain an even number of hex digits (upper or lower case). """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/binhex.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/binhex.pyi index bbfe58203c..b66b9cabe5 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/binhex.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/binhex.pyi @@ -42,9 +42,7 @@ class BinHex: def close(self) -> None: ... def binhex(inp: str, out: str) -> None: - """ - binhex(infilename, outfilename): create binhex-encoded copy of a file - """ + """binhex(infilename, outfilename): create binhex-encoded copy of a file""" class HexBin: def __init__(self, ifp: _FileHandleUnion) -> None: ... @@ -54,6 +52,4 @@ class HexBin: def close(self) -> None: ... def hexbin(inp: str, out: str) -> None: - """ - hexbin(infilename, outfilename) - Decode binhexed file - """ + """hexbin(infilename, outfilename) - Decode binhexed file""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/builtins.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/builtins.pyi index a2284b43ad..55a163d43c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/builtins.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/builtins.pyi @@ -117,8 +117,7 @@ _StopT_co = TypeVar("_StopT_co", covariant=True, default=_StartT_co) # slice[A _StepT_co = TypeVar("_StepT_co", covariant=True, default=_StartT_co | _StopT_co) # slice[A,B] -> slice[A, B, A|B] class object: - """ - The base class of the class hierarchy. + """The base class of the class hierarchy. When called, it accepts no arguments and returns a new featureless instance that has no instance attributes and cannot be given any. @@ -159,8 +158,7 @@ class object: def __subclasshook__(cls, subclass: type, /) -> bool: ... class staticmethod(Generic[_P, _R_co]): - """ - Convert a function to be a static method. + """Convert a function to be a static method. A static method does not receive an implicit first argument. To declare a static method, use this idiom: @@ -185,9 +183,7 @@ class staticmethod(Generic[_P, _R_co]): def __init__(self, f: Callable[_P, _R_co], /) -> None: ... @overload def __get__(self, instance: None, owner: type, /) -> Callable[_P, _R_co]: - """ - Return an attribute of instance, which is of type owner. - """ + """Return an attribute of instance, which is of type owner.""" @overload def __get__(self, instance: _T, owner: type[_T] | None = None, /) -> Callable[_P, _R_co]: ... @@ -197,16 +193,13 @@ class staticmethod(Generic[_P, _R_co]): @property def __wrapped__(self) -> Callable[_P, _R_co]: ... def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R_co: - """ - Call self as a function. - """ + """Call self as a function.""" if sys.version_info >= (3, 14): def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... __annotate__: AnnotateFunc | None class classmethod(Generic[_T, _P, _R_co]): - """ - Convert a function to be a class method. + """Convert a function to be a class method. A class method receives the class as implicit first argument, just like an instance method receives the instance. @@ -233,9 +226,7 @@ class classmethod(Generic[_T, _P, _R_co]): def __init__(self, f: Callable[Concatenate[type[_T], _P], _R_co], /) -> None: ... @overload def __get__(self, instance: _T, owner: type[_T] | None = None, /) -> Callable[_P, _R_co]: - """ - Return an attribute of instance, which is of type owner. - """ + """Return an attribute of instance, which is of type owner.""" @overload def __get__(self, instance: None, owner: type[_T], /) -> Callable[_P, _R_co]: ... @@ -249,8 +240,7 @@ class classmethod(Generic[_T, _P, _R_co]): __annotate__: AnnotateFunc | None class type: - """ - type(object) -> the object's type + """type(object) -> the object's type type(name, bases, dict, **kwds) -> a new type """ @@ -288,46 +278,30 @@ class type: cls: type[_typeshed.Self], name: str, bases: tuple[type, ...], namespace: dict[str, Any], /, **kwds: Any ) -> _typeshed.Self: ... def __call__(self, *args: Any, **kwds: Any) -> Any: - """ - Call self as a function. - """ + """Call self as a function.""" def __subclasses__(self: _typeshed.Self) -> list[_typeshed.Self]: - """ - Return a list of immediate subclasses. - """ + """Return a list of immediate subclasses.""" # Note: the documentation doesn't specify what the return type is, the standard # implementation seems to be returning a list. def mro(self) -> list[type]: - """ - Return a type's method resolution order. - """ + """Return a type's method resolution order.""" def __instancecheck__(self, instance: Any, /) -> bool: - """ - Check if an object is an instance. - """ + """Check if an object is an instance.""" def __subclasscheck__(self, subclass: type, /) -> bool: - """ - Check if a class is a subclass. - """ + """Check if a class is a subclass.""" @classmethod def __prepare__(metacls, name: str, bases: tuple[type, ...], /, **kwds: Any) -> MutableMapping[str, object]: - """ - Create the namespace for the class statement - """ + """Create the namespace for the class statement""" if sys.version_info >= (3, 10): def __or__(self, value: Any, /) -> types.UnionType: - """ - Return self|value. - """ + """Return self|value.""" def __ror__(self, value: Any, /) -> types.UnionType: - """ - Return value|self. - """ + """Return value|self.""" if sys.version_info >= (3, 12): __type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] __annotations__: dict[str, AnnotationForm] @@ -335,8 +309,7 @@ class type: __annotate__: AnnotateFunc | None class super: - """ - super() -> same as super(__class__, ) + """super() -> same as super(__class__, ) super(type) -> unbound super object super(type, obj) -> bound super object; requires isinstance(obj, type) super(type, type2) -> bound super object; requires issubclass(type2, type) @@ -363,8 +336,7 @@ _NegativeInteger: TypeAlias = Literal[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, - _LiteralInteger = _PositiveInteger | _NegativeInteger | Literal[0] # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed class int: - """ - int([x]) -> integer + """int([x]) -> integer int(x, base=10) -> integer Convert a number or string to an integer, or return 0 if no arguments @@ -385,8 +357,7 @@ class int: @overload def __new__(cls, x: str | bytes | bytearray, /, base: SupportsIndex) -> Self: ... def as_integer_ratio(self) -> tuple[int, Literal[1]]: - """ - Return a pair of integers, whose ratio is equal to the original int. + """Return a pair of integers, whose ratio is equal to the original int. The ratio is in lowest terms and has a positive denominator. @@ -400,36 +371,25 @@ class int: @property def real(self) -> int: - """ - the real part of a complex number - """ + """the real part of a complex number""" @property def imag(self) -> Literal[0]: - """ - the imaginary part of a complex number - """ + """the imaginary part of a complex number""" @property def numerator(self) -> int: - """ - the numerator of a rational number in lowest terms - """ + """the numerator of a rational number in lowest terms""" @property def denominator(self) -> Literal[1]: - """ - the denominator of a rational number in lowest terms - """ + """the denominator of a rational number in lowest terms""" def conjugate(self) -> int: - """ - Returns self, the complex conjugate of any int. - """ + """Returns self, the complex conjugate of any int.""" def bit_length(self) -> int: - """ - Number of bits necessary to represent self in binary. + """Number of bits necessary to represent self in binary. >>> bin(37) '0b100101' @@ -438,8 +398,7 @@ class int: """ if sys.version_info >= (3, 10): def bit_count(self) -> int: - """ - Number of ones in the binary representation of the absolute value of self. + """Number of ones in the binary representation of the absolute value of self. Also known as the population count. @@ -452,8 +411,7 @@ class int: def to_bytes( self, length: SupportsIndex = 1, byteorder: Literal["little", "big"] = "big", *, signed: bool = False ) -> bytes: - """ - Return an array of bytes representing an integer. + """Return an array of bytes representing an integer. length Length of bytes object to use. An OverflowError is raised if the @@ -479,8 +437,7 @@ class int: *, signed: bool = False, ) -> Self: - """ - Return the integer represented by the given array of bytes. + """Return the integer represented by the given array of bytes. bytes Holds the array of bytes to convert. The argument must either @@ -498,8 +455,7 @@ class int: """ else: def to_bytes(self, length: SupportsIndex, byteorder: Literal["little", "big"], *, signed: bool = False) -> bytes: - """ - Return an array of bytes representing an integer. + """Return an array of bytes representing an integer. length Length of bytes object to use. An OverflowError is raised if the @@ -525,8 +481,7 @@ class int: *, signed: bool = False, ) -> Self: - """ - Return the integer represented by the given array of bytes. + """Return the integer represented by the given array of bytes. bytes Holds the array of bytes to convert. The argument must either @@ -544,85 +499,53 @@ class int: """ if sys.version_info >= (3, 12): def is_integer(self) -> Literal[True]: - """ - Returns True. Exists for duck type compatibility with float.is_integer. - """ + """Returns True. Exists for duck type compatibility with float.is_integer.""" def __add__(self, value: int, /) -> int: - """ - Return self+value. - """ + """Return self+value.""" def __sub__(self, value: int, /) -> int: - """ - Return self-value. - """ + """Return self-value.""" def __mul__(self, value: int, /) -> int: - """ - Return self*value. - """ + """Return self*value.""" def __floordiv__(self, value: int, /) -> int: - """ - Return self//value. - """ + """Return self//value.""" def __truediv__(self, value: int, /) -> float: - """ - Return self/value. - """ + """Return self/value.""" def __mod__(self, value: int, /) -> int: - """ - Return self%value. - """ + """Return self%value.""" def __divmod__(self, value: int, /) -> tuple[int, int]: - """ - Return divmod(self, value). - """ + """Return divmod(self, value).""" def __radd__(self, value: int, /) -> int: - """ - Return value+self. - """ + """Return value+self.""" def __rsub__(self, value: int, /) -> int: - """ - Return value-self. - """ + """Return value-self.""" def __rmul__(self, value: int, /) -> int: - """ - Return value*self. - """ + """Return value*self.""" def __rfloordiv__(self, value: int, /) -> int: - """ - Return value//self. - """ + """Return value//self.""" def __rtruediv__(self, value: int, /) -> float: - """ - Return value/self. - """ + """Return value/self.""" def __rmod__(self, value: int, /) -> int: - """ - Return value%self. - """ + """Return value%self.""" def __rdivmod__(self, value: int, /) -> tuple[int, int]: - """ - Return divmod(value, self). - """ + """Return divmod(value, self).""" @overload def __pow__(self, x: Literal[0], /) -> Literal[1]: - """ - Return pow(self, value, mod). - """ + """Return pow(self, value, mod).""" @overload def __pow__(self, value: Literal[0], mod: None, /) -> Literal[1]: ... @@ -637,100 +560,64 @@ class int: @overload def __pow__(self, value: int, mod: int, /) -> int: ... def __rpow__(self, value: int, mod: int | None = None, /) -> Any: - """ - Return pow(value, self, mod). - """ + """Return pow(value, self, mod).""" def __and__(self, value: int, /) -> int: - """ - Return self&value. - """ + """Return self&value.""" def __or__(self, value: int, /) -> int: - """ - Return self|value. - """ + """Return self|value.""" def __xor__(self, value: int, /) -> int: - """ - Return self^value. - """ + """Return self^value.""" def __lshift__(self, value: int, /) -> int: - """ - Return self< int: - """ - Return self>>value. - """ + """Return self>>value.""" def __rand__(self, value: int, /) -> int: - """ - Return value&self. - """ + """Return value&self.""" def __ror__(self, value: int, /) -> int: - """ - Return value|self. - """ + """Return value|self.""" def __rxor__(self, value: int, /) -> int: - """ - Return value^self. - """ + """Return value^self.""" def __rlshift__(self, value: int, /) -> int: - """ - Return value< int: - """ - Return value>>self. - """ + """Return value>>self.""" def __neg__(self) -> int: - """ - -self - """ + """-self""" def __pos__(self) -> int: - """ - +self - """ + """+self""" def __invert__(self) -> int: - """ - ~self - """ + """~self""" def __trunc__(self) -> int: - """ - Truncating an Integral returns itself. - """ + """Truncating an Integral returns itself.""" def __ceil__(self) -> int: - """ - Ceiling of an Integral returns itself. - """ + """Ceiling of an Integral returns itself.""" def __floor__(self) -> int: - """ - Flooring an Integral returns itself. - """ + """Flooring an Integral returns itself.""" if sys.version_info >= (3, 14): def __round__(self, ndigits: SupportsIndex | None = None, /) -> int: - """ - Rounding an Integral returns itself. + """Rounding an Integral returns itself. Rounding with an ndigits argument also returns an integer. """ else: def __round__(self, ndigits: SupportsIndex = ..., /) -> int: - """ - Rounding an Integral returns itself. + """Rounding an Integral returns itself. Rounding with an ndigits argument also returns an integer. """ @@ -743,40 +630,27 @@ class int: def __gt__(self, value: int, /) -> bool: ... def __ge__(self, value: int, /) -> bool: ... def __float__(self) -> float: - """ - float(self) - """ + """float(self)""" def __int__(self) -> int: - """ - int(self) - """ + """int(self)""" def __abs__(self) -> int: - """ - abs(self) - """ + """abs(self)""" def __hash__(self) -> int: ... def __bool__(self) -> bool: - """ - True if self else False - """ + """True if self else False""" def __index__(self) -> int: - """ - Return self converted to an integer, if self is suitable for use as an index into a list. - """ + """Return self converted to an integer, if self is suitable for use as an index into a list.""" class float: - """ - Convert a string or number to a floating-point number, if possible. - """ + """Convert a string or number to a floating-point number, if possible.""" def __new__(cls, x: ConvertibleToFloat = ..., /) -> Self: ... def as_integer_ratio(self) -> tuple[int, int]: - """ - Return a pair of integers, whose ratio is exactly equal to the original float. + """Return a pair of integers, whose ratio is exactly equal to the original float. The ratio is in lowest terms and has a positive denominator. Raise OverflowError on infinities and a ValueError on NaNs. @@ -790,8 +664,7 @@ class float: """ def hex(self) -> str: - """ - Return a hexadecimal representation of a floating-point number. + """Return a hexadecimal representation of a floating-point number. >>> (-0.1).hex() '-0x1.999999999999ap-4' @@ -800,14 +673,11 @@ class float: """ def is_integer(self) -> bool: - """ - Return True if the float is an integer. - """ + """Return True if the float is an integer.""" @classmethod def fromhex(cls, string: str, /) -> Self: - """ - Create a floating-point number from a hexadecimal string. + """Create a floating-point number from a hexadecimal string. >>> float.fromhex('0x1.ffffp10') 2047.984375 @@ -817,105 +687,67 @@ class float: @property def real(self) -> float: - """ - the real part of a complex number - """ + """the real part of a complex number""" @property def imag(self) -> float: - """ - the imaginary part of a complex number - """ + """the imaginary part of a complex number""" def conjugate(self) -> float: - """ - Return self, the complex conjugate of any float. - """ + """Return self, the complex conjugate of any float.""" def __add__(self, value: float, /) -> float: - """ - Return self+value. - """ + """Return self+value.""" def __sub__(self, value: float, /) -> float: - """ - Return self-value. - """ + """Return self-value.""" def __mul__(self, value: float, /) -> float: - """ - Return self*value. - """ + """Return self*value.""" def __floordiv__(self, value: float, /) -> float: - """ - Return self//value. - """ + """Return self//value.""" def __truediv__(self, value: float, /) -> float: - """ - Return self/value. - """ + """Return self/value.""" def __mod__(self, value: float, /) -> float: - """ - Return self%value. - """ + """Return self%value.""" def __divmod__(self, value: float, /) -> tuple[float, float]: - """ - Return divmod(self, value). - """ + """Return divmod(self, value).""" @overload def __pow__(self, value: int, mod: None = None, /) -> float: - """ - Return pow(self, value, mod). - """ + """Return pow(self, value, mod).""" # positive __value -> float; negative __value -> complex # return type must be Any as `float | complex` causes too many false-positive errors @overload def __pow__(self, value: float, mod: None = None, /) -> Any: ... def __radd__(self, value: float, /) -> float: - """ - Return value+self. - """ + """Return value+self.""" def __rsub__(self, value: float, /) -> float: - """ - Return value-self. - """ + """Return value-self.""" def __rmul__(self, value: float, /) -> float: - """ - Return value*self. - """ + """Return value*self.""" def __rfloordiv__(self, value: float, /) -> float: - """ - Return value//self. - """ + """Return value//self.""" def __rtruediv__(self, value: float, /) -> float: - """ - Return value/self. - """ + """Return value/self.""" def __rmod__(self, value: float, /) -> float: - """ - Return value%self. - """ + """Return value%self.""" def __rdivmod__(self, value: float, /) -> tuple[float, float]: - """ - Return divmod(value, self). - """ + """Return divmod(value, self).""" @overload def __rpow__(self, value: _PositiveInteger, mod: None = None, /) -> float: - """ - Return pow(value, self, mod). - """ + """Return pow(value, self, mod).""" @overload def __rpow__(self, value: _NegativeInteger, mod: None = None, /) -> complex: ... @@ -924,24 +756,17 @@ class float: def __rpow__(self, value: float, mod: None = None, /) -> Any: ... def __getnewargs__(self) -> tuple[float]: ... def __trunc__(self) -> int: - """ - Return the Integral closest to x between 0 and x. - """ + """Return the Integral closest to x between 0 and x.""" def __ceil__(self) -> int: - """ - Return the ceiling as an Integral. - """ + """Return the ceiling as an Integral.""" def __floor__(self) -> int: - """ - Return the floor as an Integral. - """ + """Return the floor as an Integral.""" @overload def __round__(self, ndigits: None = None, /) -> int: - """ - Return the Integral closest to x, rounding half toward even. + """Return the Integral closest to x, rounding half toward even. When an argument is passed, work like built-in round(x, ndigits). """ @@ -955,45 +780,30 @@ class float: def __gt__(self, value: float, /) -> bool: ... def __ge__(self, value: float, /) -> bool: ... def __neg__(self) -> float: - """ - -self - """ + """-self""" def __pos__(self) -> float: - """ - +self - """ + """+self""" def __int__(self) -> int: - """ - int(self) - """ + """int(self)""" def __float__(self) -> float: - """ - float(self) - """ + """float(self)""" def __abs__(self) -> float: - """ - abs(self) - """ + """abs(self)""" def __hash__(self) -> int: ... def __bool__(self) -> bool: - """ - True if self else False - """ + """True if self else False""" if sys.version_info >= (3, 14): @classmethod def from_number(cls, number: float | SupportsIndex | SupportsFloat, /) -> Self: - """ - Convert real number to a floating-point number. - """ + """Convert real number to a floating-point number.""" class complex: - """ - Create a complex number from a string or numbers. + """Create a complex number from a string or numbers. If a string is given, parse it as a complex number. If a single number is given, convert it to a complex number. @@ -1012,104 +822,66 @@ class complex: def __new__(cls, real: str | SupportsComplex | SupportsFloat | SupportsIndex | complex) -> Self: ... @property def real(self) -> float: - """ - the real part of a complex number - """ + """the real part of a complex number""" @property def imag(self) -> float: - """ - the imaginary part of a complex number - """ + """the imaginary part of a complex number""" def conjugate(self) -> complex: - """ - Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j. - """ + """Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.""" def __add__(self, value: complex, /) -> complex: - """ - Return self+value. - """ + """Return self+value.""" def __sub__(self, value: complex, /) -> complex: - """ - Return self-value. - """ + """Return self-value.""" def __mul__(self, value: complex, /) -> complex: - """ - Return self*value. - """ + """Return self*value.""" def __pow__(self, value: complex, mod: None = None, /) -> complex: - """ - Return pow(self, value, mod). - """ + """Return pow(self, value, mod).""" def __truediv__(self, value: complex, /) -> complex: - """ - Return self/value. - """ + """Return self/value.""" def __radd__(self, value: complex, /) -> complex: - """ - Return value+self. - """ + """Return value+self.""" def __rsub__(self, value: complex, /) -> complex: - """ - Return value-self. - """ + """Return value-self.""" def __rmul__(self, value: complex, /) -> complex: - """ - Return value*self. - """ + """Return value*self.""" def __rpow__(self, value: complex, mod: None = None, /) -> complex: - """ - Return pow(value, self, mod). - """ + """Return pow(value, self, mod).""" def __rtruediv__(self, value: complex, /) -> complex: - """ - Return value/self. - """ + """Return value/self.""" def __eq__(self, value: object, /) -> bool: ... def __ne__(self, value: object, /) -> bool: ... def __neg__(self) -> complex: - """ - -self - """ + """-self""" def __pos__(self) -> complex: - """ - +self - """ + """+self""" def __abs__(self) -> float: - """ - abs(self) - """ + """abs(self)""" def __hash__(self) -> int: ... def __bool__(self) -> bool: - """ - True if self else False - """ + """True if self else False""" if sys.version_info >= (3, 11): def __complex__(self) -> complex: - """ - Convert this value to exact type complex. - """ + """Convert this value to exact type complex.""" if sys.version_info >= (3, 14): @classmethod def from_number(cls, number: complex | SupportsComplex | SupportsFloat | SupportsIndex, /) -> Self: - """ - Convert number to a complex floating-point number. - """ + """Convert number to a complex floating-point number.""" class _FormatMapMapping(Protocol): def __getitem__(self, key: str, /) -> Any: ... @@ -1118,8 +890,7 @@ class _TranslateTable(Protocol): def __getitem__(self, key: int, /) -> str | int | None: ... class str(Sequence[str]): - """ - str(object='') -> str + """str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or @@ -1137,8 +908,7 @@ class str(Sequence[str]): def __new__(cls, object: ReadableBuffer, encoding: str = ..., errors: str = ...) -> Self: ... @overload def capitalize(self: LiteralString) -> LiteralString: - """ - Return a capitalized version of the string. + """Return a capitalized version of the string. More specifically, make the first character have upper case and the rest lower case. @@ -1148,16 +918,13 @@ class str(Sequence[str]): def capitalize(self) -> str: ... # type: ignore[misc] @overload def casefold(self: LiteralString) -> LiteralString: - """ - Return a version of the string suitable for caseless comparisons. - """ + """Return a version of the string suitable for caseless comparisons.""" @overload def casefold(self) -> str: ... # type: ignore[misc] @overload def center(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: - """ - Return a centered string of length width. + """Return a centered string of length width. Padding is done using the specified fill character (default is a space). """ @@ -1165,15 +932,13 @@ class str(Sequence[str]): @overload def center(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] def count(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: - """ - Return the number of non-overlapping occurrences of substring sub in string S[start:end]. + """Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation. """ def encode(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: - """ - Encode the string using the codec registered for encoding. + """Encode the string using the codec registered for encoding. encoding The encoding in which to encode the string. @@ -1188,8 +953,7 @@ class str(Sequence[str]): def endswith( self, suffix: str | tuple[str, ...], start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> bool: - """ - Return True if the string ends with the specified suffix, False otherwise. + """Return True if the string ends with the specified suffix, False otherwise. suffix A string or a tuple of strings to try. @@ -1201,8 +965,7 @@ class str(Sequence[str]): @overload def expandtabs(self: LiteralString, tabsize: SupportsIndex = 8) -> LiteralString: - """ - Return a copy where all tab characters are expanded using spaces. + """Return a copy where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. """ @@ -1210,8 +973,7 @@ class str(Sequence[str]): @overload def expandtabs(self, tabsize: SupportsIndex = 8) -> str: ... # type: ignore[misc] def find(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: - """ - Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. + """Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. @@ -1219,117 +981,102 @@ class str(Sequence[str]): @overload def format(self: LiteralString, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: - """ - Return a formatted version of the string, using substitutions from args and kwargs. + """Return a formatted version of the string, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}'). """ @overload def format(self, *args: object, **kwargs: object) -> str: ... def format_map(self, mapping: _FormatMapMapping, /) -> str: - """ - Return a formatted version of the string, using substitutions from mapping. + """Return a formatted version of the string, using substitutions from mapping. The substitutions are identified by braces ('{' and '}'). """ def index(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: - """ - Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. + """Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found. """ def isalnum(self) -> bool: - """ - Return True if the string is an alpha-numeric string, False otherwise. + """Return True if the string is an alpha-numeric string, False otherwise. A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string. """ def isalpha(self) -> bool: - """ - Return True if the string is an alphabetic string, False otherwise. + """Return True if the string is an alphabetic string, False otherwise. A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string. """ def isascii(self) -> bool: - """ - Return True if all characters in the string are ASCII, False otherwise. + """Return True if all characters in the string are ASCII, False otherwise. ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too. """ def isdecimal(self) -> bool: - """ - Return True if the string is a decimal string, False otherwise. + """Return True if the string is a decimal string, False otherwise. A string is a decimal string if all characters in the string are decimal and there is at least one character in the string. """ def isdigit(self) -> bool: - """ - Return True if the string is a digit string, False otherwise. + """Return True if the string is a digit string, False otherwise. A string is a digit string if all characters in the string are digits and there is at least one character in the string. """ def isidentifier(self) -> bool: - """ - Return True if the string is a valid Python identifier, False otherwise. + """Return True if the string is a valid Python identifier, False otherwise. Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as "def" or "class". """ def islower(self) -> bool: - """ - Return True if the string is a lowercase string, False otherwise. + """Return True if the string is a lowercase string, False otherwise. A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string. """ def isnumeric(self) -> bool: - """ - Return True if the string is a numeric string, False otherwise. + """Return True if the string is a numeric string, False otherwise. A string is numeric if all characters in the string are numeric and there is at least one character in the string. """ def isprintable(self) -> bool: - """ - Return True if all characters in the string are printable, False otherwise. + """Return True if all characters in the string are printable, False otherwise. A character is printable if repr() may use it in its output. """ def isspace(self) -> bool: - """ - Return True if the string is a whitespace string, False otherwise. + """Return True if the string is a whitespace string, False otherwise. A string is whitespace if all characters in the string are whitespace and there is at least one character in the string. """ def istitle(self) -> bool: - """ - Return True if the string is a title-cased string, False otherwise. + """Return True if the string is a title-cased string, False otherwise. In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones. """ def isupper(self) -> bool: - """ - Return True if the string is an uppercase string, False otherwise. + """Return True if the string is an uppercase string, False otherwise. A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string. @@ -1337,8 +1084,7 @@ class str(Sequence[str]): @overload def join(self: LiteralString, iterable: Iterable[LiteralString], /) -> LiteralString: - """ - Concatenate any number of strings. + """Concatenate any number of strings. The string whose method is called is inserted in between each given string. The result is returned as a new string. @@ -1350,8 +1096,7 @@ class str(Sequence[str]): def join(self, iterable: Iterable[str], /) -> str: ... # type: ignore[misc] @overload def ljust(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: - """ - Return a left-justified string of length width. + """Return a left-justified string of length width. Padding is done using the specified fill character (default is a space). """ @@ -1360,16 +1105,13 @@ class str(Sequence[str]): def ljust(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] @overload def lower(self: LiteralString) -> LiteralString: - """ - Return a copy of the string converted to lowercase. - """ + """Return a copy of the string converted to lowercase.""" @overload def lower(self) -> str: ... # type: ignore[misc] @overload def lstrip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: - """ - Return a copy of the string with leading whitespace removed. + """Return a copy of the string with leading whitespace removed. If chars is given and not None, remove characters in chars instead. """ @@ -1378,8 +1120,7 @@ class str(Sequence[str]): def lstrip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] @overload def partition(self: LiteralString, sep: LiteralString, /) -> tuple[LiteralString, LiteralString, LiteralString]: - """ - Partition the string into three parts using the given separator. + """Partition the string into three parts using the given separator. This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator @@ -1394,8 +1135,7 @@ class str(Sequence[str]): if sys.version_info >= (3, 13): @overload def replace(self: LiteralString, old: LiteralString, new: LiteralString, /, count: SupportsIndex = -1) -> LiteralString: - """ - Return a copy with all occurrences of substring old replaced by new. + """Return a copy with all occurrences of substring old replaced by new. count Maximum number of occurrences to replace. @@ -1410,8 +1150,7 @@ class str(Sequence[str]): else: @overload def replace(self: LiteralString, old: LiteralString, new: LiteralString, count: SupportsIndex = -1, /) -> LiteralString: - """ - Return a copy with all occurrences of substring old replaced by new. + """Return a copy with all occurrences of substring old replaced by new. count Maximum number of occurrences to replace. @@ -1426,8 +1165,7 @@ class str(Sequence[str]): @overload def removeprefix(self: LiteralString, prefix: LiteralString, /) -> LiteralString: - """ - Return a str with the given prefix string removed if present. + """Return a str with the given prefix string removed if present. If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string. @@ -1437,8 +1175,7 @@ class str(Sequence[str]): def removeprefix(self, prefix: str, /) -> str: ... # type: ignore[misc] @overload def removesuffix(self: LiteralString, suffix: LiteralString, /) -> LiteralString: - """ - Return a str with the given suffix string removed if present. + """Return a str with the given suffix string removed if present. If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original @@ -1448,16 +1185,14 @@ class str(Sequence[str]): @overload def removesuffix(self, suffix: str, /) -> str: ... # type: ignore[misc] def rfind(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: - """ - Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. + """Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ def rindex(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: - """ - Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. + """Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found. @@ -1465,8 +1200,7 @@ class str(Sequence[str]): @overload def rjust(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: - """ - Return a right-justified string of length width. + """Return a right-justified string of length width. Padding is done using the specified fill character (default is a space). """ @@ -1475,8 +1209,7 @@ class str(Sequence[str]): def rjust(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] @overload def rpartition(self: LiteralString, sep: LiteralString, /) -> tuple[LiteralString, LiteralString, LiteralString]: - """ - Partition the string into three parts using the given separator. + """Partition the string into three parts using the given separator. This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the @@ -1490,8 +1223,7 @@ class str(Sequence[str]): def rpartition(self, sep: str, /) -> tuple[str, str, str]: ... # type: ignore[misc] @overload def rsplit(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: - """ - Return a list of the substrings in the string, using sep as the separator string. + """Return a list of the substrings in the string, using sep as the separator string. sep The separator used to split the string. @@ -1510,8 +1242,7 @@ class str(Sequence[str]): def rsplit(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] @overload def rstrip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: - """ - Return a copy of the string with trailing whitespace removed. + """Return a copy of the string with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ @@ -1520,8 +1251,7 @@ class str(Sequence[str]): def rstrip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] @overload def split(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: - """ - Return a list of the substrings in the string, using sep as the separator string. + """Return a list of the substrings in the string, using sep as the separator string. sep The separator used to split the string. @@ -1544,8 +1274,7 @@ class str(Sequence[str]): def split(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] @overload def splitlines(self: LiteralString, keepends: bool = False) -> list[LiteralString]: - """ - Return a list of the lines in the string, breaking at line boundaries. + """Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. @@ -1556,8 +1285,7 @@ class str(Sequence[str]): def startswith( self, prefix: str | tuple[str, ...], start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> bool: - """ - Return True if the string starts with the specified prefix, False otherwise. + """Return True if the string starts with the specified prefix, False otherwise. prefix A string or a tuple of strings to try. @@ -1569,8 +1297,7 @@ class str(Sequence[str]): @overload def strip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: - """ - Return a copy of the string with leading and trailing whitespace removed. + """Return a copy of the string with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ @@ -1579,16 +1306,13 @@ class str(Sequence[str]): def strip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] @overload def swapcase(self: LiteralString) -> LiteralString: - """ - Convert uppercase characters to lowercase and lowercase characters to uppercase. - """ + """Convert uppercase characters to lowercase and lowercase characters to uppercase.""" @overload def swapcase(self) -> str: ... # type: ignore[misc] @overload def title(self: LiteralString) -> LiteralString: - """ - Return a version of the string where each word is titlecased. + """Return a version of the string where each word is titlecased. More specifically, words start with uppercased characters and all remaining cased characters have lower case. @@ -1597,8 +1321,7 @@ class str(Sequence[str]): @overload def title(self) -> str: ... # type: ignore[misc] def translate(self, table: _TranslateTable, /) -> str: - """ - Replace each character in the string using the given translation table. + """Replace each character in the string using the given translation table. table Translation table, which must be a mapping of Unicode ordinals to @@ -1611,16 +1334,13 @@ class str(Sequence[str]): @overload def upper(self: LiteralString) -> LiteralString: - """ - Return a copy of the string converted to uppercase. - """ + """Return a copy of the string converted to uppercase.""" @overload def upper(self) -> str: ... # type: ignore[misc] @overload def zfill(self: LiteralString, width: SupportsIndex, /) -> LiteralString: - """ - Pad a numeric string with zeros on the left, to fill a field of the given width. + """Pad a numeric string with zeros on the left, to fill a field of the given width. The string is never truncated. """ @@ -1630,8 +1350,7 @@ class str(Sequence[str]): @staticmethod @overload def maketrans(x: dict[int, _T] | dict[str, _T] | dict[str | int, _T], /) -> dict[int, _T]: - """ - Return a translation table usable for str.translate(). + """Return a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. @@ -1650,25 +1369,19 @@ class str(Sequence[str]): def maketrans(x: str, y: str, z: str, /) -> dict[int, int | None]: ... @overload def __add__(self: LiteralString, value: LiteralString, /) -> LiteralString: - """ - Return self+value. - """ + """Return self+value.""" @overload def __add__(self, value: str, /) -> str: ... # type: ignore[misc] # Incompatible with Sequence.__contains__ def __contains__(self, key: str, /) -> bool: # type: ignore[override] - """ - Return bool(key in self). - """ + """Return bool(key in self).""" def __eq__(self, value: object, /) -> bool: ... def __ge__(self, value: str, /) -> bool: ... @overload def __getitem__(self: LiteralString, key: SupportsIndex | slice, /) -> LiteralString: - """ - Return self[key]. - """ + """Return self[key].""" @overload def __getitem__(self, key: SupportsIndex | slice, /) -> str: ... # type: ignore[misc] @@ -1676,49 +1389,38 @@ class str(Sequence[str]): def __hash__(self) -> int: ... @overload def __iter__(self: LiteralString) -> Iterator[LiteralString]: - """ - Implement iter(self). - """ + """Implement iter(self).""" @overload def __iter__(self) -> Iterator[str]: ... # type: ignore[misc] def __le__(self, value: str, /) -> bool: ... def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" def __lt__(self, value: str, /) -> bool: ... @overload def __mod__(self: LiteralString, value: LiteralString | tuple[LiteralString, ...], /) -> LiteralString: - """ - Return self%value. - """ + """Return self%value.""" @overload def __mod__(self, value: Any, /) -> str: ... @overload def __mul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: - """ - Return self*value. - """ + """Return self*value.""" @overload def __mul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] def __ne__(self, value: object, /) -> bool: ... @overload def __rmul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: - """ - Return value*self. - """ + """Return value*self.""" @overload def __rmul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] def __getnewargs__(self) -> tuple[str]: ... class bytes(Sequence[int]): - """ - bytes(iterable_of_ints) -> bytes + """bytes(iterable_of_ints) -> bytes bytes(string, encoding[, errors]) -> bytes bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer bytes(int) -> bytes object of size given by the parameter initialized with null bytes @@ -1738,16 +1440,14 @@ class bytes(Sequence[int]): @overload def __new__(cls) -> Self: ... def capitalize(self) -> bytes: - """ - B.capitalize() -> copy of B + """B.capitalize() -> copy of B Return a copy of B with only its first character capitalized (ASCII) and the rest lower-cased. """ def center(self, width: SupportsIndex, fillchar: bytes = b" ", /) -> bytes: - """ - Return a centered string of length width. + """Return a centered string of length width. Padding is done using the specified fill character. """ @@ -1755,8 +1455,7 @@ class bytes(Sequence[int]): def count( self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: - """ - Return the number of non-overlapping occurrences of subsection 'sub' in bytes B[start:end]. + """Return the number of non-overlapping occurrences of subsection 'sub' in bytes B[start:end]. start Optional start position. Default: start of the bytes. @@ -1765,8 +1464,7 @@ class bytes(Sequence[int]): """ def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: - """ - Decode the bytes using the codec registered for encoding. + """Decode the bytes using the codec registered for encoding. encoding The encoding with which to decode the bytes. @@ -1785,8 +1483,7 @@ class bytes(Sequence[int]): end: SupportsIndex | None = ..., /, ) -> bool: - """ - Return True if the bytes ends with the specified suffix, False otherwise. + """Return True if the bytes ends with the specified suffix, False otherwise. suffix A bytes or a tuple of bytes to try. @@ -1797,8 +1494,7 @@ class bytes(Sequence[int]): """ def expandtabs(self, tabsize: SupportsIndex = 8) -> bytes: - """ - Return a copy where all tab characters are expanded using spaces. + """Return a copy where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. """ @@ -1806,8 +1502,7 @@ class bytes(Sequence[int]): def find( self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: - """ - Return the lowest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start,end]. + """Return the lowest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start,end]. start Optional start position. Default: start of the bytes. @@ -1818,8 +1513,7 @@ class bytes(Sequence[int]): """ def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: - """ - Create a string of hexadecimal numbers from a bytes object. + """Create a string of hexadecimal numbers from a bytes object. sep An optional single character or byte to separate hex bytes. @@ -1842,8 +1536,7 @@ class bytes(Sequence[int]): def index( self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: - """ - Return the lowest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start,end]. + """Return the lowest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start,end]. start Optional start position. Default: start of the bytes. @@ -1854,56 +1547,49 @@ class bytes(Sequence[int]): """ def isalnum(self) -> bool: - """ - B.isalnum() -> bool + """B.isalnum() -> bool Return True if all characters in B are alphanumeric and there is at least one character in B, False otherwise. """ def isalpha(self) -> bool: - """ - B.isalpha() -> bool + """B.isalpha() -> bool Return True if all characters in B are alphabetic and there is at least one character in B, False otherwise. """ def isascii(self) -> bool: - """ - B.isascii() -> bool + """B.isascii() -> bool Return True if B is empty or all characters in B are ASCII, False otherwise. """ def isdigit(self) -> bool: - """ - B.isdigit() -> bool + """B.isdigit() -> bool Return True if all characters in B are digits and there is at least one character in B, False otherwise. """ def islower(self) -> bool: - """ - B.islower() -> bool + """B.islower() -> bool Return True if all cased characters in B are lowercase and there is at least one cased character in B, False otherwise. """ def isspace(self) -> bool: - """ - B.isspace() -> bool + """B.isspace() -> bool Return True if all characters in B are whitespace and there is at least one character in B, False otherwise. """ def istitle(self) -> bool: - """ - B.istitle() -> bool + """B.istitle() -> bool Return True if B is a titlecased string and there is at least one character in B, i.e. uppercase characters may only follow uncased @@ -1912,16 +1598,14 @@ class bytes(Sequence[int]): """ def isupper(self) -> bool: - """ - B.isupper() -> bool + """B.isupper() -> bool Return True if all cased characters in B are uppercase and there is at least one cased character in B, False otherwise. """ def join(self, iterable_of_bytes: Iterable[ReadableBuffer], /) -> bytes: - """ - Concatenate any number of bytes objects. + """Concatenate any number of bytes objects. The bytes whose method is called is inserted in between each pair. @@ -1931,29 +1615,25 @@ class bytes(Sequence[int]): """ def ljust(self, width: SupportsIndex, fillchar: bytes | bytearray = b" ", /) -> bytes: - """ - Return a left-justified string of length width. + """Return a left-justified string of length width. Padding is done using the specified fill character. """ def lower(self) -> bytes: - """ - B.lower() -> copy of B + """B.lower() -> copy of B Return a copy of B with all ASCII characters converted to lowercase. """ def lstrip(self, bytes: ReadableBuffer | None = None, /) -> bytes: - """ - Strip leading bytes contained in the argument. + """Strip leading bytes contained in the argument. If the argument is omitted or None, strip leading ASCII whitespace. """ def partition(self, sep: ReadableBuffer, /) -> tuple[bytes, bytes, bytes]: - """ - Partition the bytes into three parts using the given separator. + """Partition the bytes into three parts using the given separator. This will search for the separator sep in the bytes. If the separator is found, returns a 3-tuple containing the part before the separator, the separator @@ -1964,8 +1644,7 @@ class bytes(Sequence[int]): """ def replace(self, old: ReadableBuffer, new: ReadableBuffer, count: SupportsIndex = -1, /) -> bytes: - """ - Return a copy with all occurrences of substring old replaced by new. + """Return a copy with all occurrences of substring old replaced by new. count Maximum number of occurrences to replace. @@ -1976,16 +1655,14 @@ class bytes(Sequence[int]): """ def removeprefix(self, prefix: ReadableBuffer, /) -> bytes: - """ - Return a bytes object with the given prefix string removed if present. + """Return a bytes object with the given prefix string removed if present. If the bytes starts with the prefix string, return bytes[len(prefix):]. Otherwise, return a copy of the original bytes. """ def removesuffix(self, suffix: ReadableBuffer, /) -> bytes: - """ - Return a bytes object with the given suffix string removed if present. + """Return a bytes object with the given suffix string removed if present. If the bytes ends with the suffix string and that suffix is not empty, return bytes[:-len(prefix)]. Otherwise, return a copy of the original @@ -1995,8 +1672,7 @@ class bytes(Sequence[int]): def rfind( self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: - """ - Return the highest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start,end]. + """Return the highest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start,end]. start Optional start position. Default: start of the bytes. @@ -2009,8 +1685,7 @@ class bytes(Sequence[int]): def rindex( self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: - """ - Return the highest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start,end]. + """Return the highest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start,end]. start Optional start position. Default: start of the bytes. @@ -2021,15 +1696,13 @@ class bytes(Sequence[int]): """ def rjust(self, width: SupportsIndex, fillchar: bytes | bytearray = b" ", /) -> bytes: - """ - Return a right-justified string of length width. + """Return a right-justified string of length width. Padding is done using the specified fill character. """ def rpartition(self, sep: ReadableBuffer, /) -> tuple[bytes, bytes, bytes]: - """ - Partition the bytes into three parts using the given separator. + """Partition the bytes into three parts using the given separator. This will search for the separator sep in the bytes, starting at the end. If the separator is found, returns a 3-tuple containing the part before the @@ -2040,8 +1713,7 @@ class bytes(Sequence[int]): """ def rsplit(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytes]: - """ - Return a list of the sections in the bytes, using sep as the delimiter. + """Return a list of the sections in the bytes, using sep as the delimiter. sep The delimiter according which to split the bytes. @@ -2055,15 +1727,13 @@ class bytes(Sequence[int]): """ def rstrip(self, bytes: ReadableBuffer | None = None, /) -> bytes: - """ - Strip trailing bytes contained in the argument. + """Strip trailing bytes contained in the argument. If the argument is omitted or None, strip trailing ASCII whitespace. """ def split(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytes]: - """ - Return a list of the sections in the bytes, using sep as the delimiter. + """Return a list of the sections in the bytes, using sep as the delimiter. sep The delimiter according which to split the bytes. @@ -2075,8 +1745,7 @@ class bytes(Sequence[int]): """ def splitlines(self, keepends: bool = False) -> list[bytes]: - """ - Return a list of the lines in the bytes, breaking at line boundaries. + """Return a list of the lines in the bytes, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. @@ -2089,8 +1758,7 @@ class bytes(Sequence[int]): end: SupportsIndex | None = ..., /, ) -> bool: - """ - Return True if the bytes starts with the specified prefix, False otherwise. + """Return True if the bytes starts with the specified prefix, False otherwise. prefix A bytes or a tuple of bytes to try. @@ -2101,31 +1769,27 @@ class bytes(Sequence[int]): """ def strip(self, bytes: ReadableBuffer | None = None, /) -> bytes: - """ - Strip leading and trailing bytes contained in the argument. + """Strip leading and trailing bytes contained in the argument. If the argument is omitted or None, strip leading and trailing ASCII whitespace. """ def swapcase(self) -> bytes: - """ - B.swapcase() -> copy of B + """B.swapcase() -> copy of B Return a copy of B with uppercase ASCII characters converted to lowercase ASCII and vice versa. """ def title(self) -> bytes: - """ - B.title() -> copy of B + """B.title() -> copy of B Return a titlecased version of B, i.e. ASCII words start with uppercase characters, all remaining cased characters have lowercase. """ def translate(self, table: ReadableBuffer | None, /, delete: ReadableBuffer = b"") -> bytes: - """ - Return a copy with each character mapped by the given translation table. + """Return a copy with each character mapped by the given translation table. table Translation table, which must be a bytes object of length 256. @@ -2135,23 +1799,20 @@ class bytes(Sequence[int]): """ def upper(self) -> bytes: - """ - B.upper() -> copy of B + """B.upper() -> copy of B Return a copy of B with all ASCII characters converted to uppercase. """ def zfill(self, width: SupportsIndex, /) -> bytes: - """ - Pad a numeric string with zeros on the left, to fill a field of the given width. + """Pad a numeric string with zeros on the left, to fill a field of the given width. The original string is never truncated. """ @classmethod def fromhex(cls, string: str, /) -> Self: - """ - Create a bytes object from a string of hexadecimal numbers. + """Create a bytes object from a string of hexadecimal numbers. Spaces between two numbers are accepted. Example: bytes.fromhex('B9 01EF') -> b'\\\\xb9\\\\x01\\\\xef'. @@ -2159,8 +1820,7 @@ class bytes(Sequence[int]): @staticmethod def maketrans(frm: ReadableBuffer, to: ReadableBuffer, /) -> bytes: - """ - Return a translation table usable for the bytes or bytearray translate method. + """Return a translation table usable for the bytes or bytearray translate method. The returned table will be one where each byte in frm is mapped to the byte at the same position in to. @@ -2169,48 +1829,32 @@ class bytes(Sequence[int]): """ def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" def __iter__(self) -> Iterator[int]: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __hash__(self) -> int: ... @overload def __getitem__(self, key: SupportsIndex, /) -> int: - """ - Return self[key]. - """ + """Return self[key].""" @overload def __getitem__(self, key: slice, /) -> bytes: ... def __add__(self, value: ReadableBuffer, /) -> bytes: - """ - Return self+value. - """ + """Return self+value.""" def __mul__(self, value: SupportsIndex, /) -> bytes: - """ - Return self*value. - """ + """Return self*value.""" def __rmul__(self, value: SupportsIndex, /) -> bytes: - """ - Return value*self. - """ + """Return value*self.""" def __mod__(self, value: Any, /) -> bytes: - """ - Return self%value. - """ + """Return self%value.""" # Incompatible with Sequence.__contains__ def __contains__(self, key: SupportsIndex | ReadableBuffer, /) -> bool: # type: ignore[override] - """ - Return bool(key in self). - """ + """Return bool(key in self).""" def __eq__(self, value: object, /) -> bool: ... def __ne__(self, value: object, /) -> bool: ... @@ -2221,18 +1865,13 @@ class bytes(Sequence[int]): def __getnewargs__(self) -> tuple[bytes]: ... if sys.version_info >= (3, 11): def __bytes__(self) -> bytes: - """ - Convert this value to exact type bytes. - """ + """Convert this value to exact type bytes.""" def __buffer__(self, flags: int, /) -> memoryview: - """ - Return a buffer object that exposes the underlying memory of the object. - """ + """Return a buffer object that exposes the underlying memory of the object.""" class bytearray(MutableSequence[int]): - """ - bytearray(iterable_of_ints) -> bytearray + """bytearray(iterable_of_ints) -> bytearray bytearray(string, encoding[, errors]) -> bytearray bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer bytearray(int) -> bytes array of size given by the parameter initialized with null bytes @@ -2253,24 +1892,21 @@ class bytearray(MutableSequence[int]): @overload def __init__(self, string: str, /, encoding: str, errors: str = ...) -> None: ... def append(self, item: SupportsIndex, /) -> None: - """ - Append a single item to the end of the bytearray. + """Append a single item to the end of the bytearray. item The item to be appended. """ def capitalize(self) -> bytearray: - """ - B.capitalize() -> copy of B + """B.capitalize() -> copy of B Return a copy of B with only its first character capitalized (ASCII) and the rest lower-cased. """ def center(self, width: SupportsIndex, fillchar: bytes = b" ", /) -> bytearray: - """ - Return a centered string of length width. + """Return a centered string of length width. Padding is done using the specified fill character. """ @@ -2278,8 +1914,7 @@ class bytearray(MutableSequence[int]): def count( self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: - """ - Return the number of non-overlapping occurrences of subsection 'sub' in bytes B[start:end]. + """Return the number of non-overlapping occurrences of subsection 'sub' in bytes B[start:end]. start Optional start position. Default: start of the bytes. @@ -2288,13 +1923,10 @@ class bytearray(MutableSequence[int]): """ def copy(self) -> bytearray: - """ - Return a copy of B. - """ + """Return a copy of B.""" def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: - """ - Decode the bytearray using the codec registered for encoding. + """Decode the bytearray using the codec registered for encoding. encoding The encoding with which to decode the bytearray. @@ -2313,8 +1945,7 @@ class bytearray(MutableSequence[int]): end: SupportsIndex | None = ..., /, ) -> bool: - """ - Return True if the bytearray ends with the specified suffix, False otherwise. + """Return True if the bytearray ends with the specified suffix, False otherwise. suffix A bytes or a tuple of bytes to try. @@ -2325,15 +1956,13 @@ class bytearray(MutableSequence[int]): """ def expandtabs(self, tabsize: SupportsIndex = 8) -> bytearray: - """ - Return a copy where all tab characters are expanded using spaces. + """Return a copy where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. """ def extend(self, iterable_of_ints: Iterable[SupportsIndex], /) -> None: - """ - Append all the items from the iterator or sequence to the end of the bytearray. + """Append all the items from the iterator or sequence to the end of the bytearray. iterable_of_ints The iterable of items to append. @@ -2342,8 +1971,7 @@ class bytearray(MutableSequence[int]): def find( self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: - """ - Return the lowest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end]. + """Return the lowest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end]. start Optional start position. Default: start of the bytes. @@ -2354,8 +1982,7 @@ class bytearray(MutableSequence[int]): """ def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: - """ - Create a string of hexadecimal numbers from a bytearray object. + """Create a string of hexadecimal numbers from a bytearray object. sep An optional single character or byte to separate hex bytes. @@ -2378,8 +2005,7 @@ class bytearray(MutableSequence[int]): def index( self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: - """ - Return the lowest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end]. + """Return the lowest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end]. start Optional start position. Default: start of the bytes. @@ -2390,8 +2016,7 @@ class bytearray(MutableSequence[int]): """ def insert(self, index: SupportsIndex, item: SupportsIndex, /) -> None: - """ - Insert a single item into the bytearray before the given index. + """Insert a single item into the bytearray before the given index. index The index where the value is to be inserted. @@ -2400,56 +2025,49 @@ class bytearray(MutableSequence[int]): """ def isalnum(self) -> bool: - """ - B.isalnum() -> bool + """B.isalnum() -> bool Return True if all characters in B are alphanumeric and there is at least one character in B, False otherwise. """ def isalpha(self) -> bool: - """ - B.isalpha() -> bool + """B.isalpha() -> bool Return True if all characters in B are alphabetic and there is at least one character in B, False otherwise. """ def isascii(self) -> bool: - """ - B.isascii() -> bool + """B.isascii() -> bool Return True if B is empty or all characters in B are ASCII, False otherwise. """ def isdigit(self) -> bool: - """ - B.isdigit() -> bool + """B.isdigit() -> bool Return True if all characters in B are digits and there is at least one character in B, False otherwise. """ def islower(self) -> bool: - """ - B.islower() -> bool + """B.islower() -> bool Return True if all cased characters in B are lowercase and there is at least one cased character in B, False otherwise. """ def isspace(self) -> bool: - """ - B.isspace() -> bool + """B.isspace() -> bool Return True if all characters in B are whitespace and there is at least one character in B, False otherwise. """ def istitle(self) -> bool: - """ - B.istitle() -> bool + """B.istitle() -> bool Return True if B is a titlecased string and there is at least one character in B, i.e. uppercase characters may only follow uncased @@ -2458,16 +2076,14 @@ class bytearray(MutableSequence[int]): """ def isupper(self) -> bool: - """ - B.isupper() -> bool + """B.isupper() -> bool Return True if all cased characters in B are uppercase and there is at least one cased character in B, False otherwise. """ def join(self, iterable_of_bytes: Iterable[ReadableBuffer], /) -> bytearray: - """ - Concatenate any number of bytes/bytearray objects. + """Concatenate any number of bytes/bytearray objects. The bytearray whose method is called is inserted in between each pair. @@ -2475,29 +2091,25 @@ class bytearray(MutableSequence[int]): """ def ljust(self, width: SupportsIndex, fillchar: bytes | bytearray = b" ", /) -> bytearray: - """ - Return a left-justified string of length width. + """Return a left-justified string of length width. Padding is done using the specified fill character. """ def lower(self) -> bytearray: - """ - B.lower() -> copy of B + """B.lower() -> copy of B Return a copy of B with all ASCII characters converted to lowercase. """ def lstrip(self, bytes: ReadableBuffer | None = None, /) -> bytearray: - """ - Strip leading bytes contained in the argument. + """Strip leading bytes contained in the argument. If the argument is omitted or None, strip leading ASCII whitespace. """ def partition(self, sep: ReadableBuffer, /) -> tuple[bytearray, bytearray, bytearray]: - """ - Partition the bytearray into three parts using the given separator. + """Partition the bytearray into three parts using the given separator. This will search for the separator sep in the bytearray. If the separator is found, returns a 3-tuple containing the part before the separator, the @@ -2508,8 +2120,7 @@ class bytearray(MutableSequence[int]): """ def pop(self, index: int = -1, /) -> int: - """ - Remove and return a single item from B. + """Remove and return a single item from B. index The index from where to remove the item. @@ -2519,16 +2130,14 @@ class bytearray(MutableSequence[int]): """ def remove(self, value: int, /) -> None: - """ - Remove the first occurrence of a value in the bytearray. + """Remove the first occurrence of a value in the bytearray. value The value to remove. """ def removeprefix(self, prefix: ReadableBuffer, /) -> bytearray: - """ - Return a bytearray with the given prefix string removed if present. + """Return a bytearray with the given prefix string removed if present. If the bytearray starts with the prefix string, return bytearray[len(prefix):]. Otherwise, return a copy of the original @@ -2536,8 +2145,7 @@ class bytearray(MutableSequence[int]): """ def removesuffix(self, suffix: ReadableBuffer, /) -> bytearray: - """ - Return a bytearray with the given suffix string removed if present. + """Return a bytearray with the given suffix string removed if present. If the bytearray ends with the suffix string and that suffix is not empty, return bytearray[:-len(suffix)]. Otherwise, return a copy of @@ -2545,8 +2153,7 @@ class bytearray(MutableSequence[int]): """ def replace(self, old: ReadableBuffer, new: ReadableBuffer, count: SupportsIndex = -1, /) -> bytearray: - """ - Return a copy with all occurrences of substring old replaced by new. + """Return a copy with all occurrences of substring old replaced by new. count Maximum number of occurrences to replace. @@ -2559,8 +2166,7 @@ class bytearray(MutableSequence[int]): def rfind( self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: - """ - Return the highest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end]. + """Return the highest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end]. start Optional start position. Default: start of the bytes. @@ -2573,8 +2179,7 @@ class bytearray(MutableSequence[int]): def rindex( self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: - """ - Return the highest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end]. + """Return the highest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start:end]. start Optional start position. Default: start of the bytes. @@ -2585,15 +2190,13 @@ class bytearray(MutableSequence[int]): """ def rjust(self, width: SupportsIndex, fillchar: bytes | bytearray = b" ", /) -> bytearray: - """ - Return a right-justified string of length width. + """Return a right-justified string of length width. Padding is done using the specified fill character. """ def rpartition(self, sep: ReadableBuffer, /) -> tuple[bytearray, bytearray, bytearray]: - """ - Partition the bytearray into three parts using the given separator. + """Partition the bytearray into three parts using the given separator. This will search for the separator sep in the bytearray, starting at the end. If the separator is found, returns a 3-tuple containing the part before the @@ -2605,8 +2208,7 @@ class bytearray(MutableSequence[int]): """ def rsplit(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytearray]: - """ - Return a list of the sections in the bytearray, using sep as the delimiter. + """Return a list of the sections in the bytearray, using sep as the delimiter. sep The delimiter according which to split the bytearray. @@ -2620,15 +2222,13 @@ class bytearray(MutableSequence[int]): """ def rstrip(self, bytes: ReadableBuffer | None = None, /) -> bytearray: - """ - Strip trailing bytes contained in the argument. + """Strip trailing bytes contained in the argument. If the argument is omitted or None, strip trailing ASCII whitespace. """ def split(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytearray]: - """ - Return a list of the sections in the bytearray, using sep as the delimiter. + """Return a list of the sections in the bytearray, using sep as the delimiter. sep The delimiter according which to split the bytearray. @@ -2640,8 +2240,7 @@ class bytearray(MutableSequence[int]): """ def splitlines(self, keepends: bool = False) -> list[bytearray]: - """ - Return a list of the lines in the bytearray, breaking at line boundaries. + """Return a list of the lines in the bytearray, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. @@ -2654,8 +2253,7 @@ class bytearray(MutableSequence[int]): end: SupportsIndex | None = ..., /, ) -> bool: - """ - Return True if the bytearray starts with the specified prefix, False otherwise. + """Return True if the bytearray starts with the specified prefix, False otherwise. prefix A bytes or a tuple of bytes to try. @@ -2666,31 +2264,27 @@ class bytearray(MutableSequence[int]): """ def strip(self, bytes: ReadableBuffer | None = None, /) -> bytearray: - """ - Strip leading and trailing bytes contained in the argument. + """Strip leading and trailing bytes contained in the argument. If the argument is omitted or None, strip leading and trailing ASCII whitespace. """ def swapcase(self) -> bytearray: - """ - B.swapcase() -> copy of B + """B.swapcase() -> copy of B Return a copy of B with uppercase ASCII characters converted to lowercase ASCII and vice versa. """ def title(self) -> bytearray: - """ - B.title() -> copy of B + """B.title() -> copy of B Return a titlecased version of B, i.e. ASCII words start with uppercase characters, all remaining cased characters have lowercase. """ def translate(self, table: ReadableBuffer | None, /, delete: bytes = b"") -> bytearray: - """ - Return a copy with each character mapped by the given translation table. + """Return a copy with each character mapped by the given translation table. table Translation table, which must be a bytes object of length 256. @@ -2700,23 +2294,20 @@ class bytearray(MutableSequence[int]): """ def upper(self) -> bytearray: - """ - B.upper() -> copy of B + """B.upper() -> copy of B Return a copy of B with all ASCII characters converted to uppercase. """ def zfill(self, width: SupportsIndex, /) -> bytearray: - """ - Pad a numeric string with zeros on the left, to fill a field of the given width. + """Pad a numeric string with zeros on the left, to fill a field of the given width. The original string is never truncated. """ @classmethod def fromhex(cls, string: str, /) -> Self: - """ - Create a bytearray object from a string of hexadecimal numbers. + """Create a bytearray object from a string of hexadecimal numbers. Spaces between two numbers are accepted. Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\\\xb9\\\\x01\\\\xef') @@ -2724,8 +2315,7 @@ class bytearray(MutableSequence[int]): @staticmethod def maketrans(frm: ReadableBuffer, to: ReadableBuffer, /) -> bytes: - """ - Return a translation table usable for the bytes or bytearray translate method. + """Return a translation table usable for the bytes or bytearray translate method. The returned table will be one where each byte in frm is mapped to the byte at the same position in to. @@ -2734,70 +2324,46 @@ class bytearray(MutableSequence[int]): """ def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" def __iter__(self) -> Iterator[int]: - """ - Implement iter(self). - """ + """Implement iter(self).""" __hash__: ClassVar[None] # type: ignore[assignment] @overload def __getitem__(self, key: SupportsIndex, /) -> int: - """ - Return self[key]. - """ + """Return self[key].""" @overload def __getitem__(self, key: slice, /) -> bytearray: ... @overload def __setitem__(self, key: SupportsIndex, value: SupportsIndex, /) -> None: - """ - Set self[key] to value. - """ + """Set self[key] to value.""" @overload def __setitem__(self, key: slice, value: Iterable[SupportsIndex] | bytes, /) -> None: ... def __delitem__(self, key: SupportsIndex | slice, /) -> None: - """ - Delete self[key]. - """ + """Delete self[key].""" def __add__(self, value: ReadableBuffer, /) -> bytearray: - """ - Return self+value. - """ + """Return self+value.""" # The superclass wants us to accept Iterable[int], but that fails at runtime. def __iadd__(self, value: ReadableBuffer, /) -> Self: # type: ignore[override] - """ - Implement self+=value. - """ + """Implement self+=value.""" def __mul__(self, value: SupportsIndex, /) -> bytearray: - """ - Return self*value. - """ + """Return self*value.""" def __rmul__(self, value: SupportsIndex, /) -> bytearray: - """ - Return value*self. - """ + """Return value*self.""" def __imul__(self, value: SupportsIndex, /) -> Self: - """ - Implement self*=value. - """ + """Implement self*=value.""" def __mod__(self, value: Any, /) -> bytes: - """ - Return self%value. - """ + """Return self%value.""" # Incompatible with Sequence.__contains__ def __contains__(self, key: SupportsIndex | ReadableBuffer, /) -> bool: # type: ignore[override] - """ - Return bool(key in self). - """ + """Return bool(key in self).""" def __eq__(self, value: object, /) -> bool: ... def __ne__(self, value: object, /) -> bool: ... @@ -2806,25 +2372,19 @@ class bytearray(MutableSequence[int]): def __gt__(self, value: ReadableBuffer, /) -> bool: ... def __ge__(self, value: ReadableBuffer, /) -> bool: ... def __alloc__(self) -> int: - """ - B.__alloc__() -> int + """B.__alloc__() -> int Return the number of bytes actually allocated. """ def __buffer__(self, flags: int, /) -> memoryview: - """ - Return a buffer object that exposes the underlying memory of the object. - """ + """Return a buffer object that exposes the underlying memory of the object.""" def __release_buffer__(self, buffer: memoryview, /) -> None: - """ - Release the buffer object that exposes the underlying memory of the object. - """ + """Release the buffer object that exposes the underlying memory of the object.""" if sys.version_info >= (3, 14): def resize(self, size: int, /) -> None: - """ - Resize the internal buffer of bytearray to len. + """Resize the internal buffer of bytearray to len. size New size to resize to.. @@ -2836,84 +2396,63 @@ _IntegerFormats: TypeAlias = Literal[ @final class memoryview(Sequence[_I]): - """ - Create a new memoryview object which references the given object. - """ + """Create a new memoryview object which references the given object.""" @property def format(self) -> str: - """ - A string containing the format (in struct module style) + """A string containing the format (in struct module style) for each element in the view. """ @property def itemsize(self) -> int: - """ - The size in bytes of each element of the memoryview. - """ + """The size in bytes of each element of the memoryview.""" @property def shape(self) -> tuple[int, ...] | None: - """ - A tuple of ndim integers giving the shape of the memory + """A tuple of ndim integers giving the shape of the memory as an N-dimensional array. """ @property def strides(self) -> tuple[int, ...] | None: - """ - A tuple of ndim integers giving the size in bytes to access + """A tuple of ndim integers giving the size in bytes to access each element for each dimension of the array. """ @property def suboffsets(self) -> tuple[int, ...] | None: - """ - A tuple of integers used internally for PIL-style arrays. - """ + """A tuple of integers used internally for PIL-style arrays.""" @property def readonly(self) -> bool: - """ - A bool indicating whether the memory is read only. - """ + """A bool indicating whether the memory is read only.""" @property def ndim(self) -> int: - """ - An integer indicating how many dimensions of a multi-dimensional + """An integer indicating how many dimensions of a multi-dimensional array the memory represents. """ @property def obj(self) -> ReadableBuffer: - """ - The underlying object of the memoryview. - """ + """The underlying object of the memoryview.""" @property def c_contiguous(self) -> bool: - """ - A bool indicating whether the memory is C contiguous. - """ + """A bool indicating whether the memory is C contiguous.""" @property def f_contiguous(self) -> bool: - """ - A bool indicating whether the memory is Fortran contiguous. - """ + """A bool indicating whether the memory is Fortran contiguous.""" @property def contiguous(self) -> bool: - """ - A bool indicating whether the memory is contiguous. - """ + """A bool indicating whether the memory is contiguous.""" @property def nbytes(self) -> int: - """ - The amount of space in bytes that the array would use in + """The amount of space in bytes that the array would use in a contiguous representation. """ @@ -2926,15 +2465,11 @@ class memoryview(Sequence[_I]): exc_tb: TracebackType | None, /, ) -> None: - """ - Release the underlying buffer exposed by the memoryview object. - """ + """Release the underlying buffer exposed by the memoryview object.""" @overload def cast(self, format: Literal["c", "@c"], shape: list[int] | tuple[int, ...] = ...) -> memoryview[bytes]: - """ - Cast a memoryview to a new format or shape. - """ + """Cast a memoryview to a new format or shape.""" @overload def cast(self, format: Literal["f", "@f", "d", "@d"], shape: list[int] | tuple[int, ...] = ...) -> memoryview[float]: ... @@ -2944,37 +2479,28 @@ class memoryview(Sequence[_I]): def cast(self, format: _IntegerFormats, shape: list[int] | tuple[int, ...] = ...) -> memoryview: ... @overload def __getitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...], /) -> _I: - """ - Return self[key]. - """ + """Return self[key].""" @overload def __getitem__(self, key: slice, /) -> memoryview[_I]: ... def __contains__(self, x: object, /) -> bool: ... def __iter__(self) -> Iterator[_I]: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... @overload def __setitem__(self, key: slice, value: ReadableBuffer, /) -> None: - """ - Set self[key] to value. - """ + """Set self[key] to value.""" @overload def __setitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...], value: _I, /) -> None: ... if sys.version_info >= (3, 10): def tobytes(self, order: Literal["C", "F", "A"] | None = "C") -> bytes: - """ - Return the data in the buffer as a byte string. + """Return the data in the buffer as a byte string. Order can be {'C', 'F', 'A'}. When order is 'C' or 'F', the data of the original array is converted to C or Fortran order. For contiguous views, @@ -2984,8 +2510,7 @@ class memoryview(Sequence[_I]): """ else: def tobytes(self, order: Literal["C", "F", "A"] | None = None) -> bytes: - """ - Return the data in the buffer as a byte string. + """Return the data in the buffer as a byte string. Order can be {'C', 'F', 'A'}. When order is 'C' or 'F', the data of the original array is converted to C or Fortran order. For contiguous views, @@ -2995,23 +2520,16 @@ class memoryview(Sequence[_I]): """ def tolist(self) -> list[int]: - """ - Return the data in the buffer as a list of elements. - """ + """Return the data in the buffer as a list of elements.""" def toreadonly(self) -> memoryview: - """ - Return a readonly version of the memoryview. - """ + """Return a readonly version of the memoryview.""" def release(self) -> None: - """ - Release the underlying buffer exposed by the memoryview object. - """ + """Release the underlying buffer exposed by the memoryview object.""" def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: - """ - Return the data in the buffer as a str of hexadecimal numbers. + """Return the data in the buffer as a str of hexadecimal numbers. sep An optional single character or byte to separate hex bytes. @@ -3032,28 +2550,21 @@ class memoryview(Sequence[_I]): """ def __buffer__(self, flags: int, /) -> memoryview: - """ - Return a buffer object that exposes the underlying memory of the object. - """ + """Return a buffer object that exposes the underlying memory of the object.""" def __release_buffer__(self, buffer: memoryview, /) -> None: - """ - Release the buffer object that exposes the underlying memory of the object. - """ + """Release the buffer object that exposes the underlying memory of the object.""" # These are inherited from the Sequence ABC, but don't actually exist on memoryview. # See https://github.com/python/cpython/issues/125420 index: ClassVar[None] # type: ignore[assignment] count: ClassVar[None] # type: ignore[assignment] if sys.version_info >= (3, 14): def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" @final class bool(int): - """ - Returns True when the argument is true, False otherwise. + """Returns True when the argument is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed. """ @@ -3063,63 +2574,48 @@ class bool(int): # however mypy has a bug regarding TypeVar constraints (https://github.com/python/mypy/issues/11880). @overload def __and__(self, value: bool, /) -> bool: - """ - Return self&value. - """ + """Return self&value.""" @overload def __and__(self, value: int, /) -> int: ... @overload def __or__(self, value: bool, /) -> bool: - """ - Return self|value. - """ + """Return self|value.""" @overload def __or__(self, value: int, /) -> int: ... @overload def __xor__(self, value: bool, /) -> bool: - """ - Return self^value. - """ + """Return self^value.""" @overload def __xor__(self, value: int, /) -> int: ... @overload def __rand__(self, value: bool, /) -> bool: - """ - Return value&self. - """ + """Return value&self.""" @overload def __rand__(self, value: int, /) -> int: ... @overload def __ror__(self, value: bool, /) -> bool: - """ - Return value|self. - """ + """Return value|self.""" @overload def __ror__(self, value: int, /) -> int: ... @overload def __rxor__(self, value: bool, /) -> bool: - """ - Return value^self. - """ + """Return value^self.""" @overload def __rxor__(self, value: int, /) -> int: ... def __getnewargs__(self) -> tuple[int]: ... @deprecated("Will throw an error in Python 3.16. Use `not` for logical negation of bools instead.") def __invert__(self) -> int: - """ - ~self - """ + """~self""" @final class slice(Generic[_StartT_co, _StopT_co, _StepT_co]): - """ - slice(stop) + """slice(stop) slice(start, stop[, step]) Create a slice object. This is used for extended slicing (e.g. a[0:10:2]). @@ -3162,8 +2658,7 @@ class slice(Generic[_StartT_co, _StopT_co, _StepT_co]): __hash__: ClassVar[None] # type: ignore[assignment] def indices(self, len: SupportsIndex, /) -> tuple[int, int, int]: - """ - S.indices(len) -> (start, stop, stride) + """S.indices(len) -> (start, stop, stride) Assuming a sequence of length len, calculate the start and stop indices, and the stride length of the extended slice described by @@ -3172,8 +2667,7 @@ class slice(Generic[_StartT_co, _StopT_co, _StepT_co]): """ class tuple(Sequence[_T_co]): - """ - Built-in immutable sequence. + """Built-in immutable sequence. If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items. @@ -3183,27 +2677,19 @@ class tuple(Sequence[_T_co]): def __new__(cls, iterable: Iterable[_T_co] = ..., /) -> Self: ... def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" def __contains__(self, key: object, /) -> bool: - """ - Return bool(key in self). - """ + """Return bool(key in self).""" @overload def __getitem__(self, key: SupportsIndex, /) -> _T_co: - """ - Return self[key]. - """ + """Return self[key].""" @overload def __getitem__(self, key: slice, /) -> tuple[_T_co, ...]: ... def __iter__(self) -> Iterator[_T_co]: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __lt__(self, value: tuple[_T_co, ...], /) -> bool: ... def __le__(self, value: tuple[_T_co, ...], /) -> bool: ... @@ -3213,38 +2699,27 @@ class tuple(Sequence[_T_co]): def __hash__(self) -> int: ... @overload def __add__(self, value: tuple[_T_co, ...], /) -> tuple[_T_co, ...]: - """ - Return self+value. - """ + """Return self+value.""" @overload def __add__(self, value: tuple[_T, ...], /) -> tuple[_T_co | _T, ...]: ... def __mul__(self, value: SupportsIndex, /) -> tuple[_T_co, ...]: - """ - Return self*value. - """ + """Return self*value.""" def __rmul__(self, value: SupportsIndex, /) -> tuple[_T_co, ...]: - """ - Return value*self. - """ + """Return value*self.""" def count(self, value: Any, /) -> int: - """ - Return number of occurrences of value. - """ + """Return number of occurrences of value.""" def index(self, value: Any, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: - """ - Return first index of value. + """Return first index of value. Raises ValueError if the value is not present. """ def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" # Doesn't exist at runtime, but deleting this breaks mypy and pyright. See: # https://github.com/python/typeshed/issues/7580 @@ -3298,8 +2773,7 @@ class function: def __get__(self, instance: object, owner: type | None = None, /) -> Any: ... class list(MutableSequence[_T]): - """ - Built-in mutable sequence. + """Built-in mutable sequence. If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified. @@ -3310,48 +2784,35 @@ class list(MutableSequence[_T]): @overload def __init__(self, iterable: Iterable[_T], /) -> None: ... def copy(self) -> list[_T]: - """ - Return a shallow copy of the list. - """ + """Return a shallow copy of the list.""" def append(self, object: _T, /) -> None: - """ - Append object to the end of the list. - """ + """Append object to the end of the list.""" def extend(self, iterable: Iterable[_T], /) -> None: - """ - Extend list by appending elements from the iterable. - """ + """Extend list by appending elements from the iterable.""" def pop(self, index: SupportsIndex = -1, /) -> _T: - """ - Remove and return item at index (default last). + """Remove and return item at index (default last). Raises IndexError if list is empty or index is out of range. """ # Signature of `list.index` should be kept in line with `collections.UserList.index()` # and multiprocessing.managers.ListProxy.index() def index(self, value: _T, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: - """ - Return first index of value. + """Return first index of value. Raises ValueError if the value is not present. """ def count(self, value: _T, /) -> int: - """ - Return number of occurrences of value. - """ + """Return number of occurrences of value.""" def insert(self, index: SupportsIndex, object: _T, /) -> None: - """ - Insert object before index. - """ + """Insert object before index.""" def remove(self, value: _T, /) -> None: - """ - Remove first occurrence of value. + """Remove first occurrence of value. Raises ValueError if the value is not present. """ @@ -3362,8 +2823,7 @@ class list(MutableSequence[_T]): # to work around invariance @overload def sort(self: list[SupportsRichComparisonT], *, key: None = None, reverse: bool = False) -> None: - """ - Sort the list in ascending order and return None. + """Sort the list in ascending order and return None. The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained). @@ -3377,73 +2837,49 @@ class list(MutableSequence[_T]): @overload def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> None: ... def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" def __iter__(self) -> Iterator[_T]: - """ - Implement iter(self). - """ + """Implement iter(self).""" __hash__: ClassVar[None] # type: ignore[assignment] @overload def __getitem__(self, i: SupportsIndex, /) -> _T: - """ - Return self[index]. - """ + """Return self[index].""" @overload def __getitem__(self, s: slice, /) -> list[_T]: ... @overload def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: - """ - Set self[key] to value. - """ + """Set self[key] to value.""" @overload def __setitem__(self, key: slice, value: Iterable[_T], /) -> None: ... def __delitem__(self, key: SupportsIndex | slice, /) -> None: - """ - Delete self[key]. - """ + """Delete self[key].""" # Overloading looks unnecessary, but is needed to work around complex mypy problems @overload def __add__(self, value: list[_T], /) -> list[_T]: - """ - Return self+value. - """ + """Return self+value.""" @overload def __add__(self, value: list[_S], /) -> list[_S | _T]: ... def __iadd__(self, value: Iterable[_T], /) -> Self: # type: ignore[misc] - """ - Implement self+=value. - """ + """Implement self+=value.""" def __mul__(self, value: SupportsIndex, /) -> list[_T]: - """ - Return self*value. - """ + """Return self*value.""" def __rmul__(self, value: SupportsIndex, /) -> list[_T]: - """ - Return value*self. - """ + """Return value*self.""" def __imul__(self, value: SupportsIndex, /) -> Self: - """ - Implement self*=value. - """ + """Implement self*=value.""" def __contains__(self, key: object, /) -> bool: - """ - Return bool(key in self). - """ + """Return bool(key in self).""" def __reversed__(self) -> Iterator[_T]: - """ - Return a reverse iterator over the list. - """ + """Return a reverse iterator over the list.""" def __gt__(self, value: list[_T], /) -> bool: ... def __ge__(self, value: list[_T], /) -> bool: ... @@ -3451,13 +2887,10 @@ class list(MutableSequence[_T]): def __le__(self, value: list[_T], /) -> bool: ... def __eq__(self, value: object, /) -> bool: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" class dict(MutableMapping[_KT, _VT]): - """ - dict() -> new empty dictionary + """dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: @@ -3500,24 +2933,16 @@ class dict(MutableMapping[_KT, _VT]): def __init__(self: dict[bytes, bytes], iterable: Iterable[list[bytes]], /) -> None: ... def __new__(cls, *args: Any, **kwargs: Any) -> Self: ... def copy(self) -> dict[_KT, _VT]: - """ - Return a shallow copy of the dict. - """ + """Return a shallow copy of the dict.""" def keys(self) -> dict_keys[_KT, _VT]: - """ - Return a set-like object providing a view on the dict's keys. - """ + """Return a set-like object providing a view on the dict's keys.""" def values(self) -> dict_values[_KT, _VT]: - """ - Return an object providing a view on the dict's values. - """ + """Return an object providing a view on the dict's values.""" def items(self) -> dict_items[_KT, _VT]: - """ - Return a set-like object providing a view on the dict's items. - """ + """Return a set-like object providing a view on the dict's items.""" # Signature of `dict.fromkeys` should be kept identical to # `fromkeys` methods of `OrderedDict`/`ChainMap`/`UserDict` in `collections` # TODO: the true signature of `dict.fromkeys` is not expressible in the current type system. @@ -3525,9 +2950,7 @@ class dict(MutableMapping[_KT, _VT]): @classmethod @overload def fromkeys(cls, iterable: Iterable[_T], value: None = None, /) -> dict[_T, Any | None]: - """ - Create a new dictionary with keys from iterable and values set to value. - """ + """Create a new dictionary with keys from iterable and values set to value.""" @classmethod @overload @@ -3535,9 +2958,7 @@ class dict(MutableMapping[_KT, _VT]): # Positional-only in dict, but not in MutableMapping @overload # type: ignore[override] def get(self, key: _KT, default: None = None, /) -> _VT | None: - """ - Return the value for key if key is in the dictionary, else default. - """ + """Return the value for key if key is in the dictionary, else default.""" @overload def get(self, key: _KT, default: _VT, /) -> _VT: ... @@ -3545,8 +2966,7 @@ class dict(MutableMapping[_KT, _VT]): def get(self, key: _KT, default: _T, /) -> _VT | _T: ... @overload def pop(self, key: _KT, /) -> _VT: - """ - D.pop(k[,d]) -> v, remove specified key and return the corresponding value. + """D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If the key is not found, return the default if given; otherwise, raise a KeyError. @@ -3557,212 +2977,141 @@ class dict(MutableMapping[_KT, _VT]): @overload def pop(self, key: _KT, default: _T, /) -> _VT | _T: ... def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" def __getitem__(self, key: _KT, /) -> _VT: - """ - Return self[key]. - """ + """Return self[key].""" def __setitem__(self, key: _KT, value: _VT, /) -> None: - """ - Set self[key] to value. - """ + """Set self[key] to value.""" def __delitem__(self, key: _KT, /) -> None: - """ - Delete self[key]. - """ + """Delete self[key].""" def __iter__(self) -> Iterator[_KT]: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __eq__(self, value: object, /) -> bool: ... def __reversed__(self) -> Iterator[_KT]: - """ - Return a reverse iterator over the dict keys. - """ + """Return a reverse iterator over the dict keys.""" __hash__: ClassVar[None] # type: ignore[assignment] def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" @overload def __or__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: - """ - Return self|value. - """ + """Return self|value.""" @overload def __or__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... @overload def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: - """ - Return value|self. - """ + """Return value|self.""" @overload def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... # dict.__ior__ should be kept roughly in line with MutableMapping.update() @overload # type: ignore[misc] def __ior__(self, value: SupportsKeysAndGetItem[_KT, _VT], /) -> Self: - """ - Return self|=value. - """ + """Return self|=value.""" @overload def __ior__(self, value: Iterable[tuple[_KT, _VT]], /) -> Self: ... class set(MutableSet[_T]): - """ - Build an unordered collection of unique elements. - """ + """Build an unordered collection of unique elements.""" @overload def __init__(self) -> None: ... @overload def __init__(self, iterable: Iterable[_T], /) -> None: ... def add(self, element: _T, /) -> None: - """ - Add an element to a set. + """Add an element to a set. This has no effect if the element is already present. """ def copy(self) -> set[_T]: - """ - Return a shallow copy of a set. - """ + """Return a shallow copy of a set.""" def difference(self, *s: Iterable[Any]) -> set[_T]: - """ - Return a new set with elements in the set that are not in the others. - """ + """Return a new set with elements in the set that are not in the others.""" def difference_update(self, *s: Iterable[Any]) -> None: - """ - Update the set, removing elements found in others. - """ + """Update the set, removing elements found in others.""" def discard(self, element: _T, /) -> None: - """ - Remove an element from a set if it is a member. + """Remove an element from a set if it is a member. Unlike set.remove(), the discard() method does not raise an exception when an element is missing from the set. """ def intersection(self, *s: Iterable[Any]) -> set[_T]: - """ - Return a new set with elements common to the set and all others. - """ + """Return a new set with elements common to the set and all others.""" def intersection_update(self, *s: Iterable[Any]) -> None: - """ - Update the set, keeping only elements found in it and all others. - """ + """Update the set, keeping only elements found in it and all others.""" def isdisjoint(self, s: Iterable[Any], /) -> bool: - """ - Return True if two sets have a null intersection. - """ + """Return True if two sets have a null intersection.""" def issubset(self, s: Iterable[Any], /) -> bool: - """ - Report whether another set contains this set. - """ + """Report whether another set contains this set.""" def issuperset(self, s: Iterable[Any], /) -> bool: - """ - Report whether this set contains another set. - """ + """Report whether this set contains another set.""" def remove(self, element: _T, /) -> None: - """ - Remove an element from a set; it must be a member. + """Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. """ def symmetric_difference(self, s: Iterable[_T], /) -> set[_T]: - """ - Return a new set with elements in either the set or other but not both. - """ + """Return a new set with elements in either the set or other but not both.""" def symmetric_difference_update(self, s: Iterable[_T], /) -> None: - """ - Update the set, keeping only elements found in either set, but not in both. - """ + """Update the set, keeping only elements found in either set, but not in both.""" def union(self, *s: Iterable[_S]) -> set[_T | _S]: - """ - Return a new set with elements from the set and all others. - """ + """Return a new set with elements from the set and all others.""" def update(self, *s: Iterable[_T]) -> None: - """ - Update the set, adding elements from all others. - """ + """Update the set, adding elements from all others.""" def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" def __contains__(self, o: object, /) -> bool: - """ - x.__contains__(y) <==> y in x. - """ + """x.__contains__(y) <==> y in x.""" def __iter__(self) -> Iterator[_T]: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __and__(self, value: AbstractSet[object], /) -> set[_T]: - """ - Return self&value. - """ + """Return self&value.""" def __iand__(self, value: AbstractSet[object], /) -> Self: - """ - Return self&=value. - """ + """Return self&=value.""" def __or__(self, value: AbstractSet[_S], /) -> set[_T | _S]: - """ - Return self|value. - """ + """Return self|value.""" def __ior__(self, value: AbstractSet[_T], /) -> Self: # type: ignore[override,misc] - """ - Return self|=value. - """ + """Return self|=value.""" def __sub__(self, value: AbstractSet[_T | None], /) -> set[_T]: - """ - Return self-value. - """ + """Return self-value.""" def __isub__(self, value: AbstractSet[object], /) -> Self: - """ - Return self-=value. - """ + """Return self-=value.""" def __xor__(self, value: AbstractSet[_S], /) -> set[_T | _S]: - """ - Return self^value. - """ + """Return self^value.""" def __ixor__(self, value: AbstractSet[_T], /) -> Self: # type: ignore[override,misc] - """ - Return self^=value. - """ + """Return self^=value.""" def __le__(self, value: AbstractSet[object], /) -> bool: ... def __lt__(self, value: AbstractSet[object], /) -> bool: ... @@ -3771,93 +3120,59 @@ class set(MutableSet[_T]): def __eq__(self, value: object, /) -> bool: ... __hash__: ClassVar[None] # type: ignore[assignment] def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" class frozenset(AbstractSet[_T_co]): - """ - Build an immutable unordered collection of unique elements. - """ + """Build an immutable unordered collection of unique elements.""" @overload def __new__(cls) -> Self: ... @overload def __new__(cls, iterable: Iterable[_T_co], /) -> Self: ... def copy(self) -> frozenset[_T_co]: - """ - Return a shallow copy of a set. - """ + """Return a shallow copy of a set.""" def difference(self, *s: Iterable[object]) -> frozenset[_T_co]: - """ - Return a new set with elements in the set that are not in the others. - """ + """Return a new set with elements in the set that are not in the others.""" def intersection(self, *s: Iterable[object]) -> frozenset[_T_co]: - """ - Return a new set with elements common to the set and all others. - """ + """Return a new set with elements common to the set and all others.""" def isdisjoint(self, s: Iterable[_T_co], /) -> bool: - """ - Return True if two sets have a null intersection. - """ + """Return True if two sets have a null intersection.""" def issubset(self, s: Iterable[object], /) -> bool: - """ - Report whether another set contains this set. - """ + """Report whether another set contains this set.""" def issuperset(self, s: Iterable[object], /) -> bool: - """ - Report whether this set contains another set. - """ + """Report whether this set contains another set.""" def symmetric_difference(self, s: Iterable[_T_co], /) -> frozenset[_T_co]: - """ - Return a new set with elements in either the set or other but not both. - """ + """Return a new set with elements in either the set or other but not both.""" def union(self, *s: Iterable[_S]) -> frozenset[_T_co | _S]: - """ - Return a new set with elements from the set and all others. - """ + """Return a new set with elements from the set and all others.""" def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" def __contains__(self, o: object, /) -> bool: - """ - x.__contains__(y) <==> y in x. - """ + """x.__contains__(y) <==> y in x.""" def __iter__(self) -> Iterator[_T_co]: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __and__(self, value: AbstractSet[_T_co], /) -> frozenset[_T_co]: - """ - Return self&value. - """ + """Return self&value.""" def __or__(self, value: AbstractSet[_S], /) -> frozenset[_T_co | _S]: - """ - Return self|value. - """ + """Return self|value.""" def __sub__(self, value: AbstractSet[_T_co], /) -> frozenset[_T_co]: - """ - Return self-value. - """ + """Return self-value.""" def __xor__(self, value: AbstractSet[_S], /) -> frozenset[_T_co | _S]: - """ - Return self^value. - """ + """Return self^value.""" def __le__(self, value: AbstractSet[object], /) -> bool: ... def __lt__(self, value: AbstractSet[object], /) -> bool: ... @@ -3866,13 +3181,10 @@ class frozenset(AbstractSet[_T_co]): def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" class enumerate(Generic[_T]): - """ - Return an enumerate object. + """Return an enumerate object. iterable an object supporting iteration @@ -3886,24 +3198,17 @@ class enumerate(Generic[_T]): def __new__(cls, iterable: Iterable[_T], start: int = 0) -> Self: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> tuple[int, _T]: - """ - Implement next(self). - """ + """Implement next(self).""" def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" @final class range(Sequence[int]): - """ - range(stop) -> range object + """range(stop) -> range object range(start, stop[, step]) -> range object Return an object that produces a sequence of integers from start (inclusive) @@ -3924,49 +3229,35 @@ class range(Sequence[int]): @overload def __new__(cls, start: SupportsIndex, stop: SupportsIndex, step: SupportsIndex = ..., /) -> Self: ... def count(self, value: int, /) -> int: - """ - rangeobject.count(value) -> integer -- return number of occurrences of value - """ + """rangeobject.count(value) -> integer -- return number of occurrences of value""" def index(self, value: int, /) -> int: # type: ignore[override] - """ - rangeobject.index(value) -> integer -- return index of value. + """rangeobject.index(value) -> integer -- return index of value. Raise ValueError if the value is not present. """ def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... def __contains__(self, key: object, /) -> bool: - """ - Return bool(key in self). - """ + """Return bool(key in self).""" def __iter__(self) -> Iterator[int]: - """ - Implement iter(self). - """ + """Implement iter(self).""" @overload def __getitem__(self, key: SupportsIndex, /) -> int: - """ - Return self[key]. - """ + """Return self[key].""" @overload def __getitem__(self, key: slice, /) -> range: ... def __reversed__(self) -> Iterator[int]: - """ - Return a reverse iterator. - """ + """Return a reverse iterator.""" class property: - """ - Property attribute. + """Property attribute. fget function to be used for getting an attribute value @@ -4015,37 +3306,25 @@ class property: doc: str | None = ..., ) -> None: ... def getter(self, fget: Callable[[Any], Any], /) -> property: - """ - Descriptor to obtain a copy of the property with a different getter. - """ + """Descriptor to obtain a copy of the property with a different getter.""" def setter(self, fset: Callable[[Any, Any], None], /) -> property: - """ - Descriptor to obtain a copy of the property with a different setter. - """ + """Descriptor to obtain a copy of the property with a different setter.""" def deleter(self, fdel: Callable[[Any], None], /) -> property: - """ - Descriptor to obtain a copy of the property with a different deleter. - """ + """Descriptor to obtain a copy of the property with a different deleter.""" @overload def __get__(self, instance: None, owner: type, /) -> Self: - """ - Return an attribute of instance, which is of type owner. - """ + """Return an attribute of instance, which is of type owner.""" @overload def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... def __set__(self, instance: Any, value: Any, /) -> None: - """ - Set an attribute of instance to value. - """ + """Set an attribute of instance to value.""" def __delete__(self, instance: Any, /) -> None: - """ - Delete an attribute of instance. - """ + """Delete an attribute of instance.""" @final class _NotImplementedType(Any): @@ -4054,27 +3333,22 @@ class _NotImplementedType(Any): NotImplemented: _NotImplementedType def abs(x: SupportsAbs[_T], /) -> _T: - """ - Return the absolute value of the argument. - """ + """Return the absolute value of the argument.""" def all(iterable: Iterable[object], /) -> bool: - """ - Return True if bool(x) is True for all values x in the iterable. + """Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True. """ def any(iterable: Iterable[object], /) -> bool: - """ - Return True if bool(x) is True for any x in the iterable. + """Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False. """ def ascii(obj: object, /) -> str: - """ - Return an ASCII-only representation of an object. + """Return an ASCII-only representation of an object. As repr(), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by @@ -4083,39 +3357,32 @@ def ascii(obj: object, /) -> str: """ def bin(number: int | SupportsIndex, /) -> str: - """ - Return the binary representation of an integer. + """Return the binary representation of an integer. >>> bin(2796202) '0b1010101010101010101010' """ def breakpoint(*args: Any, **kws: Any) -> None: - """ - Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept + """Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept whatever arguments are passed. By default, this drops you into the pdb debugger. """ def callable(obj: object, /) -> TypeIs[Callable[..., object]]: - """ - Return whether the object is callable (i.e., some kind of function). + """Return whether the object is callable (i.e., some kind of function). Note that classes are callable, as are instances of classes with a __call__() method. """ def chr(i: int | SupportsIndex, /) -> str: - """ - Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. - """ + """Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.""" if sys.version_info >= (3, 10): def aiter(async_iterable: SupportsAiter[_SupportsAnextT_co], /) -> _SupportsAnextT_co: - """ - Return an AsyncIterator for an AsyncIterable object. - """ + """Return an AsyncIterator for an AsyncIterable object.""" class _SupportsSynchronousAnext(Protocol[_AwaitableT_co]): def __anext__(self) -> _AwaitableT_co: ... @@ -4125,8 +3392,7 @@ if sys.version_info >= (3, 10): # `anext` is just a passthrough for `obj.__anext__` # See discussion in #7491 and pure-Python implementation of `anext` at https://github.com/python/cpython/blob/ea786a882b9ed4261eafabad6011bc7ef3b5bf94/Lib/test/test_asyncgen.py#L52-L80 def anext(i: _SupportsSynchronousAnext[_AwaitableT], /) -> _AwaitableT: - """ - Return the next item from the async iterator. + """Return the next item from the async iterator. If default is given and the async iterator is exhausted, it is returned instead of raising StopAsyncIteration. @@ -4149,8 +3415,7 @@ def compile( *, _feature_version: int = -1, ) -> CodeType: - """ - Compile source into a code object that can be executed by exec() or eval(). + """Compile source into a code object that can be executed by exec() or eval(). The source code may represent a Python module, statement or expression. The filename will be used for run-time error messages. @@ -4201,15 +3466,13 @@ copyright: _sitebuiltins._Printer credits: _sitebuiltins._Printer def delattr(obj: object, name: str, /) -> None: - """ - Deletes the named attribute from the given object. + """Deletes the named attribute from the given object. delattr(x, 'y') is equivalent to ``del x.y`` """ def dir(o: object = ..., /) -> list[str]: - """ - dir([object]) -> list of strings + """dir([object]) -> list of strings If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprising (some of) the attributes @@ -4225,9 +3488,7 @@ def dir(o: object = ..., /) -> list[str]: @overload def divmod(x: SupportsDivMod[_T_contra, _T_co], y: _T_contra, /) -> _T_co: - """ - Return the tuple (x//y, x%y). Invariant: div*y + mod == x. - """ + """Return the tuple (x//y, x%y). Invariant: div*y + mod == x.""" @overload def divmod(x: _T_contra, y: SupportsRDivMod[_T_contra, _T_co], /) -> _T_co: ... @@ -4241,8 +3502,7 @@ if sys.version_info >= (3, 13): globals: dict[str, Any] | None = None, locals: Mapping[str, object] | None = None, ) -> Any: - """ - Evaluate the given source in the context of globals and locals. + """Evaluate the given source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). @@ -4258,8 +3518,7 @@ else: locals: Mapping[str, object] | None = None, /, ) -> Any: - """ - Evaluate the given source in the context of globals and locals. + """Evaluate the given source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). @@ -4278,8 +3537,7 @@ if sys.version_info >= (3, 13): *, closure: tuple[CellType, ...] | None = None, ) -> None: - """ - Execute the given source in the context of globals and locals. + """Execute the given source in the context of globals and locals. The source may be a string representing one or more Python statements or a code object as returned by compile(). @@ -4299,8 +3557,7 @@ elif sys.version_info >= (3, 11): *, closure: tuple[CellType, ...] | None = None, ) -> None: - """ - Execute the given source in the context of globals and locals. + """Execute the given source in the context of globals and locals. The source may be a string representing one or more Python statements or a code object as returned by compile(). @@ -4318,8 +3575,7 @@ else: locals: Mapping[str, object] | None = None, /, ) -> None: - """ - Execute the given source in the context of globals and locals. + """Execute the given source in the context of globals and locals. The source may be a string representing one or more Python statements or a code object as returned by compile(). @@ -4331,8 +3587,7 @@ else: exit: _sitebuiltins.Quitter class filter(Generic[_T]): - """ - Return an iterator yielding those items of iterable for which function(item) + """Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true. """ @@ -4345,18 +3600,13 @@ class filter(Generic[_T]): @overload def __new__(cls, function: Callable[[_T], Any], iterable: Iterable[_T], /) -> Self: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> _T: - """ - Implement next(self). - """ + """Implement next(self).""" def format(value: object, format_spec: str = "", /) -> str: - """ - Return type(value).__format__(value, format_spec) + """Return type(value).__format__(value, format_spec) Many built-in types implement format_spec according to the Format Specification Mini-language. See help('FORMATTING'). @@ -4368,8 +3618,7 @@ def format(value: object, format_spec: str = "", /) -> str: @overload def getattr(o: object, name: str, /) -> Any: - """ - getattr(object, name[, default]) -> value + """getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't @@ -4390,23 +3639,20 @@ def getattr(o: object, name: str, default: dict[Any, Any], /) -> Any | dict[Any, @overload def getattr(o: object, name: str, default: _T, /) -> Any | _T: ... def globals() -> dict[str, Any]: - """ - Return the dictionary containing the current scope's global variables. + """Return the dictionary containing the current scope's global variables. NOTE: Updates to this dictionary *will* affect name lookups in the current global scope and vice-versa. """ def hasattr(obj: object, name: str, /) -> bool: - """ - Return whether the object has an attribute with the given name. + """Return whether the object has an attribute with the given name. This is done by calling getattr(obj, name) and catching AttributeError. """ def hash(obj: object, /) -> int: - """ - Return the hash value for the given object. + """Return the hash value for the given object. Two objects that compare equal must also have the same hash value, but the reverse is not necessarily true. @@ -4415,24 +3661,21 @@ def hash(obj: object, /) -> int: help: _sitebuiltins._Helper def hex(number: int | SupportsIndex, /) -> str: - """ - Return the hexadecimal representation of an integer. + """Return the hexadecimal representation of an integer. >>> hex(12648430) '0xc0ffee' """ def id(obj: object, /) -> int: - """ - Return the identity of an object. + """Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (CPython uses the object's memory address.) """ def input(prompt: object = "", /) -> str: - """ - Read a string from standard input. The trailing newline is stripped. + """Read a string from standard input. The trailing newline is stripped. The prompt string, if given, is printed to standard output without a trailing newline before reading input. @@ -4446,8 +3689,7 @@ class _GetItemIterable(Protocol[_T_co]): @overload def iter(object: SupportsIter[_SupportsNextT_co], /) -> _SupportsNextT_co: - """ - iter(iterable) -> iterator + """iter(iterable) -> iterator iter(callable, sentinel) -> iterator Get an iterator from an object. In the first form, the argument must @@ -4469,8 +3711,7 @@ else: _ClassInfo: TypeAlias = type | tuple[_ClassInfo, ...] def isinstance(obj: object, class_or_tuple: _ClassInfo, /) -> bool: - """ - Return whether an object is an instance of a class or of a subclass thereof. + """Return whether an object is an instance of a class or of a subclass thereof. A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B) @@ -4478,8 +3719,7 @@ def isinstance(obj: object, class_or_tuple: _ClassInfo, /) -> bool: """ def issubclass(cls: type, class_or_tuple: _ClassInfo, /) -> bool: - """ - Return whether 'cls' is derived from another class or is the same class. + """Return whether 'cls' is derived from another class or is the same class. A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B) @@ -4487,15 +3727,12 @@ def issubclass(cls: type, class_or_tuple: _ClassInfo, /) -> bool: """ def len(obj: Sized, /) -> int: - """ - Return the number of items in a container. - """ + """Return the number of items in a container.""" license: _sitebuiltins._Printer def locals() -> dict[str, Any]: - """ - Return a dictionary containing the current scope's local variables. + """Return a dictionary containing the current scope's local variables. NOTE: Whether or not updates to this dictionary will affect name lookups in the local scope and vice-versa is *implementation dependent* and not @@ -4503,8 +3740,7 @@ def locals() -> dict[str, Any]: """ class map(Generic[_S]): - """ - Make an iterator that computes the function using arguments from + """Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted. If strict is true and one of the arguments is exhausted before the others, @@ -4614,21 +3850,16 @@ class map(Generic[_S]): ) -> Self: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> _S: - """ - Implement next(self). - """ + """Implement next(self).""" @overload def max( arg1: SupportsRichComparisonT, arg2: SupportsRichComparisonT, /, *_args: SupportsRichComparisonT, key: None = None ) -> SupportsRichComparisonT: - """ - max(iterable, *[, default=obj, key=func]) -> value + """max(iterable, *[, default=obj, key=func]) -> value max(arg1, arg2, *args, *[, key=func]) -> value With a single iterable argument, return its biggest item. The @@ -4651,8 +3882,7 @@ def max(iterable: Iterable[_T1], /, *, key: Callable[[_T1], SupportsRichComparis def min( arg1: SupportsRichComparisonT, arg2: SupportsRichComparisonT, /, *_args: SupportsRichComparisonT, key: None = None ) -> SupportsRichComparisonT: - """ - min(iterable, *[, default=obj, key=func]) -> value + """min(iterable, *[, default=obj, key=func]) -> value min(arg1, arg2, *args, *[, key=func]) -> value With a single iterable argument, return its smallest item. The @@ -4673,8 +3903,7 @@ def min(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, def def min(iterable: Iterable[_T1], /, *, key: Callable[[_T1], SupportsRichComparison], default: _T2) -> _T1 | _T2: ... @overload def next(i: SupportsNext[_T], /) -> _T: - """ - next(iterator[, default]) + """next(iterator[, default]) Return the next item from the iterator. If default is given and the iterator is exhausted, it is returned instead of raising StopIteration. @@ -4683,8 +3912,7 @@ def next(i: SupportsNext[_T], /) -> _T: @overload def next(i: SupportsNext[_T], default: _VT, /) -> _T | _VT: ... def oct(number: int | SupportsIndex, /) -> str: - """ - Return the octal representation of an integer. + """Return the octal representation of an integer. >>> oct(342391) '0o1234567' @@ -4704,8 +3932,7 @@ def open( closefd: bool = True, opener: _Opener | None = None, ) -> TextIOWrapper: - """ - Open file and return a stream. Raise OSError upon failure. + """Open file and return a stream. Raise OSError upon failure. file is either a text or byte string giving the name (and the path if the file isn't in the current working directory) of the file to @@ -4894,9 +4121,7 @@ def open( opener: _Opener | None = None, ) -> IO[Any]: ... def ord(c: str | bytes | bytearray, /) -> int: - """ - Return the Unicode code point for a one-character string. - """ + """Return the Unicode code point for a one-character string.""" class _SupportsWriteAndFlush(SupportsWrite[_T_contra], SupportsFlush, Protocol[_T_contra]): ... @@ -4908,8 +4133,7 @@ def print( file: SupportsWrite[str] | None = None, flush: Literal[False] = False, ) -> None: - """ - Prints the values to a stream, or to sys.stdout by default. + """Prints the values to a stream, or to sys.stdout by default. sep string inserted between values, default a space. @@ -4946,8 +4170,7 @@ _SupportsSomeKindOfPow = ( # noqa: Y026 # TODO: Use TypeAlias once mypy bugs a # but adding a `NoReturn` overload isn't a good solution for expressing that (see #8566). @overload def pow(base: int, exp: int, mod: int) -> int: - """ - Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments + """Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments Some types, such as ints, are able to use a more efficient algorithm when invoked using the three argument form. @@ -4992,32 +4215,23 @@ def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex quit: _sitebuiltins.Quitter class reversed(Generic[_T]): - """ - Return a reverse iterator over the values of the given sequence. - """ + """Return a reverse iterator over the values of the given sequence.""" @overload def __new__(cls, sequence: Reversible[_T], /) -> Iterator[_T]: ... # type: ignore[misc] @overload def __new__(cls, sequence: SupportsLenAndGetItem[_T], /) -> Iterator[_T]: ... # type: ignore[misc] def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> _T: - """ - Implement next(self). - """ + """Implement next(self).""" def __length_hint__(self) -> int: - """ - Private method returning an estimate of len(list(it)). - """ + """Private method returning an estimate of len(list(it)).""" def repr(obj: object, /) -> str: - """ - Return the canonical string representation of the object. + """Return the canonical string representation of the object. For many object types, including most builtins, eval(repr(obj)) == obj. """ @@ -5034,8 +4248,7 @@ class _SupportsRound2(Protocol[_T_co]): @overload def round(number: _SupportsRound1[_T], ndigits: None = None) -> _T: - """ - Round a number to a given precision in decimal digits. + """Round a number to a given precision in decimal digits. The return value is an integer if ndigits is omitted or None. Otherwise the return value has the same type as the number. ndigits may be negative. @@ -5047,8 +4260,7 @@ def round(number: _SupportsRound2[_T], ndigits: SupportsIndex) -> _T: ... # See https://github.com/python/typeshed/pull/6292#discussion_r748875189 # for why arg 3 of `setattr` should be annotated with `Any` and not `object` def setattr(obj: object, name: str, value: Any, /) -> None: - """ - Sets the named attribute on the given object to the specified value. + """Sets the named attribute on the given object to the specified value. setattr(x, 'y', v) is equivalent to ``x.y = v`` """ @@ -5057,8 +4269,7 @@ def setattr(obj: object, name: str, value: Any, /) -> None: def sorted( iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, reverse: bool = False ) -> list[SupportsRichComparisonT]: - """ - Return a new list containing all items from the iterable in ascending order. + """Return a new list containing all items from the iterable in ascending order. A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order. @@ -5080,8 +4291,7 @@ _SupportsSumNoDefaultT = TypeVar("_SupportsSumNoDefaultT", bound=_SupportsSumWit # Instead, we special-case the most common examples of this: bool and literal integers. @overload def sum(iterable: Iterable[bool | _LiteralInteger], /, start: int = 0) -> int: - """ - Return the sum of a 'start' value (default: 0) plus an iterable of numbers + """Return the sum of a 'start' value (default: 0) plus an iterable of numbers When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may @@ -5097,8 +4307,7 @@ def sum(iterable: Iterable[_AddableT1], /, start: _AddableT2) -> _AddableT1 | _A # (A "SupportsDunderDict" protocol doesn't work) @overload def vars(object: type, /) -> types.MappingProxyType[str, Any]: - """ - vars([object]) -> dictionary + """vars([object]) -> dictionary Without arguments, equivalent to locals(). With an argument, equivalent to object.__dict__. @@ -5108,8 +4317,7 @@ def vars(object: type, /) -> types.MappingProxyType[str, Any]: def vars(object: Any = ..., /) -> dict[str, Any]: ... class zip(Generic[_T_co]): - """ - The zip object yields n-length tuples, where n is the number of iterables + """The zip object yields n-length tuples, where n is the number of iterables passed as positional arguments to zip(). The i-th element in every tuple comes from the i-th iterable argument to zip(). This continues until the shortest argument is exhausted. @@ -5192,14 +4400,10 @@ class zip(Generic[_T_co]): ) -> zip[tuple[Any, ...]]: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> _T_co: - """ - Implement next(self). - """ + """Implement next(self).""" # Signature of `builtins.__import__` should be kept identical to `importlib.__import__` # Return type of `__import__` should be kept the same as return type of `importlib.import_module` @@ -5210,8 +4414,7 @@ def __import__( fromlist: Sequence[str] = (), level: int = 0, ) -> types.ModuleType: - """ - Import a module. + """Import a module. Because this function is meant for use by the Python interpreter and not for general use, it is better to use @@ -5229,8 +4432,7 @@ def __import__( """ def __build_class__(func: Callable[[], CellType | Any], name: str, /, *bases: Any, metaclass: Any = ..., **kwds: Any) -> Any: - """ - __build_class__(func, name, /, *bases, [metaclass], **kwds) -> class + """__build_class__(func, name, /, *bases, [metaclass], **kwds) -> class Internal helper function used by the class statement. """ @@ -5254,9 +4456,7 @@ else: Ellipsis: ellipsis class BaseException: - """ - Common base class for all exceptions - """ + """Common base class for all exceptions""" args: tuple[Any, ...] __cause__: BaseException | None @@ -5267,50 +4467,34 @@ class BaseException: 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: - """ - Set self.__traceback__ to tb and return self. - """ + """Set self.__traceback__ to tb and return self.""" if sys.version_info >= (3, 11): # only present after add_note() is called __notes__: list[str] def add_note(self, note: str, /) -> None: - """ - Add a note to the exception - """ + """Add a note to the exception""" class GeneratorExit(BaseException): - """ - Request that a generator exit. - """ + """Request that a generator exit.""" class KeyboardInterrupt(BaseException): - """ - Program interrupted by user. - """ + """Program interrupted by user.""" class SystemExit(BaseException): - """ - Request to exit from the interpreter. - """ + """Request to exit from the interpreter.""" code: sys._ExitCode class Exception(BaseException): - """ - Common base class for all non-exit exceptions. - """ + """Common base class for all non-exit exceptions.""" class StopIteration(Exception): - """ - Signal the end from iterator.__next__(). - """ + """Signal the end from iterator.__next__().""" value: Any class OSError(Exception): - """ - Base class for I/O related errors. - """ + """Base class for I/O related errors.""" errno: int | None strerror: str | None @@ -5326,19 +4510,13 @@ if sys.platform == "win32": WindowsError = OSError class ArithmeticError(Exception): - """ - Base class for arithmetic errors. - """ + """Base class for arithmetic errors.""" class AssertionError(Exception): - """ - Assertion failed. - """ + """Assertion failed.""" class AttributeError(Exception): - """ - Attribute not found. - """ + """Attribute not found.""" if sys.version_info >= (3, 10): def __init__(self, *args: object, name: str | None = ..., obj: object = ...) -> None: ... @@ -5346,19 +4524,13 @@ class AttributeError(Exception): obj: object class BufferError(Exception): - """ - Buffer error. - """ + """Buffer error.""" class EOFError(Exception): - """ - Read beyond end of file. - """ + """Read beyond end of file.""" class ImportError(Exception): - """ - Import can't find module, or can't find name in module. - """ + """Import can't find module, or can't find name in module.""" def __init__(self, *args: object, name: str | None = ..., path: str | None = ...) -> None: ... name: str | None @@ -5368,43 +4540,29 @@ class ImportError(Exception): name_from: str | None # undocumented class LookupError(Exception): - """ - Base class for lookup errors. - """ + """Base class for lookup errors.""" class MemoryError(Exception): - """ - Out of memory. - """ + """Out of memory.""" class NameError(Exception): - """ - Name not found globally. - """ + """Name not found globally.""" if sys.version_info >= (3, 10): def __init__(self, *args: object, name: str | None = ...) -> None: ... name: str class ReferenceError(Exception): - """ - Weak ref proxy used after referent went away. - """ + """Weak ref proxy used after referent went away.""" class RuntimeError(Exception): - """ - Unspecified run-time error. - """ + """Unspecified run-time error.""" class StopAsyncIteration(Exception): - """ - Signal the end from iterator.__anext__(). - """ + """Signal the end from iterator.__anext__().""" class SyntaxError(Exception): - """ - Invalid syntax. - """ + """Invalid syntax.""" msg: str filename: str | None @@ -5435,164 +4593,103 @@ class SyntaxError(Exception): # the arguments from the info tuple are not parsed. This form is omitted. class SystemError(Exception): - """ - Internal error in the Python interpreter. + """Internal error in the Python interpreter. Please report this to the Python maintainer, along with the traceback, the Python version, and the hardware/OS platform and version. """ class TypeError(Exception): - """ - Inappropriate argument type. - """ + """Inappropriate argument type.""" class ValueError(Exception): - """ - Inappropriate argument value (of correct type). - """ + """Inappropriate argument value (of correct type).""" class FloatingPointError(ArithmeticError): - """ - Floating-point operation failed. - """ + """Floating-point operation failed.""" class OverflowError(ArithmeticError): - """ - Result too large to be represented. - """ + """Result too large to be represented.""" class ZeroDivisionError(ArithmeticError): - """ - Second argument to a division or modulo operation was zero. - """ + """Second argument to a division or modulo operation was zero.""" class ModuleNotFoundError(ImportError): - """ - Module not found. - """ + """Module not found.""" class IndexError(LookupError): - """ - Sequence index out of range. - """ + """Sequence index out of range.""" class KeyError(LookupError): - """ - Mapping key not found. - """ + """Mapping key not found.""" class UnboundLocalError(NameError): - """ - Local name referenced but not bound to a value. - """ + """Local name referenced but not bound to a value.""" class BlockingIOError(OSError): - """ - I/O operation would block. - """ + """I/O operation would block.""" characters_written: int class ChildProcessError(OSError): - """ - Child process error. - """ + """Child process error.""" class ConnectionError(OSError): - """ - Connection error. - """ + """Connection error.""" class BrokenPipeError(ConnectionError): - """ - Broken pipe. - """ + """Broken pipe.""" class ConnectionAbortedError(ConnectionError): - """ - Connection aborted. - """ + """Connection aborted.""" class ConnectionRefusedError(ConnectionError): - """ - Connection refused. - """ + """Connection refused.""" class ConnectionResetError(ConnectionError): - """ - Connection reset. - """ + """Connection reset.""" class FileExistsError(OSError): - """ - File already exists. - """ + """File already exists.""" class FileNotFoundError(OSError): - """ - File not found. - """ + """File not found.""" class InterruptedError(OSError): - """ - Interrupted by signal. - """ + """Interrupted by signal.""" class IsADirectoryError(OSError): - """ - Operation doesn't work on directories. - """ + """Operation doesn't work on directories.""" class NotADirectoryError(OSError): - """ - Operation only works on directories. - """ + """Operation only works on directories.""" class PermissionError(OSError): - """ - Not enough permissions. - """ + """Not enough permissions.""" class ProcessLookupError(OSError): - """ - Process not found. - """ + """Process not found.""" class TimeoutError(OSError): - """ - Timeout expired. - """ + """Timeout expired.""" class NotImplementedError(RuntimeError): - """ - Method or function hasn't been implemented yet. - """ + """Method or function hasn't been implemented yet.""" class RecursionError(RuntimeError): - """ - Recursion limit exceeded. - """ + """Recursion limit exceeded.""" class IndentationError(SyntaxError): - """ - Improper indentation. - """ + """Improper indentation.""" class TabError(IndentationError): - """ - Improper mixture of spaces and tabs. - """ + """Improper mixture of spaces and tabs.""" class UnicodeError(ValueError): - """ - Unicode related error. - """ + """Unicode related error.""" class UnicodeDecodeError(UnicodeError): - """ - Unicode decoding error. - """ + """Unicode decoding error.""" encoding: str object: bytes @@ -5602,9 +4699,7 @@ class UnicodeDecodeError(UnicodeError): def __init__(self, encoding: str, object: ReadableBuffer, start: int, end: int, reason: str, /) -> None: ... class UnicodeEncodeError(UnicodeError): - """ - Unicode encoding error. - """ + """Unicode encoding error.""" encoding: str object: str @@ -5614,9 +4709,7 @@ class UnicodeEncodeError(UnicodeError): def __init__(self, encoding: str, object: str, start: int, end: int, reason: str, /) -> None: ... class UnicodeTranslateError(UnicodeError): - """ - Unicode translation error. - """ + """Unicode translation error.""" encoding: None object: str @@ -5626,69 +4719,49 @@ class UnicodeTranslateError(UnicodeError): def __init__(self, object: str, start: int, end: int, reason: str, /) -> None: ... class Warning(Exception): - """ - Base class for warning categories. - """ + """Base class for warning categories.""" class UserWarning(Warning): - """ - Base class for warnings generated by user code. - """ + """Base class for warnings generated by user code.""" class DeprecationWarning(Warning): - """ - Base class for warnings about deprecated features. - """ + """Base class for warnings about deprecated features.""" class SyntaxWarning(Warning): - """ - Base class for warnings about dubious syntax. - """ + """Base class for warnings about dubious syntax.""" class RuntimeWarning(Warning): - """ - Base class for warnings about dubious runtime behavior. - """ + """Base class for warnings about dubious runtime behavior.""" class FutureWarning(Warning): - """ - Base class for warnings about constructs that will change semantically + """Base class for warnings about constructs that will change semantically in the future. """ class PendingDeprecationWarning(Warning): - """ - Base class for warnings about features which will be deprecated + """Base class for warnings about features which will be deprecated in the future. """ class ImportWarning(Warning): - """ - Base class for warnings about probable mistakes in module imports - """ + """Base class for warnings about probable mistakes in module imports""" class UnicodeWarning(Warning): - """ - Base class for warnings about Unicode related problems, mostly + """Base class for warnings about Unicode related problems, mostly related to conversion problems. """ class BytesWarning(Warning): - """ - Base class for warnings about bytes and buffer related problems, mostly + """Base class for warnings about bytes and buffer related problems, mostly related to conversion from str or comparing to str. """ class ResourceWarning(Warning): - """ - Base class for warnings about resource usage. - """ + """Base class for warnings about resource usage.""" if sys.version_info >= (3, 10): class EncodingWarning(Warning): - """ - Base class for warnings about encodings. - """ + """Base class for warnings about encodings.""" if sys.version_info >= (3, 11): _BaseExceptionT_co = TypeVar("_BaseExceptionT_co", bound=BaseException, covariant=True, default=BaseException) @@ -5698,23 +4771,17 @@ if sys.version_info >= (3, 11): # See `check_exception_group.py` for use-cases and comments. class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]): - """ - A combination of multiple unrelated exceptions. - """ + """A combination of multiple unrelated exceptions.""" def __new__(cls, message: str, exceptions: Sequence[_BaseExceptionT_co], /) -> Self: ... def __init__(self, message: str, exceptions: Sequence[_BaseExceptionT_co], /) -> None: ... @property def message(self) -> str: - """ - exception message - """ + """exception message""" @property def exceptions(self) -> tuple[_BaseExceptionT_co | BaseExceptionGroup[_BaseExceptionT_co], ...]: - """ - nested exceptions - """ + """nested exceptions""" @overload def subgroup( @@ -5746,18 +4813,14 @@ if sys.version_info >= (3, 11): @overload def derive(self, excs: Sequence[_BaseExceptionT], /) -> BaseExceptionGroup[_BaseExceptionT]: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" class ExceptionGroup(BaseExceptionGroup[_ExceptionT_co], Exception): def __new__(cls, message: str, exceptions: Sequence[_ExceptionT_co], /) -> Self: ... def __init__(self, message: str, exceptions: Sequence[_ExceptionT_co], /) -> None: ... @property def exceptions(self) -> tuple[_ExceptionT_co | ExceptionGroup[_ExceptionT_co], ...]: - """ - nested exceptions - """ + """nested exceptions""" # We accept a narrower type, but that's OK. @overload # type: ignore[override] def subgroup( @@ -5778,6 +4841,4 @@ if sys.version_info >= (3, 11): if sys.version_info >= (3, 13): class PythonFinalizationError(RuntimeError): - """ - Operation blocked during Python finalization. - """ + """Operation blocked during Python finalization.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/bz2.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/bz2.pyi index 45e307e05c..e702e8942e 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/bz2.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/bz2.pyi @@ -32,8 +32,7 @@ class _WritableFileobj(Protocol): # def close(self) -> object: ... def compress(data: ReadableBuffer, compresslevel: int = 9) -> bytes: - """ - Compress a block of data. + """Compress a block of data. compresslevel, if given, must be a number between 1 and 9. @@ -41,8 +40,7 @@ def compress(data: ReadableBuffer, compresslevel: int = 9) -> bytes: """ def decompress(data: ReadableBuffer) -> bytes: - """ - Decompress a block of data. + """Decompress a block of data. For incremental decompression, use a BZ2Decompressor object instead. """ @@ -61,8 +59,7 @@ def open( errors: None = None, newline: None = None, ) -> BZ2File: - """ - Open a bzip2-compressed file in binary or text mode. + """Open a bzip2-compressed file in binary or text mode. The filename argument can be an actual filename (a str, bytes, or PathLike object), or an existing file object to read from or write @@ -137,8 +134,7 @@ def open( ) -> BZ2File | TextIOWrapper: ... class BZ2File(BaseStream, IO[bytes]): - """ - A file object providing transparent bzip2 (de)compression. + """A file object providing transparent bzip2 (de)compression. A BZ2File can act as a wrapper for an existing file object, or refer directly to a named file on disk. @@ -150,8 +146,7 @@ class BZ2File(BaseStream, IO[bytes]): def __enter__(self) -> Self: ... @overload def __init__(self, filename: _WritableFileobj, mode: _WriteBinaryMode, *, compresslevel: int = 9) -> None: - """ - Open a bzip2-compressed file. + """Open a bzip2-compressed file. If filename is a str, bytes, or PathLike object, it gives the name of the file to be opened. Otherwise, it should be a file @@ -176,16 +171,14 @@ class BZ2File(BaseStream, IO[bytes]): self, filename: StrOrBytesPath, mode: _ReadBinaryMode | _WriteBinaryMode = "r", *, compresslevel: int = 9 ) -> None: ... def read(self, size: int | None = -1) -> bytes: - """ - Read up to size uncompressed bytes from the file. + """Read up to size uncompressed bytes from the file. If size is negative or omitted, read until EOF is reached. Returns b'' if the file is already at EOF. """ def read1(self, size: int = -1) -> bytes: - """ - Read up to size uncompressed bytes, while trying to avoid + """Read up to size uncompressed bytes, while trying to avoid making multiple reads from the underlying stream. Reads up to a buffer's worth of data if size is negative. @@ -193,8 +186,7 @@ class BZ2File(BaseStream, IO[bytes]): """ def readline(self, size: SupportsIndex = -1) -> bytes: # type: ignore[override] - """ - Read a line of uncompressed bytes from the file. + """Read a line of uncompressed bytes from the file. The terminating newline (if present) is retained. If size is non-negative, no more than size bytes will be read (in which @@ -202,15 +194,13 @@ class BZ2File(BaseStream, IO[bytes]): """ def readinto(self, b: WriteableBuffer) -> int: - """ - Read bytes into b. + """Read bytes into b. Returns the number of bytes read (0 for EOF). """ def readlines(self, size: SupportsIndex = -1) -> list[bytes]: - """ - Read a list of lines of uncompressed bytes from the file. + """Read a list of lines of uncompressed bytes from the file. size can be specified to control the number of lines read: no further lines will be read once the total size of the lines read @@ -218,16 +208,14 @@ class BZ2File(BaseStream, IO[bytes]): """ def peek(self, n: int = 0) -> bytes: - """ - Return buffered data without advancing the file position. + """Return buffered data without advancing the file position. Always returns at least one byte of data, unless at EOF. The exact number of bytes returned is unspecified. """ def seek(self, offset: int, whence: int = 0) -> int: - """ - Change the file position. + """Change the file position. The new position is specified by offset, relative to the position indicated by whence. Values for whence are: @@ -243,8 +231,7 @@ class BZ2File(BaseStream, IO[bytes]): """ def write(self, data: ReadableBuffer) -> int: - """ - Write a byte string to the file. + """Write a byte string to the file. Returns the number of uncompressed bytes written, which is always the length of data in bytes. Note that due to buffering, @@ -253,8 +240,7 @@ class BZ2File(BaseStream, IO[bytes]): """ def writelines(self, seq: Iterable[ReadableBuffer]) -> None: - """ - Write a sequence of byte strings to the file. + """Write a sequence of byte strings to the file. Returns the number of uncompressed bytes written. seq can be any iterable yielding byte strings. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/cProfile.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/cProfile.pyi index 7d4c31a424..866ceade81 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/cProfile.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/cProfile.pyi @@ -13,8 +13,7 @@ from typing_extensions import ParamSpec, Self, TypeAlias __all__ = ["run", "runctx", "Profile"] def run(statement: str, filename: str | None = None, sort: str | int = -1) -> None: - """ - Run statement under profiler optionally saving results in filename + """Run statement under profiler optionally saving results in filename This function takes a single argument that can be passed to the "exec" statement, and an optional file name. In all cases this @@ -28,8 +27,7 @@ def run(statement: str, filename: str | None = None, sort: str | int = -1) -> No def runctx( statement: str, globals: dict[str, Any], locals: Mapping[str, Any], filename: str | None = None, sort: str | int = -1 ) -> None: - """ - Run statement under profiler, supplying your own globals and locals, + """Run statement under profiler, supplying your own globals and locals, optionally saving results in filename. statement and filename have the same semantics as profile.run @@ -40,8 +38,7 @@ _P = ParamSpec("_P") _Label: TypeAlias = tuple[str, int, str] class Profile(_lsprof.Profiler): - """ - Profile(timer=None, timeunit=None, subcalls=True, builtins=True) + """Profile(timer=None, timeunit=None, subcalls=True, builtins=True) Builds a profiler object using the specified timer function. The default timer is a fast built-in one based on real time. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/calendar.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/calendar.pyi index 0e5cde94b9..696e31d932 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/calendar.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/calendar.pyi @@ -72,30 +72,23 @@ class IllegalWeekdayError(ValueError): def __init__(self, weekday: int) -> None: ... def isleap(year: int) -> bool: - """ - Return True for leap years, False for non-leap years. - """ + """Return True for leap years, False for non-leap years.""" def leapdays(y1: int, y2: int) -> int: - """ - Return number of leap years in range [y1, y2). + """Return number of leap years in range [y1, y2). Assume y1 <= y2. """ def weekday(year: int, month: int, day: int) -> int: - """ - Return weekday (0-6 ~ Mon-Sun) for year, month (1-12), day (1-31). - """ + """Return weekday (0-6 ~ Mon-Sun) for year, month (1-12), day (1-31).""" def monthrange(year: int, month: int) -> tuple[int, int]: - """ - Return weekday of first day of month (0-6 ~ Mon-Sun) + """Return weekday of first day of month (0-6 ~ Mon-Sun) and number of days (28-31) for year, month. """ class Calendar: - """ - Base calendar class. This class doesn't do any formatting. It simply + """Base calendar class. This class doesn't do any formatting. It simply provides data to subclasses. """ @@ -104,187 +97,137 @@ class Calendar: def getfirstweekday(self) -> int: ... def setfirstweekday(self, firstweekday: int) -> None: ... def iterweekdays(self) -> Iterable[int]: - """ - Return an iterator for one week of weekday numbers starting with the + """Return an iterator for one week of weekday numbers starting with the configured first one. """ def itermonthdates(self, year: int, month: int) -> Iterable[datetime.date]: - """ - Return an iterator for one month. The iterator will yield datetime.date + """Return an iterator for one month. The iterator will yield datetime.date values and will always iterate through complete weeks, so it will yield dates outside the specified month. """ def itermonthdays2(self, year: int, month: int) -> Iterable[tuple[int, int]]: - """ - Like itermonthdates(), but will yield (day number, weekday number) + """Like itermonthdates(), but will yield (day number, weekday number) tuples. For days outside the specified month the day number is 0. """ def itermonthdays(self, year: int, month: int) -> Iterable[int]: - """ - Like itermonthdates(), but will yield day numbers. For days outside + """Like itermonthdates(), but will yield day numbers. For days outside the specified month the day number is 0. """ def monthdatescalendar(self, year: int, month: int) -> list[list[datetime.date]]: - """ - Return a matrix (list of lists) representing a month's calendar. + """Return a matrix (list of lists) representing a month's calendar. Each row represents a week; week entries are datetime.date values. """ def monthdays2calendar(self, year: int, month: int) -> list[list[tuple[int, int]]]: - """ - Return a matrix representing a month's calendar. + """Return a matrix representing a month's calendar. Each row represents a week; week entries are (day number, weekday number) tuples. Day numbers outside this month are zero. """ def monthdayscalendar(self, year: int, month: int) -> list[list[int]]: - """ - Return a matrix representing a month's calendar. + """Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero. """ def yeardatescalendar(self, year: int, width: int = 3) -> list[list[list[list[datetime.date]]]]: - """ - Return the data for the specified year ready for formatting. The return + """Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains up to width months. Each month contains between 4 and 6 weeks and each week contains 1-7 days. Days are datetime.date objects. """ def yeardays2calendar(self, year: int, width: int = 3) -> list[list[list[list[tuple[int, int]]]]]: - """ - Return the data for the specified year ready for formatting (similar to + """Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are (day number, weekday number) tuples. Day numbers outside this month are zero. """ def yeardayscalendar(self, year: int, width: int = 3) -> list[list[list[list[int]]]]: - """ - Return the data for the specified year ready for formatting (similar to + """Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero. """ def itermonthdays3(self, year: int, month: int) -> Iterable[tuple[int, int, int]]: - """ - Like itermonthdates(), but will yield (year, month, day) tuples. Can be + """Like itermonthdates(), but will yield (year, month, day) tuples. Can be used for dates outside of datetime.date range. """ def itermonthdays4(self, year: int, month: int) -> Iterable[tuple[int, int, int, int]]: - """ - Like itermonthdates(), but will yield (year, month, day, day_of_week) tuples. + """Like itermonthdates(), but will yield (year, month, day, day_of_week) tuples. Can be used for dates outside of datetime.date range. """ class TextCalendar(Calendar): - """ - Subclass of Calendar that outputs a calendar as a simple plain text + """Subclass of Calendar that outputs a calendar as a simple plain text similar to the UNIX program cal. """ def prweek(self, theweek: int, width: int) -> None: - """ - Print a single week (no newline). - """ + """Print a single week (no newline).""" def formatday(self, day: int, weekday: int, width: int) -> str: - """ - Returns a formatted day. - """ + """Returns a formatted day.""" def formatweek(self, theweek: int, width: int) -> str: - """ - Returns a single week in a string (no newline). - """ + """Returns a single week in a string (no newline).""" def formatweekday(self, day: int, width: int) -> str: - """ - Returns a formatted week day name. - """ + """Returns a formatted week day name.""" def formatweekheader(self, width: int) -> str: - """ - Return a header for a week. - """ + """Return a header for a week.""" def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = True) -> str: - """ - Return a formatted month name. - """ + """Return a formatted month name.""" def prmonth(self, theyear: int, themonth: int, w: int = 0, l: int = 0) -> None: - """ - Print a month's calendar. - """ + """Print a month's calendar.""" def formatmonth(self, theyear: int, themonth: int, w: int = 0, l: int = 0) -> str: - """ - Return a month's calendar string (multi-line). - """ + """Return a month's calendar string (multi-line).""" def formatyear(self, theyear: int, w: int = 2, l: int = 1, c: int = 6, m: int = 3) -> str: - """ - Returns a year's calendar as a multi-line string. - """ + """Returns a year's calendar as a multi-line string.""" def pryear(self, theyear: int, w: int = 0, l: int = 0, c: int = 6, m: int = 3) -> None: - """ - Print a year's calendar. - """ + """Print a year's calendar.""" def firstweekday() -> int: ... def monthcalendar(year: int, month: int) -> list[list[int]]: - """ - Return a matrix representing a month's calendar. + """Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero. """ def prweek(theweek: int, width: int) -> None: - """ - Print a single week (no newline). - """ + """Print a single week (no newline).""" def week(theweek: int, width: int) -> str: - """ - Returns a single week in a string (no newline). - """ + """Returns a single week in a string (no newline).""" def weekheader(width: int) -> str: - """ - Return a header for a week. - """ + """Return a header for a week.""" def prmonth(theyear: int, themonth: int, w: int = 0, l: int = 0) -> None: - """ - Print a month's calendar. - """ + """Print a month's calendar.""" def month(theyear: int, themonth: int, w: int = 0, l: int = 0) -> str: - """ - Return a month's calendar string (multi-line). - """ + """Return a month's calendar string (multi-line).""" def calendar(theyear: int, w: int = 2, l: int = 1, c: int = 6, m: int = 3) -> str: - """ - Returns a year's calendar as a multi-line string. - """ + """Returns a year's calendar as a multi-line string.""" def prcal(theyear: int, w: int = 0, l: int = 0, c: int = 6, m: int = 3) -> None: - """ - Print a year's calendar. - """ + """Print a year's calendar.""" class HTMLCalendar(Calendar): - """ - This calendar returns complete HTML pages. - """ + """This calendar returns complete HTML pages.""" cssclasses: ClassVar[list[str]] cssclass_noday: ClassVar[str] @@ -294,46 +237,30 @@ class HTMLCalendar(Calendar): cssclass_year: ClassVar[str] cssclass_year_head: ClassVar[str] def formatday(self, day: int, weekday: int) -> str: - """ - Return a day as a table cell. - """ + """Return a day as a table cell.""" def formatweek(self, theweek: int) -> str: - """ - Return a complete week as a table row. - """ + """Return a complete week as a table row.""" def formatweekday(self, day: int) -> str: - """ - Return a weekday name as a table header. - """ + """Return a weekday name as a table header.""" def formatweekheader(self) -> str: - """ - Return a header for a week as a table row. - """ + """Return a header for a week as a table row.""" def formatmonthname(self, theyear: int, themonth: int, withyear: bool = True) -> str: - """ - Return a month name as a table row. - """ + """Return a month name as a table row.""" def formatmonth(self, theyear: int, themonth: int, withyear: bool = True) -> str: - """ - Return a formatted month as a table. - """ + """Return a formatted month as a table.""" def formatyear(self, theyear: int, width: int = 3) -> str: - """ - Return a formatted year as a table of tables. - """ + """Return a formatted year as a table of tables.""" def formatyearpage( self, theyear: int, width: int = 3, css: str | None = "calendar.css", encoding: str | None = None ) -> bytes: - """ - Return a formatted year as a complete HTML page. - """ + """Return a formatted year as a complete HTML page.""" class different_locale: def __init__(self, locale: _LocaleType) -> None: ... @@ -341,16 +268,14 @@ class different_locale: def __exit__(self, *args: Unused) -> None: ... class LocaleTextCalendar(TextCalendar): - """ - This class can be passed a locale name in the constructor and will return + """This class can be passed a locale name in the constructor and will return month and weekday names in the specified locale. """ def __init__(self, firstweekday: int = 0, locale: _LocaleType | None = None) -> None: ... class LocaleHTMLCalendar(HTMLCalendar): - """ - This class can be passed a locale name in the constructor and will return + """This class can be passed a locale name in the constructor and will return month and weekday names in the specified locale. """ @@ -362,19 +287,13 @@ c: TextCalendar def setfirstweekday(firstweekday: int) -> None: ... def format(cols: int, colwidth: int = 20, spacing: int = 6) -> str: - """ - Prints multi-column formatting for year calendars - """ + """Prints multi-column formatting for year calendars""" def formatstring(cols: int, colwidth: int = 20, spacing: int = 6) -> str: - """ - Returns a string formatted from n strings, centered within n columns. - """ + """Returns a string formatted from n strings, centered within n columns.""" def timegm(tuple: tuple[int, ...] | struct_time) -> int: - """ - Unrelated but handy function to calculate Unix timestamp from GMT. - """ + """Unrelated but handy function to calculate Unix timestamp from GMT.""" # Data attributes day_name: Sequence[str] diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/cgi.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/cgi.pyi index 83d5b38cbe..0c0d63f762 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/cgi.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/cgi.pyi @@ -40,8 +40,7 @@ def parse( strict_parsing: bool = ..., separator: str = "&", ) -> dict[str, list[str]]: - """ - Parse a query in the environment or from a file (default stdin) + """Parse a query in the environment or from a file (default stdin) Arguments, all optional: @@ -67,8 +66,7 @@ def parse( def parse_multipart( fp: IO[Any], pdict: SupportsGetItem[str, bytes], encoding: str = "utf-8", errors: str = "replace", separator: str = "&" ) -> dict[str, list[Any]]: - """ - Parse multipart input. + """Parse multipart input. Arguments: fp : input file @@ -86,44 +84,32 @@ class _Environ(Protocol): def keys(self) -> Iterable[str]: ... def parse_header(line: str) -> tuple[str, dict[str, str]]: - """ - Parse a Content-type like header. + """Parse a Content-type like header. Return the main content-type and a dictionary of options. """ def test(environ: _Environ = ...) -> None: - """ - Robust test CGI script, usable as main program. + """Robust test CGI script, usable as main program. Write minimal HTTP headers and dump all information provided to the script in HTML form. """ def print_environ(environ: _Environ = ...) -> None: - """ - Dump the shell environment as HTML. - """ + """Dump the shell environment as HTML.""" def print_form(form: dict[str, Any]) -> None: - """ - Dump the contents of a form as HTML. - """ + """Dump the contents of a form as HTML.""" def print_directory() -> None: - """ - Dump the current directory as HTML. - """ + """Dump the current directory as HTML.""" def print_environ_usage() -> None: - """ - Dump a list of environment variables used by CGI as HTML. - """ + """Dump a list of environment variables used by CGI as HTML.""" class MiniFieldStorage: - """ - Like FieldStorage, for use when no file uploads are possible. - """ + """Like FieldStorage, for use when no file uploads are possible.""" # The first five "Any" attributes here are always None, but mypy doesn't support that filename: Any @@ -137,13 +123,10 @@ class MiniFieldStorage: name: Any value: Any def __init__(self, name: Any, value: Any) -> None: - """ - Constructor from field name and value. - """ + """Constructor from field name and value.""" class FieldStorage: - """ - Store a sequence of fields, reading multipart/form-data. + """Store a sequence of fields, reading multipart/form-data. This class provides naming, typing, files stored on disk, and more. At the top level, it is accessible like a dictionary, whose @@ -220,8 +203,7 @@ class FieldStorage: max_num_fields: int | None = None, separator: str = "&", ) -> None: - """ - Constructor. Read multipart/* until last part. + """Constructor. Read multipart/* until last part. Arguments, all optional: @@ -268,46 +250,31 @@ class FieldStorage: def __exit__(self, *args: Unused) -> None: ... def __iter__(self) -> Iterator[str]: ... def __getitem__(self, key: str) -> Any: - """ - Dictionary style indexing. - """ + """Dictionary style indexing.""" def getvalue(self, key: str, default: Any = None) -> Any: - """ - Dictionary style get() method, including 'value' lookup. - """ + """Dictionary style get() method, including 'value' lookup.""" def getfirst(self, key: str, default: Any = None) -> Any: - """ - Return the first value received. - """ + """Return the first value received.""" def getlist(self, key: str) -> _list[Any]: - """ - Return list of received values. - """ + """Return list of received values.""" def keys(self) -> _list[str]: - """ - Dictionary style keys() method. - """ + """Dictionary style keys() method.""" def __contains__(self, key: str) -> bool: - """ - Dictionary style __contains__ method. - """ + """Dictionary style __contains__ method.""" def __len__(self) -> int: - """ - Dictionary style len(x) support. - """ + """Dictionary style len(x) support.""" def __bool__(self) -> bool: ... def __del__(self) -> None: ... # Returns bytes or str IO depending on an internal flag def make_file(self) -> IO[Any]: - """ - Overridable: return a readable & writable file. + """Overridable: return a readable & writable file. The file will be used as follows: - data is written to it diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/cgitb.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/cgitb.pyi index fc3890b443..3dd0205175 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/cgitb.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/cgitb.pyi @@ -30,39 +30,27 @@ from typing import IO, Any, Final __UNDEF__: Final[object] # undocumented sentinel def reset() -> str: # undocumented - """ - Return a string that resets the CGI and browser to a known state. - """ + """Return a string that resets the CGI and browser to a known state.""" def small(text: str) -> str: ... # undocumented def strong(text: str) -> str: ... # undocumented def grey(text: str) -> str: ... # undocumented def lookup(name: str, frame: FrameType, locals: dict[str, Any]) -> tuple[str | None, Any]: # undocumented - """ - Find the value for a given name in the given environment. - """ + """Find the value for a given name in the given environment.""" def scanvars( reader: Callable[[], bytes], frame: FrameType, locals: dict[str, Any] ) -> list[tuple[str, str | None, Any]]: # undocumented - """ - Scan one logical line of Python and look up values of variables used. - """ + """Scan one logical line of Python and look up values of variables used.""" def html(einfo: OptExcInfo, context: int = 5) -> str: - """ - Return a nice HTML document describing a given traceback. - """ + """Return a nice HTML document describing a given traceback.""" def text(einfo: OptExcInfo, context: int = 5) -> str: - """ - Return a plain text document describing a given traceback. - """ + """Return a plain text document describing a given traceback.""" class Hook: # undocumented - """ - A hook to replace sys.excepthook that shows tracebacks in HTML. - """ + """A hook to replace sys.excepthook that shows tracebacks in HTML.""" def __init__( self, @@ -77,8 +65,7 @@ class Hook: # undocumented def handler(info: OptExcInfo | None = None) -> None: ... def enable(display: int = 1, logdir: StrOrBytesPath | None = None, context: int = 5, format: str = "html") -> None: - """ - Install an exception handler that formats tracebacks as HTML. + """Install an exception handler that formats tracebacks as HTML. The optional argument 'display' can be set to 0 to suppress sending the traceback to the browser, and 'logdir' can be set to a directory to cause diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/chunk.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/chunk.pyi index 09851f25c4..d7b1058ae4 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/chunk.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/chunk.pyi @@ -62,35 +62,28 @@ class Chunk: seekable: bool def __init__(self, file: IO[bytes], align: bool = True, bigendian: bool = True, inclheader: bool = False) -> None: ... def getname(self) -> bytes: - """ - Return the name (ID) of the current chunk. - """ + """Return the name (ID) of the current chunk.""" def getsize(self) -> int: - """ - Return the size of the current chunk. - """ + """Return the size of the current chunk.""" def close(self) -> None: ... def isatty(self) -> bool: ... def seek(self, pos: int, whence: int = 0) -> None: - """ - Seek to specified position into the chunk. + """Seek to specified position into the chunk. Default position is 0 (start of chunk). If the file is not seekable, this will result in an error. """ def tell(self) -> int: ... def read(self, size: int = -1) -> bytes: - """ - Read at most size bytes from the chunk. + """Read at most size bytes from the chunk. If size is omitted or negative, read until the end of the chunk. """ def skip(self) -> None: - """ - Skip the rest of the chunk. + """Skip the rest of the chunk. If you are not interested in the contents of the chunk, this method should be called so that the file points to the start of the next chunk. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/cmath.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/cmath.pyi index 6df749d46a..a1f61aa5ee 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/cmath.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/cmath.pyi @@ -17,53 +17,34 @@ tau: Final[float] _C: TypeAlias = SupportsFloat | SupportsComplex | SupportsIndex | complex def acos(z: _C, /) -> complex: - """ - Return the arc cosine of z. - """ + """Return the arc cosine of z.""" def acosh(z: _C, /) -> complex: - """ - Return the inverse hyperbolic cosine of z. - """ + """Return the inverse hyperbolic cosine of z.""" def asin(z: _C, /) -> complex: - """ - Return the arc sine of z. - """ + """Return the arc sine of z.""" def asinh(z: _C, /) -> complex: - """ - Return the inverse hyperbolic sine of z. - """ + """Return the inverse hyperbolic sine of z.""" def atan(z: _C, /) -> complex: - """ - Return the arc tangent of z. - """ + """Return the arc tangent of z.""" def atanh(z: _C, /) -> complex: - """ - Return the inverse hyperbolic tangent of z. - """ + """Return the inverse hyperbolic tangent of z.""" def cos(z: _C, /) -> complex: - """ - Return the cosine of z. - """ + """Return the cosine of z.""" def cosh(z: _C, /) -> complex: - """ - Return the hyperbolic cosine of z. - """ + """Return the hyperbolic cosine of z.""" def exp(z: _C, /) -> complex: - """ - Return the exponential value e**z. - """ + """Return the exponential value e**z.""" def isclose(a: _C, b: _C, *, rel_tol: SupportsFloat = 1e-09, abs_tol: SupportsFloat = 0.0) -> bool: - """ - Determine whether two complex numbers are close in value. + """Determine whether two complex numbers are close in value. rel_tol maximum difference for being considered "close", relative to the @@ -82,70 +63,46 @@ def isclose(a: _C, b: _C, *, rel_tol: SupportsFloat = 1e-09, abs_tol: SupportsFl """ def isinf(z: _C, /) -> bool: - """ - Checks if the real or imaginary part of z is infinite. - """ + """Checks if the real or imaginary part of z is infinite.""" def isnan(z: _C, /) -> bool: - """ - Checks if the real or imaginary part of z not a number (NaN). - """ + """Checks if the real or imaginary part of z not a number (NaN).""" def log(x: _C, base: _C = ..., /) -> complex: - """ - log(z[, base]) -> the logarithm of z to the given base. + """log(z[, base]) -> the logarithm of z to the given base. If the base is not specified, returns the natural logarithm (base e) of z. """ def log10(z: _C, /) -> complex: - """ - Return the base-10 logarithm of z. - """ + """Return the base-10 logarithm of z.""" def phase(z: _C, /) -> float: - """ - Return argument, also known as the phase angle, of a complex. - """ + """Return argument, also known as the phase angle, of a complex.""" def polar(z: _C, /) -> tuple[float, float]: - """ - Convert a complex from rectangular coordinates to polar coordinates. + """Convert a complex from rectangular coordinates to polar coordinates. r is the distance from 0 and phi the phase angle. """ def rect(r: float, phi: float, /) -> complex: - """ - Convert from polar coordinates to rectangular coordinates. - """ + """Convert from polar coordinates to rectangular coordinates.""" def sin(z: _C, /) -> complex: - """ - Return the sine of z. - """ + """Return the sine of z.""" def sinh(z: _C, /) -> complex: - """ - Return the hyperbolic sine of z. - """ + """Return the hyperbolic sine of z.""" def sqrt(z: _C, /) -> complex: - """ - Return the square root of z. - """ + """Return the square root of z.""" def tan(z: _C, /) -> complex: - """ - Return the tangent of z. - """ + """Return the tangent of z.""" def tanh(z: _C, /) -> complex: - """ - Return the hyperbolic tangent of z. - """ + """Return the hyperbolic tangent of z.""" def isfinite(z: _C, /) -> bool: - """ - Return True if both the real and imaginary parts of z are finite, else False. - """ + """Return True if both the real and imaginary parts of z are finite, else False.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/cmd.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/cmd.pyi index 49ca0db50b..2ea88d16c4 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/cmd.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/cmd.pyi @@ -53,8 +53,7 @@ PROMPT: Final = "(Cmd) " IDENTCHARS: Final[LiteralString] # Too big to be `Literal` class Cmd: - """ - A simple framework for writing line-oriented command interpreters. + """A simple framework for writing line-oriented command interpreters. These are often useful for test harnesses, administrative tools, and prototypes that will later be wrapped in a more sophisticated interface. @@ -81,8 +80,7 @@ class Cmd: cmdqueue: list[str] completekey: str def __init__(self, completekey: str = "tab", stdin: IO[str] | None = None, stdout: IO[str] | None = None) -> None: - """ - Instantiate a line-oriented interpreter framework. + """Instantiate a line-oriented interpreter framework. The optional argument 'completekey' is the readline name of a completion key; it defaults to the Tab key. If completekey is @@ -93,44 +91,35 @@ class Cmd: """ old_completer: Callable[[str, int], str | None] | None def cmdloop(self, intro: Any | None = None) -> None: - """ - Repeatedly issue a prompt, accept input, parse an initial prefix + """Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument. """ def precmd(self, line: str) -> str: - """ - Hook method executed just before the command line is + """Hook method executed just before the command line is interpreted, but after the input prompt is generated and issued. """ def postcmd(self, stop: bool, line: str) -> bool: - """ - Hook method executed just after a command dispatch is finished. - """ + """Hook method executed just after a command dispatch is finished.""" def preloop(self) -> None: - """ - Hook method executed once when the cmdloop() method is called. - """ + """Hook method executed once when the cmdloop() method is called.""" def postloop(self) -> None: - """ - Hook method executed once when the cmdloop() method is about to + """Hook method executed once when the cmdloop() method is about to return. """ def parseline(self, line: str) -> tuple[str | None, str | None, str]: - """ - Parse the line into a command name and a string containing + """Parse the line into a command name and a string containing the arguments. Returns a tuple containing (command, args, line). 'command' and 'args' may be None if the line couldn't be parsed. """ def onecmd(self, line: str) -> bool: - """ - Interpret the argument as though it had been typed in response + """Interpret the argument as though it had been typed in response to the prompt. This may be overridden, but should not normally need to be; @@ -140,24 +129,21 @@ class Cmd: """ def emptyline(self) -> bool: - """ - Called when an empty line is entered in response to the prompt. + """Called when an empty line is entered in response to the prompt. If this method is not overridden, it repeats the last nonempty command entered. """ def default(self, line: str) -> None: - """ - Called on an input line when the command prefix is not recognized. + """Called on an input line when the command prefix is not recognized. If this method is not overridden, it prints an error message and returns. """ def completedefault(self, *ignored: Any) -> list[str]: - """ - Method called to complete an input line when no command-specific + """Method called to complete an input line when no command-specific complete_*() method is available. By default, it returns an empty list. @@ -166,8 +152,7 @@ class Cmd: def completenames(self, text: str, *ignored: Any) -> list[str]: ... completion_matches: list[str] | None def complete(self, text: str, state: int) -> list[str] | None: - """ - Return the next possible completion for 'text'. + """Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_ to get list of completions. @@ -177,14 +162,11 @@ class Cmd: # Only the first element of args matters. def complete_help(self, *args: Any) -> list[str]: ... def do_help(self, arg: str) -> bool | None: - """ - List available commands with "help" or detailed help with "help cmd". - """ + """List available commands with "help" or detailed help with "help cmd".""" def print_topics(self, header: str, cmds: list[str] | None, cmdlen: Any, maxcol: int) -> None: ... def columnize(self, list: list[str] | None, displaywidth: int = 80) -> None: - """ - Display a list of strings as a compact set of columns. + """Display a list of strings as a compact set of columns. Each column is only as wide as necessary. Columns are separated by two spaces (one was not legible enough). diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/code.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/code.pyi index 55e70a2f1d..8c6bee7c4d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/code.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/code.pyi @@ -11,8 +11,7 @@ from typing import Any __all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact", "compile_command"] class InteractiveInterpreter: - """ - Base class for InteractiveConsole. + """Base class for InteractiveConsole. This class deals with parsing and interpreter state (the user's namespace); it doesn't deal with input buffering or prompting or @@ -22,8 +21,7 @@ class InteractiveInterpreter: locals: dict[str, Any] # undocumented compile: CommandCompiler # undocumented def __init__(self, locals: dict[str, Any] | None = None) -> None: - """ - Constructor. + """Constructor. The optional 'locals' argument specifies a mapping to use as the namespace in which code will be executed; it defaults to a newly @@ -32,8 +30,7 @@ class InteractiveInterpreter: """ def runsource(self, source: str, filename: str = "", symbol: str = "single") -> bool: - """ - Compile and run some source in the interpreter. + """Compile and run some source in the interpreter. Arguments are as for compile_command(). @@ -57,8 +54,7 @@ class InteractiveInterpreter: """ def runcode(self, code: CodeType) -> None: - """ - Execute a code object. + """Execute a code object. When an exception occurs, self.showtraceback() is called to display a traceback. All exceptions are caught except @@ -70,8 +66,7 @@ class InteractiveInterpreter: """ if sys.version_info >= (3, 13): def showsyntaxerror(self, filename: str | None = None, *, source: str = "") -> None: - """ - Display the syntax error that just occurred. + """Display the syntax error that just occurred. This doesn't display a stack trace because there isn't one. @@ -83,8 +78,7 @@ class InteractiveInterpreter: """ else: def showsyntaxerror(self, filename: str | None = None) -> None: - """ - Display the syntax error that just occurred. + """Display the syntax error that just occurred. This doesn't display a stack trace because there isn't one. @@ -96,8 +90,7 @@ class InteractiveInterpreter: """ def showtraceback(self) -> None: - """ - Display the exception that just occurred. + """Display the exception that just occurred. We remove the first stack item because it is our own code. @@ -105,16 +98,14 @@ class InteractiveInterpreter: """ def write(self, data: str) -> None: - """ - Write a string. + """Write a string. The base implementation writes to sys.stderr; a subclass may replace this with a different implementation. """ class InteractiveConsole(InteractiveInterpreter): - """ - Closely emulate the behavior of the interactive Python interpreter. + """Closely emulate the behavior of the interactive Python interpreter. This class builds on InteractiveInterpreter and adds prompting using the familiar sys.ps1 and sys.ps2, and input buffering. @@ -126,8 +117,7 @@ class InteractiveConsole(InteractiveInterpreter): def __init__( self, locals: dict[str, Any] | None = None, filename: str = "", *, local_exit: bool = False ) -> None: - """ - Constructor. + """Constructor. The optional locals argument will be passed to the InteractiveInterpreter base class. @@ -137,8 +127,7 @@ class InteractiveConsole(InteractiveInterpreter): """ def push(self, line: str, filename: str | None = None) -> bool: - """ - Push a line to the interpreter. + """Push a line to the interpreter. The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the @@ -152,8 +141,7 @@ class InteractiveConsole(InteractiveInterpreter): """ else: def __init__(self, locals: dict[str, Any] | None = None, filename: str = "") -> None: - """ - Constructor. + """Constructor. The optional locals argument will be passed to the InteractiveInterpreter base class. @@ -163,8 +151,7 @@ class InteractiveConsole(InteractiveInterpreter): """ def push(self, line: str) -> bool: - """ - Push a line to the interpreter. + """Push a line to the interpreter. The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the @@ -178,8 +165,7 @@ class InteractiveConsole(InteractiveInterpreter): """ def interact(self, banner: str | None = None, exitmsg: str | None = None) -> None: - """ - Closely emulate the interactive Python console. + """Closely emulate the interactive Python console. The optional banner argument specifies the banner to print before the first interaction; by default it prints a banner @@ -195,13 +181,10 @@ class InteractiveConsole(InteractiveInterpreter): """ def resetbuffer(self) -> None: - """ - Reset the input buffer. - """ + """Reset the input buffer.""" def raw_input(self, prompt: str = "") -> str: - """ - Write a prompt and read a line. + """Write a prompt and read a line. The returned line does not include the trailing newline. When the user enters the EOF key sequence, EOFError is raised. @@ -219,8 +202,7 @@ if sys.version_info >= (3, 13): exitmsg: str | None = None, local_exit: bool = False, ) -> None: - """ - Closely emulate the interactive Python interpreter. + """Closely emulate the interactive Python interpreter. This is a backwards compatible interface to the InteractiveConsole class. When readfunc is not specified, it attempts to import the @@ -242,8 +224,7 @@ else: local: dict[str, Any] | None = None, exitmsg: str | None = None, ) -> None: - """ - Closely emulate the interactive Python interpreter. + """Closely emulate the interactive Python interpreter. This is a backwards compatible interface to the InteractiveConsole class. When readfunc is not specified, it attempts to import the diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/codecs.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/codecs.pyi index 78111eac7c..0c2c18e9ef 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/codecs.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/codecs.pyi @@ -122,9 +122,7 @@ class _BufferedIncrementalDecoder(Protocol): def __call__(self, errors: str = ...) -> BufferedIncrementalDecoder: ... class CodecInfo(tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): - """ - Codec details when looking up the codec registry - """ + """Codec details when looking up the codec registry""" _is_text_encoding: bool @property @@ -154,24 +152,21 @@ class CodecInfo(tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): ) -> Self: ... def getencoder(encoding: str) -> _Encoder: - """ - Lookup up the codec for the given encoding and return + """Lookup up the codec for the given encoding and return its encoder function. Raises a LookupError in case the encoding cannot be found. """ def getdecoder(encoding: str) -> _Decoder: - """ - Lookup up the codec for the given encoding and return + """Lookup up the codec for the given encoding and return its decoder function. Raises a LookupError in case the encoding cannot be found. """ def getincrementalencoder(encoding: str) -> _IncrementalEncoder: - """ - Lookup up the codec for the given encoding and return + """Lookup up the codec for the given encoding and return its IncrementalEncoder class or factory function. Raises a LookupError in case the encoding cannot be found @@ -180,8 +175,7 @@ def getincrementalencoder(encoding: str) -> _IncrementalEncoder: @overload def getincrementaldecoder(encoding: _BufferedEncoding) -> _BufferedIncrementalDecoder: - """ - Lookup up the codec for the given encoding and return + """Lookup up the codec for the given encoding and return its IncrementalDecoder class or factory function. Raises a LookupError in case the encoding cannot be found @@ -191,16 +185,14 @@ def getincrementaldecoder(encoding: _BufferedEncoding) -> _BufferedIncrementalDe @overload def getincrementaldecoder(encoding: str) -> _IncrementalDecoder: ... def getreader(encoding: str) -> _StreamReader: - """ - Lookup up the codec for the given encoding and return + """Lookup up the codec for the given encoding and return its StreamReader class or factory function. Raises a LookupError in case the encoding cannot be found. """ def getwriter(encoding: str) -> _StreamWriter: - """ - Lookup up the codec for the given encoding and return + """Lookup up the codec for the given encoding and return its StreamWriter class or factory function. Raises a LookupError in case the encoding cannot be found. @@ -209,8 +201,7 @@ def getwriter(encoding: str) -> _StreamWriter: def open( filename: str, mode: str = "r", encoding: str | None = None, errors: str = "strict", buffering: int = -1 ) -> StreamReaderWriter: - """ - Open an encoded file using the given mode and return + """Open an encoded file using the given mode and return a wrapped version providing transparent encoding/decoding. Note: The wrapped version will only accept the object format @@ -240,8 +231,7 @@ def open( """ def EncodedFile(file: _Stream, data_encoding: str, file_encoding: str | None = None, errors: str = "strict") -> StreamRecoder: - """ - Return a wrapped version of file which provides transparent + """Return a wrapped version of file which provides transparent encoding translation. Data written to the wrapped file is decoded according @@ -265,8 +255,7 @@ def EncodedFile(file: _Stream, data_encoding: str, file_encoding: str | None = N """ def iterencode(iterator: Iterable[str], encoding: str, errors: str = "strict") -> Generator[bytes, None, None]: - """ - Encoding iterator. + """Encoding iterator. Encodes the input strings from the iterator using an IncrementalEncoder. @@ -275,8 +264,7 @@ def iterencode(iterator: Iterable[str], encoding: str, errors: str = "strict") - """ def iterdecode(iterator: Iterable[bytes], encoding: str, errors: str = "strict") -> Generator[str, None, None]: - """ - Decoding iterator. + """Decoding iterator. Decodes the input strings from the iterator using an IncrementalDecoder. @@ -296,38 +284,25 @@ BOM_UTF32_BE: Final = b"\x00\x00\xfe\xff" BOM_UTF32_LE: Final = b"\xff\xfe\x00\x00" def strict_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: - """ - Implements the 'strict' error handling, which raises a UnicodeError on coding errors. - """ + """Implements the 'strict' error handling, which raises a UnicodeError on coding errors.""" def replace_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: - """ - Implements the 'replace' error handling, which replaces malformed data with a replacement marker. - """ + """Implements the 'replace' error handling, which replaces malformed data with a replacement marker.""" def ignore_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: - """ - Implements the 'ignore' error handling, which ignores malformed data and continues. - """ + """Implements the 'ignore' error handling, which ignores malformed data and continues.""" def xmlcharrefreplace_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: - """ - Implements the 'xmlcharrefreplace' error handling, which replaces an unencodable character with the appropriate XML character reference. - """ + """Implements the 'xmlcharrefreplace' error handling, which replaces an unencodable character with the appropriate XML character reference.""" def backslashreplace_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: - """ - Implements the 'backslashreplace' error handling, which replaces malformed data with a backslashed escape sequence. - """ + """Implements the 'backslashreplace' error handling, which replaces malformed data with a backslashed escape sequence.""" def namereplace_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: - """ - Implements the 'namereplace' error handling, which replaces an unencodable character with a \\N{...} escape sequence. - """ + """Implements the 'namereplace' error handling, which replaces an unencodable character with a \\N{...} escape sequence.""" class Codec: - """ - Defines the interface for stateless encoders/decoders. + """Defines the interface for stateless encoders/decoders. The .encode()/.decode() methods may use different error handling schemes by providing the errors argument. These @@ -352,8 +327,7 @@ class Codec: # These are sort of @abstractmethod but sort of not. # The StreamReader and StreamWriter subclasses only implement one. def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: - """ - Encodes the object input and returns a tuple (output + """Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to @@ -369,8 +343,7 @@ class Codec: """ def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: - """ - Decodes the object input and returns a tuple (output + """Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf @@ -390,16 +363,14 @@ class Codec: """ class IncrementalEncoder: - """ - An IncrementalEncoder encodes an input in multiple steps. The input can + """An IncrementalEncoder encodes an input in multiple steps. The input can be passed piece by piece to the encode() method. The IncrementalEncoder remembers the state of the encoding process between calls to encode(). """ errors: str def __init__(self, errors: str = "strict") -> None: - """ - Creates an IncrementalEncoder instance. + """Creates an IncrementalEncoder instance. The IncrementalEncoder may use different error handling schemes by providing the errors keyword argument. See the module docstring @@ -408,37 +379,28 @@ class IncrementalEncoder: @abstractmethod def encode(self, input: str, final: bool = False) -> bytes: - """ - Encodes input and returns the resulting object. - """ + """Encodes input and returns the resulting object.""" def reset(self) -> None: - """ - Resets the encoder to the initial state. - """ + """Resets the encoder to the initial state.""" # documentation says int but str is needed for the subclass. def getstate(self) -> int | str: - """ - Return the current state of the encoder. - """ + """Return the current state of the encoder.""" def setstate(self, state: int | str) -> None: - """ - Set the current state of the encoder. state must have been + """Set the current state of the encoder. state must have been returned by getstate(). """ class IncrementalDecoder: - """ - An IncrementalDecoder decodes an input in multiple steps. The input can + """An IncrementalDecoder decodes an input in multiple steps. The input can be passed piece by piece to the decode() method. The IncrementalDecoder remembers the state of the decoding process between calls to decode(). """ errors: str def __init__(self, errors: str = "strict") -> None: - """ - Create an IncrementalDecoder instance. + """Create an IncrementalDecoder instance. The IncrementalDecoder may use different error handling schemes by providing the errors keyword argument. See the module docstring @@ -447,18 +409,13 @@ class IncrementalDecoder: @abstractmethod def decode(self, input: ReadableBuffer, final: bool = False) -> str: - """ - Decode input and returns the resulting object. - """ + """Decode input and returns the resulting object.""" def reset(self) -> None: - """ - Reset the decoder to the initial state. - """ + """Reset the decoder to the initial state.""" def getstate(self) -> tuple[bytes, int]: - """ - Return the current state of the decoder. + """Return the current state of the decoder. This must be a (buffered_input, additional_state_info) tuple. buffered_input must be a bytes object containing bytes that @@ -470,8 +427,7 @@ class IncrementalDecoder: """ def setstate(self, state: tuple[bytes, int]) -> None: - """ - Set the current state of the decoder. + """Set the current state of the decoder. state must have been returned by getstate(). The effect of setstate((b"", 0)) must be equivalent to reset(). @@ -479,8 +435,7 @@ class IncrementalDecoder: # These are not documented but used in encodings/*.py implementations. class BufferedIncrementalEncoder(IncrementalEncoder): - """ - This subclass of IncrementalEncoder can be used as the baseclass for an + """This subclass of IncrementalEncoder can be used as the baseclass for an incremental encoder if the encoder must keep some of the output in a buffer between calls to encode(). """ @@ -492,8 +447,7 @@ class BufferedIncrementalEncoder(IncrementalEncoder): def encode(self, input: str, final: bool = False) -> bytes: ... class BufferedIncrementalDecoder(IncrementalDecoder): - """ - This subclass of IncrementalDecoder can be used as the baseclass for an + """This subclass of IncrementalDecoder can be used as the baseclass for an incremental decoder if the decoder must be able to handle incomplete byte sequences. """ @@ -510,8 +464,7 @@ class StreamWriter(Codec): stream: _WritableStream errors: str def __init__(self, stream: _WritableStream, errors: str = "strict") -> None: - """ - Creates a StreamWriter instance. + """Creates a StreamWriter instance. stream must be a file-like object open for writing. @@ -533,19 +486,15 @@ class StreamWriter(Codec): """ def write(self, object: str) -> None: - """ - Writes the object's contents encoded to self.stream. - """ + """Writes the object's contents encoded to self.stream.""" def writelines(self, list: Iterable[str]) -> None: - """ - Writes the concatenated list of strings to the stream + """Writes the concatenated list of strings to the stream using .write(). """ def reset(self) -> None: - """ - Resets the codec buffers used for keeping internal state. + """Resets the codec buffers used for keeping internal state. Calling this method should ensure that the data on the output is put into a clean state, that allows appending @@ -557,9 +506,7 @@ class StreamWriter(Codec): def __enter__(self) -> Self: ... def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... def __getattr__(self, name: str, getattr: Callable[[Any, str], Any] = ...) -> Any: - """ - Inherit all other methods from the underlying stream. - """ + """Inherit all other methods from the underlying stream.""" class StreamReader(Codec): stream: _ReadableStream @@ -567,8 +514,7 @@ class StreamReader(Codec): # This is set to str, but some subclasses set to bytes instead. charbuffertype: ClassVar[type] = ... def __init__(self, stream: _ReadableStream, errors: str = "strict") -> None: - """ - Creates a StreamReader instance. + """Creates a StreamReader instance. stream must be a file-like object open for reading. @@ -586,8 +532,7 @@ class StreamReader(Codec): """ def read(self, size: int = -1, chars: int = -1, firstline: bool = False) -> str: - """ - Decodes data from the stream self.stream and returns the + """Decodes data from the stream self.stream and returns the resulting object. chars indicates the number of decoded code points or bytes to @@ -614,8 +559,7 @@ class StreamReader(Codec): """ def readline(self, size: int | None = None, keepends: bool = True) -> str: - """ - Read one line from the input stream and return the + """Read one line from the input stream and return the decoded data. size, if given, is passed as size argument to the @@ -623,8 +567,7 @@ class StreamReader(Codec): """ def readlines(self, sizehint: int | None = None, keepends: bool = True) -> list[str]: - """ - Read all lines available on the input stream + """Read all lines available on the input stream and return them as a list. Line breaks are implemented using the codec's decoder @@ -635,8 +578,7 @@ class StreamReader(Codec): """ def reset(self) -> None: - """ - Resets the codec buffers used for keeping internal state. + """Resets the codec buffers used for keeping internal state. Note that no stream repositioning should take place. This method is primarily intended to be able to recover @@ -644,8 +586,7 @@ class StreamReader(Codec): """ def seek(self, offset: int, whence: int = 0) -> None: - """ - Set the input stream's current position. + """Set the input stream's current position. Resets the codec buffers used for keeping state. """ @@ -654,20 +595,15 @@ class StreamReader(Codec): def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... def __iter__(self) -> Self: ... def __next__(self) -> str: - """ - Return the next decoded line from the input stream. - """ + """Return the next decoded line from the input stream.""" def __getattr__(self, name: str, getattr: Callable[[Any, str], Any] = ...) -> Any: - """ - Inherit all other methods from the underlying stream. - """ + """Inherit all other methods from the underlying stream.""" # Doesn't actually inherit from TextIO, but wraps a BinaryIO to provide text reading and writing # and delegates attributes to the underlying binary stream with __getattr__. class StreamReaderWriter(TextIO): - """ - StreamReaderWriter instances allow wrapping streams which + """StreamReaderWriter instances allow wrapping streams which work in both read and write modes. The design is such that one can use the factory functions @@ -677,8 +613,7 @@ class StreamReaderWriter(TextIO): stream: _Stream def __init__(self, stream: _Stream, Reader: _StreamReader, Writer: _StreamWriter, errors: str = "strict") -> None: - """ - Creates a StreamReaderWriter instance. + """Creates a StreamReaderWriter instance. stream must be a Stream-like object. @@ -693,9 +628,7 @@ class StreamReaderWriter(TextIO): def readline(self, size: int | None = None) -> str: ... def readlines(self, sizehint: int | None = None) -> list[str]: ... def __next__(self) -> str: - """ - Return the next decoded line from the input stream. - """ + """Return the next decoded line from the input stream.""" def __iter__(self) -> Self: ... def write(self, data: str) -> None: ... # type: ignore[override] @@ -705,9 +638,7 @@ class StreamReaderWriter(TextIO): def __enter__(self) -> Self: ... def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... def __getattr__(self, name: str) -> Any: - """ - Inherit all other methods from the underlying stream. - """ + """Inherit all other methods from the underlying stream.""" # These methods don't actually exist directly, but they are needed to satisfy the TextIO # interface. At runtime, they are delegated through __getattr__. def close(self) -> None: ... @@ -721,8 +652,7 @@ class StreamReaderWriter(TextIO): def writable(self) -> bool: ... class StreamRecoder(BinaryIO): - """ - StreamRecoder instances translate data from one encoding to another. + """StreamRecoder instances translate data from one encoding to another. They use the complete set of APIs returned by the codecs.lookup() function to implement their task. @@ -747,8 +677,7 @@ class StreamRecoder(BinaryIO): Writer: _StreamWriter, errors: str = "strict", ) -> None: - """ - Creates a StreamRecoder instance which implements a two-way + """Creates a StreamRecoder instance which implements a two-way conversion: encode and decode work on the frontend (the data visible to .read() and .write()) while Reader and Writer work on the backend (the data in stream). @@ -770,9 +699,7 @@ class StreamRecoder(BinaryIO): def readline(self, size: int | None = None) -> bytes: ... def readlines(self, sizehint: int | None = None) -> list[bytes]: ... def __next__(self) -> bytes: - """ - Return the next decoded line from the input stream. - """ + """Return the next decoded line from the input stream.""" def __iter__(self) -> Self: ... # Base class accepts more types than just bytes @@ -780,9 +707,7 @@ class StreamRecoder(BinaryIO): def writelines(self, list: Iterable[bytes]) -> None: ... # type: ignore[override] def reset(self) -> None: ... def __getattr__(self, name: str) -> Any: - """ - Inherit all other methods from the underlying stream. - """ + """Inherit all other methods from the underlying stream.""" def __enter__(self) -> Self: ... def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/codeop.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/codeop.pyi index f00bb9804d..492818ae8f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/codeop.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/codeop.pyi @@ -40,8 +40,7 @@ __all__ = ["compile_command", "Compile", "CommandCompiler"] if sys.version_info >= (3, 14): def compile_command(source: str, filename: str = "", symbol: str = "single", flags: int = 0) -> CodeType | None: - """ - Compile a command and determine whether it is incomplete. + """Compile a command and determine whether it is incomplete. Arguments: @@ -62,8 +61,7 @@ if sys.version_info >= (3, 14): else: def compile_command(source: str, filename: str = "", symbol: str = "single") -> CodeType | None: - """ - Compile a command and determine whether it is incomplete. + """Compile a command and determine whether it is incomplete. Arguments: @@ -83,8 +81,7 @@ else: """ class Compile: - """ - Instances of this class behave much like the built-in compile + """Instances of this class behave much like the built-in compile function, but if one is used to compile text containing a future statement, it "remembers" and compiles all subsequent program texts with the statement in force. @@ -97,8 +94,7 @@ class Compile: def __call__(self, source: str, filename: str, symbol: str) -> CodeType: ... class CommandCompiler: - """ - Instances of this class have __call__ methods identical in + """Instances of this class have __call__ methods identical in signature to compile_command; the difference is that if the instance compiles program text containing a __future__ statement, the instance 'remembers' and compiles all subsequent program texts @@ -107,8 +103,7 @@ class CommandCompiler: compiler: Compile def __call__(self, source: str, filename: str = "", symbol: str = "single") -> CodeType | None: - """ - Compile a command and determine whether it is incomplete. + """Compile a command and determine whether it is incomplete. Arguments: diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/collections/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/collections/__init__.pyi index 8a8e8cc98d..193e8fb378 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/collections/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/collections/__init__.pyi @@ -57,8 +57,7 @@ def namedtuple( module: str | None = None, defaults: Iterable[Any] | None = None, ) -> type[tuple[Any, ...]]: - """ - Returns a new subclass of tuple with named fields. + """Returns a new subclass of tuple with named fields. >>> Point = namedtuple('Point', ['x', 'y']) >>> Point.__doc__ # docstring for the new class @@ -145,9 +144,7 @@ class UserDict(MutableMapping[_KT, _VT]): if sys.version_info >= (3, 12): @overload def get(self, key: _KT, default: None = None) -> _VT | None: - """ - D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. - """ + """D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.""" @overload def get(self, key: _KT, default: _VT) -> _VT: ... @@ -155,9 +152,7 @@ class UserDict(MutableMapping[_KT, _VT]): def get(self, key: _KT, default: _T) -> _VT | _T: ... class UserList(MutableSequence[_T]): - """ - A more or less complete user-defined wrapper around list objects. - """ + """A more or less complete user-defined wrapper around list objects.""" data: list[_T] @overload @@ -278,137 +273,88 @@ class UserString(Sequence[UserString]): def zfill(self, width: int) -> Self: ... class deque(MutableSequence[_T]): - """ - A list-like sequence optimized for data accesses near its endpoints. - """ + """A list-like sequence optimized for data accesses near its endpoints.""" @property def maxlen(self) -> int | None: - """ - maximum size of a deque or None if unbounded - """ + """maximum size of a deque or None if unbounded""" @overload def __init__(self, *, maxlen: int | None = None) -> None: ... @overload def __init__(self, iterable: Iterable[_T], maxlen: int | None = None) -> None: ... def append(self, x: _T, /) -> None: - """ - Add an element to the right side of the deque. - """ + """Add an element to the right side of the deque.""" def appendleft(self, x: _T, /) -> None: - """ - Add an element to the left side of the deque. - """ + """Add an element to the left side of the deque.""" def copy(self) -> Self: - """ - Return a shallow copy of a deque. - """ + """Return a shallow copy of a deque.""" def count(self, x: _T, /) -> int: - """ - Return number of occurrences of value. - """ + """Return number of occurrences of value.""" def extend(self, iterable: Iterable[_T], /) -> None: - """ - Extend the right side of the deque with elements from the iterable. - """ + """Extend the right side of the deque with elements from the iterable.""" def extendleft(self, iterable: Iterable[_T], /) -> None: - """ - Extend the left side of the deque with elements from the iterable. - """ + """Extend the left side of the deque with elements from the iterable.""" def insert(self, i: int, x: _T, /) -> None: - """ - Insert value before index. - """ + """Insert value before index.""" def index(self, x: _T, start: int = 0, stop: int = ..., /) -> int: - """ - Return first index of value. + """Return first index of value. Raises ValueError if the value is not present. """ def pop(self) -> _T: # type: ignore[override] - """ - Remove and return the rightmost element. - """ + """Remove and return the rightmost element.""" def popleft(self) -> _T: - """ - Remove and return the leftmost element. - """ + """Remove and return the leftmost element.""" def remove(self, value: _T, /) -> None: - """ - Remove first occurrence of value. - """ + """Remove first occurrence of value.""" def rotate(self, n: int = 1, /) -> None: - """ - Rotate the deque n steps to the right. If n is negative, rotates left. - """ + """Rotate the deque n steps to the right. If n is negative, rotates left.""" def __copy__(self) -> Self: - """ - Return a shallow copy of a deque. - """ + """Return a shallow copy of a deque.""" def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" __hash__: ClassVar[None] # type: ignore[assignment] # These methods of deque don't take slices, unlike MutableSequence, hence the type: ignores def __getitem__(self, key: SupportsIndex, /) -> _T: # type: ignore[override] - """ - Return self[key]. - """ + """Return self[key].""" def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: # type: ignore[override] - """ - Set self[key] to value. - """ + """Set self[key] to value.""" def __delitem__(self, key: SupportsIndex, /) -> None: # type: ignore[override] - """ - Delete self[key]. - """ + """Delete self[key].""" def __contains__(self, key: object, /) -> bool: - """ - Return bool(key in self). - """ + """Return bool(key in self).""" def __reduce__(self) -> tuple[type[Self], tuple[()], None, Iterator[_T]]: - """ - Return state information for pickling. - """ + """Return state information for pickling.""" def __iadd__(self, value: Iterable[_T], /) -> Self: - """ - Implement self+=value. - """ + """Implement self+=value.""" def __add__(self, value: Self, /) -> Self: - """ - Return self+value. - """ + """Return self+value.""" def __mul__(self, value: int, /) -> Self: - """ - Return self*value. - """ + """Return self*value.""" def __imul__(self, value: int, /) -> Self: - """ - Implement self*=value. - """ + """Implement self*=value.""" def __lt__(self, value: deque[_T], /) -> bool: ... def __le__(self, value: deque[_T], /) -> bool: ... @@ -416,13 +362,10 @@ class deque(MutableSequence[_T]): def __ge__(self, value: deque[_T], /) -> bool: ... def __eq__(self, value: object, /) -> bool: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" class Counter(dict[_T, int], Generic[_T]): - """ - Dict subclass for counting hashable items. Sometimes called a bag + """Dict subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values. @@ -467,8 +410,7 @@ class Counter(dict[_T, int], Generic[_T]): @overload def __init__(self, iterable: None = None, /) -> None: - """ - Create a new, empty Counter object. And if given, count elements + """Create a new, empty Counter object. And if given, count elements from an input iterable. Or, initialize the count from another mapping of elements to their counts. @@ -485,13 +427,10 @@ class Counter(dict[_T, int], Generic[_T]): @overload def __init__(self, iterable: Iterable[_T], /) -> None: ... def copy(self) -> Self: - """ - Return a shallow copy. - """ + """Return a shallow copy.""" def elements(self) -> Iterator[_T]: - """ - Iterator over elements repeating each as many times as its count. + """Iterator over elements repeating each as many times as its count. >>> c = Counter('ABCABC') >>> sorted(c.elements()) @@ -509,8 +448,7 @@ class Counter(dict[_T, int], Generic[_T]): """ def most_common(self, n: int | None = None) -> list[tuple[_T, int]]: - """ - List the n most common elements and their counts from the most + """List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts. >>> Counter('abracadabra').most_common(3) @@ -521,8 +459,7 @@ class Counter(dict[_T, int], Generic[_T]): def fromkeys(cls, iterable: Any, v: int | None = None) -> NoReturn: ... # type: ignore[override] @overload def subtract(self, iterable: None = None, /) -> None: - """ - Like dict.update() but subtracts counts instead of replacing them. + """Like dict.update() but subtracts counts instead of replacing them. Counts can be reduced below zero. Both the inputs and outputs are allowed to contain zero and negative counts. @@ -549,8 +486,7 @@ class Counter(dict[_T, int], Generic[_T]): # the tuples would be added as keys, breaking type safety) @overload # type: ignore[override] def update(self, m: Mapping[_T, int], /, **kwargs: int) -> None: - """ - Like dict.update() but add counts instead of replacing them. + """Like dict.update() but add counts instead of replacing them. Source can be an iterable, a dictionary, or another Counter instance. @@ -567,71 +503,55 @@ class Counter(dict[_T, int], Generic[_T]): @overload def update(self, iterable: None = None, /, **kwargs: int) -> None: ... def __missing__(self, key: _T) -> int: - """ - The count of elements not in the Counter is zero. - """ + """The count of elements not in the Counter is zero.""" def __delitem__(self, elem: object) -> None: - """ - Like dict.__delitem__() but does not raise KeyError for missing values. - """ + """Like dict.__delitem__() but does not raise KeyError for missing values.""" if sys.version_info >= (3, 10): def __eq__(self, other: object) -> bool: - """ - True if all counts agree. Missing counts are treated as zero. - """ + """True if all counts agree. Missing counts are treated as zero.""" def __ne__(self, other: object) -> bool: - """ - True if any counts disagree. Missing counts are treated as zero. - """ + """True if any counts disagree. Missing counts are treated as zero.""" def __add__(self, other: Counter[_S]) -> Counter[_T | _S]: - """ - Add counts from two counters. + """Add counts from two counters. >>> Counter('abbb') + Counter('bcc') Counter({'b': 4, 'c': 2, 'a': 1}) """ def __sub__(self, other: Counter[_T]) -> Counter[_T]: - """ - Subtract count, but keep only results with positive counts. + """Subtract count, but keep only results with positive counts. >>> Counter('abbbc') - Counter('bccd') Counter({'b': 2, 'a': 1}) """ def __and__(self, other: Counter[_T]) -> Counter[_T]: - """ - Intersection is the minimum of corresponding counts. + """Intersection is the minimum of corresponding counts. >>> Counter('abbb') & Counter('bcc') Counter({'b': 1}) """ def __or__(self, other: Counter[_S]) -> Counter[_T | _S]: # type: ignore[override] - """ - Union is the maximum of value in either of the input counters. + """Union is the maximum of value in either of the input counters. >>> Counter('abbb') | Counter('bcc') Counter({'b': 3, 'c': 2, 'a': 1}) """ def __pos__(self) -> Counter[_T]: - """ - Adds an empty counter, effectively stripping negative and zero counts - """ + """Adds an empty counter, effectively stripping negative and zero counts""" def __neg__(self) -> Counter[_T]: - """ - Subtracts from an empty counter. Strips positive and zero counts, + """Subtracts from an empty counter. Strips positive and zero counts, and flips the sign on negative counts. """ # several type: ignores because __iadd__ is supposedly incompatible with __add__, etc. def __iadd__(self, other: SupportsItems[_T, int]) -> Self: # type: ignore[misc] - """ - Inplace add from another counter, keeping only positive counts. + """Inplace add from another counter, keeping only positive counts. >>> c = Counter('abbb') >>> c += Counter('bcc') @@ -640,8 +560,7 @@ class Counter(dict[_T, int], Generic[_T]): """ def __isub__(self, other: SupportsItems[_T, int]) -> Self: - """ - Inplace subtract counter, but keep only results with positive counts. + """Inplace subtract counter, but keep only results with positive counts. >>> c = Counter('abbbc') >>> c -= Counter('bccd') @@ -650,8 +569,7 @@ class Counter(dict[_T, int], Generic[_T]): """ def __iand__(self, other: SupportsItems[_T, int]) -> Self: - """ - Inplace intersection is the minimum of corresponding counts. + """Inplace intersection is the minimum of corresponding counts. >>> c = Counter('abbb') >>> c &= Counter('bcc') @@ -660,8 +578,7 @@ class Counter(dict[_T, int], Generic[_T]): """ def __ior__(self, other: SupportsItems[_T, int]) -> Self: # type: ignore[override,misc] - """ - Inplace union is the maximum of value from either counter. + """Inplace union is the maximum of value from either counter. >>> c = Counter('abbb') >>> c |= Counter('bcc') @@ -670,29 +587,19 @@ class Counter(dict[_T, int], Generic[_T]): """ if sys.version_info >= (3, 10): def total(self) -> int: - """ - Sum of the counts - """ + """Sum of the counts""" def __le__(self, other: Counter[Any]) -> bool: - """ - True if all counts in self are a subset of those in other. - """ + """True if all counts in self are a subset of those in other.""" def __lt__(self, other: Counter[Any]) -> bool: - """ - True if all counts in self are a proper subset of those in other. - """ + """True if all counts in self are a proper subset of those in other.""" def __ge__(self, other: Counter[Any]) -> bool: - """ - True if all counts in self are a superset of those in other. - """ + """True if all counts in self are a superset of those in other.""" def __gt__(self, other: Counter[Any]) -> bool: - """ - True if all counts in self are a proper superset of those in other. - """ + """True if all counts in self are a proper superset of those in other.""" # The pure-Python implementations of the "views" classes # These are exposed at runtime in `collections/__init__.py` @@ -722,33 +629,25 @@ class _odict_values(dict_values[_KT_co, _VT_co]): # type: ignore[misc] # pyrig def __reversed__(self) -> Iterator[_VT_co]: ... class OrderedDict(dict[_KT, _VT]): - """ - Dictionary that remembers insertion order - """ + """Dictionary that remembers insertion order""" def popitem(self, last: bool = True) -> tuple[_KT, _VT]: - """ - Remove and return a (key, value) pair from the dictionary. + """Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order if last is true or FIFO order if false. """ def move_to_end(self, key: _KT, last: bool = True) -> None: - """ - Move an existing element to the end (or beginning if last is false). + """Move an existing element to the end (or beginning if last is false). Raise KeyError if the element does not exist. """ def copy(self) -> Self: - """ - od.copy() -> a shallow copy of od - """ + """od.copy() -> a shallow copy of od""" def __reversed__(self) -> Iterator[_KT]: - """ - od.__reversed__() <==> reversed(od) - """ + """od.__reversed__() <==> reversed(od)""" def keys(self) -> _odict_keys[_KT, _VT]: ... def items(self) -> _odict_items[_KT, _VT]: ... @@ -759,9 +658,7 @@ class OrderedDict(dict[_KT, _VT]): @classmethod @overload def fromkeys(cls, iterable: Iterable[_T], value: None = None) -> OrderedDict[_T, Any | None]: - """ - Create a new ordered dictionary with keys from iterable and values set to value. - """ + """Create a new ordered dictionary with keys from iterable and values set to value.""" @classmethod @overload @@ -769,8 +666,7 @@ class OrderedDict(dict[_KT, _VT]): # Keep OrderedDict.setdefault in line with MutableMapping.setdefault, modulo positional-only differences. @overload def setdefault(self: OrderedDict[_KT, _T | None], key: _KT, default: None = None) -> _T | None: - """ - Insert key with a value of default if key is not in the dictionary. + """Insert key with a value of default if key is not in the dictionary. Return the value for key if key is in the dictionary, else default. """ @@ -780,8 +676,7 @@ class OrderedDict(dict[_KT, _VT]): # Same as dict.pop, but accepts keyword arguments @overload def pop(self, key: _KT) -> _VT: - """ - od.pop(key[,default]) -> v, remove specified key and return the corresponding value. + """od.pop(key[,default]) -> v, remove specified key and return the corresponding value. If the key is not found, return the default if given; otherwise, raise a KeyError. @@ -794,24 +689,19 @@ class OrderedDict(dict[_KT, _VT]): def __eq__(self, value: object, /) -> bool: ... @overload def __or__(self, value: dict[_KT, _VT], /) -> Self: - """ - Return self|value. - """ + """Return self|value.""" @overload def __or__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... @overload def __ror__(self, value: dict[_KT, _VT], /) -> Self: - """ - Return value|self. - """ + """Return value|self.""" @overload def __ror__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] class defaultdict(dict[_KT, _VT]): - """ - defaultdict(default_factory=None, /, [...]) --> dict with default factory + """defaultdict(default_factory=None, /, [...]) --> dict with default factory The default factory is called without arguments to produce a new value when a key is not present, in __getitem__ only. @@ -855,43 +745,33 @@ class defaultdict(dict[_KT, _VT]): **kwargs: _VT, ) -> None: ... def __missing__(self, key: _KT, /) -> _VT: - """ - __missing__(key) # Called by __getitem__ for missing key; pseudo-code: + """__missing__(key) # Called by __getitem__ for missing key; pseudo-code: if self.default_factory is None: raise KeyError((key,)) self[key] = value = self.default_factory() return value """ def __copy__(self) -> Self: - """ - D.copy() -> a shallow copy of D. - """ + """D.copy() -> a shallow copy of D.""" def copy(self) -> Self: - """ - D.copy() -> a shallow copy of D. - """ + """D.copy() -> a shallow copy of D.""" @overload def __or__(self, value: dict[_KT, _VT], /) -> Self: - """ - Return self|value. - """ + """Return self|value.""" @overload def __or__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... @overload def __ror__(self, value: dict[_KT, _VT], /) -> Self: - """ - Return value|self. - """ + """Return value|self.""" @overload def __ror__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] class ChainMap(MutableMapping[_KT, _VT]): - """ - A ChainMap groups multiple dicts (or other mappings) together + """A ChainMap groups multiple dicts (or other mappings) together to create a single, updateable view. The underlying mappings are stored in a list. That list is public and can @@ -905,23 +785,19 @@ class ChainMap(MutableMapping[_KT, _VT]): maps: list[MutableMapping[_KT, _VT]] def __init__(self, *maps: MutableMapping[_KT, _VT]) -> None: - """ - Initialize a ChainMap by setting *maps* to the given mappings. + """Initialize a ChainMap by setting *maps* to the given mappings. If no mappings are provided, a single empty dictionary is used. """ def new_child(self, m: MutableMapping[_KT, _VT] | None = None) -> Self: - """ - New ChainMap with a new map followed by all previous maps. + """New ChainMap with a new map followed by all previous maps. If no map is provided, an empty dict is used. Keyword arguments update the map or new empty dict. """ @property def parents(self) -> Self: - """ - New ChainMap from maps[1:]. - """ + """New ChainMap from maps[1:].""" def __setitem__(self, key: _KT, value: _VT) -> None: ... def __delitem__(self, key: _KT) -> None: ... @@ -940,35 +816,27 @@ class ChainMap(MutableMapping[_KT, _VT]): # Keep ChainMap.setdefault in line with MutableMapping.setdefault, modulo positional-only differences. @overload def setdefault(self: ChainMap[_KT, _T | None], key: _KT, default: None = None) -> _T | None: - """ - D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D - """ + """D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D""" @overload def setdefault(self, key: _KT, default: _VT) -> _VT: ... @overload def pop(self, key: _KT) -> _VT: - """ - Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0]. - """ + """Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].""" @overload def pop(self, key: _KT, default: _VT) -> _VT: ... @overload def pop(self, key: _KT, default: _T) -> _VT | _T: ... def copy(self) -> Self: - """ - New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:] - """ + """New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]""" __copy__ = copy # All arguments to `fromkeys` are passed to `dict.fromkeys` at runtime, # so the signature should be kept in line with `dict.fromkeys`. @classmethod @overload def fromkeys(cls, iterable: Iterable[_T]) -> ChainMap[_T, Any | None]: - """ - Create a new ChainMap with keys from iterable and values set to value. - """ + """Create a new ChainMap with keys from iterable and values set to value.""" @classmethod @overload diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/compileall.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/compileall.pyi index 70a3dec3f2..86fa27effd 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/compileall.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/compileall.pyi @@ -40,8 +40,7 @@ if sys.version_info >= (3, 10): limit_sl_dest: StrPath | None = None, hardlink_dupes: bool = False, ) -> bool: - """ - Byte-compile all modules in the given directory tree. + """Byte-compile all modules in the given directory tree. Arguments (only dir is required): @@ -81,8 +80,7 @@ if sys.version_info >= (3, 10): limit_sl_dest: StrPath | None = None, hardlink_dupes: bool = False, ) -> bool: - """ - Byte-compile one file. + """Byte-compile one file. Arguments (only fullname is required): @@ -123,8 +121,7 @@ else: limit_sl_dest: StrPath | None = None, hardlink_dupes: bool = False, ) -> bool: - """ - Byte-compile all modules in the given directory tree. + """Byte-compile all modules in the given directory tree. Arguments (only dir is required): @@ -164,8 +161,7 @@ else: limit_sl_dest: StrPath | None = None, hardlink_dupes: bool = False, ) -> bool: - """ - Byte-compile one file. + """Byte-compile one file. Arguments (only fullname is required): @@ -197,8 +193,7 @@ def compile_path( optimize: int = -1, invalidation_mode: PycInvalidationMode | None = None, ) -> bool: - """ - Byte-compile all module on sys.path. + """Byte-compile all module on sys.path. Arguments (all optional): diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/compression/_common/_streams.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/compression/_common/_streams.pyi index 5e0f5d39df..5c752dd4ec 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/compression/_common/_streams.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/compression/_common/_streams.pyi @@ -16,14 +16,10 @@ class _Reader(Protocol): def seek(self, n: int, /) -> Any: ... class BaseStream(BufferedIOBase): - """ - Mode-checking helper functions. - """ + """Mode-checking helper functions.""" class DecompressReader(RawIOBase): - """ - Adapts the decompressor API to a RawIOBase reader API - """ + """Adapts the decompressor API to a RawIOBase reader API""" def __init__( self, diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/compression/zstd/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/compression/zstd/__init__.pyi index 044d9e98ef..7026179dec 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/compression/zstd/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/compression/zstd/__init__.pyi @@ -39,17 +39,14 @@ zstd_version_info: Final[tuple[int, int, int]] COMPRESSION_LEVEL_DEFAULT: Final = _zstd.ZSTD_CLEVEL_DEFAULT class FrameInfo: - """ - Information about a Zstandard frame. - """ + """Information about a Zstandard frame.""" decompressed_size: int dictionary_id: int def __init__(self, decompressed_size: int, dictionary_id: int) -> None: ... def get_frame_info(frame_buffer: ReadableBuffer) -> FrameInfo: - """ - Get Zstandard frame information from a frame header. + """Get Zstandard frame information from a frame header. *frame_buffer* is a bytes-like object. It should start from the beginning of a frame, and needs to include at least the frame header (6 to 18 bytes). @@ -64,8 +61,7 @@ def get_frame_info(frame_buffer: ReadableBuffer) -> FrameInfo: """ def train_dict(samples: Iterable[ReadableBuffer], dict_size: int) -> ZstdDict: - """ - Return a ZstdDict representing a trained Zstandard dictionary. + """Return a ZstdDict representing a trained Zstandard dictionary. *samples* is an iterable of samples, where a sample is a bytes-like object representing a file. @@ -74,8 +70,7 @@ def train_dict(samples: Iterable[ReadableBuffer], dict_size: int) -> ZstdDict: """ def finalize_dict(zstd_dict: ZstdDict, /, samples: Iterable[ReadableBuffer], dict_size: int, level: int) -> ZstdDict: - """ - Return a ZstdDict representing a finalized Zstandard dictionary. + """Return a ZstdDict representing a finalized Zstandard dictionary. Given a custom content as a basis for dictionary, and a set of samples, finalize *zstd_dict* by adding headers and statistics according to the @@ -96,8 +91,7 @@ def finalize_dict(zstd_dict: ZstdDict, /, samples: Iterable[ReadableBuffer], dic def compress( data: ReadableBuffer, level: int | None = None, options: Mapping[int, int] | None = None, zstd_dict: ZstdDict | None = None ) -> bytes: - """ - Return Zstandard compressed *data* as bytes. + """Return Zstandard compressed *data* as bytes. *level* is an int specifying the compression level to use, defaulting to COMPRESSION_LEVEL_DEFAULT ('3'). @@ -110,8 +104,7 @@ def compress( """ def decompress(data: ReadableBuffer, zstd_dict: ZstdDict | None = None, options: Mapping[int, int] | None = None) -> bytes: - """ - Decompress one or more frames of Zstandard compressed *data*. + """Decompress one or more frames of Zstandard compressed *data*. *zstd_dict* is a ZstdDict object, a pre-trained Zstandard dictionary. See the function train_dict for how to train a ZstdDict on sample data. @@ -123,9 +116,7 @@ def decompress(data: ReadableBuffer, zstd_dict: ZstdDict | None = None, options: @final class CompressionParameter(enum.IntEnum): - """ - Compression parameters. - """ + """Compression parameters.""" compression_level = _zstd.ZSTD_c_compressionLevel window_log = _zstd.ZSTD_c_windowLog @@ -147,30 +138,25 @@ class CompressionParameter(enum.IntEnum): job_size = _zstd.ZSTD_c_jobSize overlap_log = _zstd.ZSTD_c_overlapLog def bounds(self) -> tuple[int, int]: - """ - Return the (lower, upper) int bounds of a compression parameter. + """Return the (lower, upper) int bounds of a compression parameter. Both the lower and upper bounds are inclusive. """ @final class DecompressionParameter(enum.IntEnum): - """ - Decompression parameters. - """ + """Decompression parameters.""" window_log_max = _zstd.ZSTD_d_windowLogMax def bounds(self) -> tuple[int, int]: - """ - Return the (lower, upper) int bounds of a decompression parameter. + """Return the (lower, upper) int bounds of a decompression parameter. Both the lower and upper bounds are inclusive. """ @final class Strategy(enum.IntEnum): - """ - Compression strategies, listed from fastest to strongest. + """Compression strategies, listed from fastest to strongest. Note that new strategies might be added in the future. Only the order (from fast to strong) is guaranteed, diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/compression/zstd/_zstdfile.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/compression/zstd/_zstdfile.pyi index 5b3cddc4da..8ba96fd7e3 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/compression/zstd/_zstdfile.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/compression/zstd/_zstdfile.pyi @@ -24,8 +24,7 @@ class _FileBinaryWrite(SupportsWrite[bytes], Protocol): def close(self) -> None: ... class ZstdFile(_streams.BaseStream): - """ - A file-like object providing transparent Zstandard (de)compression. + """A file-like object providing transparent Zstandard (de)compression. A ZstdFile can act as a wrapper for an existing file object, or refer directly to a named file on disk. @@ -48,8 +47,7 @@ class ZstdFile(_streams.BaseStream): options: Mapping[int, int] | None = None, zstd_dict: ZstdDict | None = None, ) -> None: - """ - Open a Zstandard compressed file in binary mode. + """Open a Zstandard compressed file in binary mode. *file* can be either an file-like object, or a file name to open. @@ -80,8 +78,7 @@ class ZstdFile(_streams.BaseStream): zstd_dict: ZstdDict | None = None, ) -> None: ... def write(self, data: ReadableBuffer, /) -> int: - """ - Write a bytes-like object *data* to the file. + """Write a bytes-like object *data* to the file. Returns the number of uncompressed bytes written, which is always the length of data in bytes. Note that due to buffering, @@ -90,8 +87,7 @@ class ZstdFile(_streams.BaseStream): """ def flush(self, mode: _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 1) -> bytes: # type: ignore[override] - """ - Flush remaining data to the underlying stream. + """Flush remaining data to the underlying stream. The mode argument can be FLUSH_BLOCK or FLUSH_FRAME. Abuse of this method will reduce compression ratio, use it only when necessary. @@ -103,16 +99,14 @@ class ZstdFile(_streams.BaseStream): """ def read(self, size: int | None = -1) -> bytes: - """ - Read up to size uncompressed bytes from the file. + """Read up to size uncompressed bytes from the file. If size is negative or omitted, read until EOF is reached. Returns b'' if the file is already at EOF. """ def read1(self, size: int | None = -1) -> bytes: - """ - Read up to size uncompressed bytes, while trying to avoid + """Read up to size uncompressed bytes, while trying to avoid making multiple reads from the underlying stream. Reads up to a buffer's worth of data if size is negative. @@ -120,23 +114,20 @@ class ZstdFile(_streams.BaseStream): """ def readinto(self, b: WriteableBuffer) -> int: - """ - Read bytes into b. + """Read bytes into b. Returns the number of bytes read (0 for EOF). """ def readinto1(self, b: WriteableBuffer) -> int: - """ - Read bytes into b, while trying to avoid making multiple reads + """Read bytes into b, while trying to avoid making multiple reads from the underlying stream. Returns the number of bytes read (0 for EOF). """ def readline(self, size: int | None = -1) -> bytes: - """ - Read a line of uncompressed bytes from the file. + """Read a line of uncompressed bytes from the file. The terminating newline (if present) is retained. If size is non-negative, no more than size bytes will be read (in which @@ -144,8 +135,7 @@ class ZstdFile(_streams.BaseStream): """ def seek(self, offset: int, whence: int = 0) -> int: - """ - Change the file position. + """Change the file position. The new position is specified by offset, relative to the position indicated by whence. Possible values for whence are: @@ -161,8 +151,7 @@ class ZstdFile(_streams.BaseStream): """ def peek(self, size: int = -1) -> bytes: - """ - Return buffered data without advancing the file position. + """Return buffered data without advancing the file position. Always returns at least one byte of data, unless at EOF. The exact number of bytes returned is unspecified. @@ -186,8 +175,7 @@ def open( errors: str | None = None, newline: str | None = None, ) -> ZstdFile: - """ - Open a Zstandard compressed file in binary or text mode. + """Open a Zstandard compressed file in binary or text mode. file can be either a file name (given as a str, bytes, or PathLike object), in which case the named file is opened, or it can be an existing file object diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/concurrent/futures/_base.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/concurrent/futures/_base.pyi index 3f398158ea..7b7a3059b2 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/concurrent/futures/_base.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/concurrent/futures/_base.pyi @@ -20,41 +20,29 @@ _STATE_TO_DESCRIPTION_MAP: dict[str, str] LOGGER: Logger class Error(Exception): - """ - Base class for all future-related exceptions. - """ + """Base class for all future-related exceptions.""" class CancelledError(Error): - """ - The Future was cancelled. - """ + """The Future was cancelled.""" if sys.version_info >= (3, 11): from builtins import TimeoutError as TimeoutError else: class TimeoutError(Error): - """ - The operation exceeded the given deadline. - """ + """The operation exceeded the given deadline.""" class InvalidStateError(Error): - """ - The operation is not allowed in this state. - """ + """The operation is not allowed in this state.""" class BrokenExecutor(RuntimeError): - """ - Raised when a executor has become non-functional after a severe failure. - """ + """Raised when a executor has become non-functional after a severe failure.""" _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) _P = ParamSpec("_P") class Future(Generic[_T]): - """ - Represents the result of an asynchronous computation. - """ + """Represents the result of an asynchronous computation.""" _condition: threading.Condition _state: str @@ -62,31 +50,23 @@ class Future(Generic[_T]): _exception: BaseException | None _waiters: list[_Waiter] def cancel(self) -> bool: - """ - Cancel the future if possible. + """Cancel the future if possible. Returns True if the future was cancelled, False otherwise. A future cannot be cancelled if it is running or has already completed. """ def cancelled(self) -> bool: - """ - Return True if the future was cancelled. - """ + """Return True if the future was cancelled.""" def running(self) -> bool: - """ - Return True if the future is currently executing. - """ + """Return True if the future is currently executing.""" def done(self) -> bool: - """ - Return True if the future was cancelled or finished executing. - """ + """Return True if the future was cancelled or finished executing.""" def add_done_callback(self, fn: Callable[[Future[_T]], object]) -> None: - """ - Attaches a callable that will be called when the future finishes. + """Attaches a callable that will be called when the future finishes. Args: fn: A callable that will be called with this future as its only @@ -98,8 +78,7 @@ class Future(Generic[_T]): """ def result(self, timeout: float | None = None) -> _T: - """ - Return the result of the call that the future represents. + """Return the result of the call that the future represents. Args: timeout: The number of seconds to wait for the result if the future @@ -116,8 +95,7 @@ class Future(Generic[_T]): """ def set_running_or_notify_cancel(self) -> bool: - """ - Mark the future as running or process any cancel notifications. + """Mark the future as running or process any cancel notifications. Should only be used by Executor implementations and unit tests. @@ -141,15 +119,13 @@ class Future(Generic[_T]): """ def set_result(self, result: _T) -> None: - """ - Sets the return value of work associated with the future. + """Sets the return value of work associated with the future. Should only be used by Executor implementations and unit tests. """ def exception(self, timeout: float | None = None) -> BaseException | None: - """ - Return the exception raised by the call that the future represents. + """Return the exception raised by the call that the future represents. Args: timeout: The number of seconds to wait for the exception if the @@ -167,27 +143,22 @@ class Future(Generic[_T]): """ def set_exception(self, exception: BaseException | None) -> None: - """ - Sets the result of the future as being the given exception. + """Sets the result of the future as being the given exception. Should only be used by Executor implementations and unit tests. """ def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ class Executor: - """ - This is an abstract base class for concrete asynchronous executors. - """ + """This is an abstract base class for concrete asynchronous executors.""" def submit(self, fn: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: - """ - Submits a callable to be executed with the given arguments. + """Submits a callable to be executed with the given arguments. Schedules the callable to be executed as fn(*args, **kwargs) and returns a Future instance representing the execution of the callable. @@ -204,8 +175,7 @@ class Executor: chunksize: int = 1, buffersize: int | None = None, ) -> Iterator[_T]: - """ - Returns an iterator equivalent to map(fn, iter). + """Returns an iterator equivalent to map(fn, iter). Args: fn: A callable that will take as many arguments as there are @@ -235,8 +205,7 @@ class Executor: def map( self, fn: Callable[..., _T], *iterables: Iterable[Any], timeout: float | None = None, chunksize: int = 1 ) -> Iterator[_T]: - """ - Returns an iterator equivalent to map(fn, iter). + """Returns an iterator equivalent to map(fn, iter). Args: fn: A callable that will take as many arguments as there are @@ -264,8 +233,7 @@ class Executor: """ def shutdown(self, wait: bool = True, *, cancel_futures: bool = False) -> None: - """ - Clean-up the resources associated with the Executor. + """Clean-up the resources associated with the Executor. It is safe to call this method several times. Otherwise, no other methods can be called after this one. @@ -295,8 +263,7 @@ class _AsCompletedFuture(Protocol[_T_co]): def result(self, timeout: float | None = None) -> _T_co: ... def as_completed(fs: Iterable[_AsCompletedFuture[_T]], timeout: float | None = None) -> Iterator[Future[_T]]: - """ - An iterator over the given futures that yields each as it completes. + """An iterator over the given futures that yields each as it completes. Args: fs: The sequence of Futures (possibly created by different Executors) to @@ -315,16 +282,13 @@ def as_completed(fs: Iterable[_AsCompletedFuture[_T]], timeout: float | None = N """ class DoneAndNotDoneFutures(NamedTuple, Generic[_T]): - """ - DoneAndNotDoneFutures(done, not_done) - """ + """DoneAndNotDoneFutures(done, not_done)""" done: set[Future[_T]] not_done: set[Future[_T]] def wait(fs: Iterable[Future[_T]], timeout: float | None = None, return_when: str = "ALL_COMPLETED") -> DoneAndNotDoneFutures[_T]: - """ - Wait for the futures in the given sequence to complete. + """Wait for the futures in the given sequence to complete. Args: fs: The sequence of Futures (possibly created by different Executors) to @@ -350,9 +314,7 @@ def wait(fs: Iterable[Future[_T]], timeout: float | None = None, return_when: st """ class _Waiter: - """ - Provides the event that wait() and as_completed() block on. - """ + """Provides the event that wait() and as_completed() block on.""" event: threading.Event finished_futures: list[Future[Any]] @@ -361,21 +323,15 @@ class _Waiter: def add_cancelled(self, future: Future[Any]) -> None: ... class _AsCompletedWaiter(_Waiter): - """ - Used by as_completed(). - """ + """Used by as_completed().""" lock: threading.Lock class _FirstCompletedWaiter(_Waiter): - """ - Used by wait(return_when=FIRST_COMPLETED). - """ + """Used by wait(return_when=FIRST_COMPLETED).""" class _AllCompletedWaiter(_Waiter): - """ - Used by wait(return_when=FIRST_EXCEPTION and ALL_COMPLETED). - """ + """Used by wait(return_when=FIRST_EXCEPTION and ALL_COMPLETED).""" num_pending_calls: int stop_on_exception: bool @@ -383,9 +339,7 @@ class _AllCompletedWaiter(_Waiter): def __init__(self, num_pending_calls: int, stop_on_exception: bool) -> None: ... class _AcquireFutures: - """ - A context manager that does an ordered acquire of Future conditions. - """ + """A context manager that does an ordered acquire of Future conditions.""" futures: Iterable[Future[Any]] def __init__(self, futures: Iterable[Future[Any]]) -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/concurrent/futures/interpreter.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/concurrent/futures/interpreter.pyi index 2aefcc1a71..b3dfe473d2 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/concurrent/futures/interpreter.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/concurrent/futures/interpreter.pyi @@ -60,9 +60,7 @@ if sys.version_info >= (3, 14): def run(self, task: _Task) -> None: ... # type: ignore[override] class BrokenInterpreterPool(BrokenThreadPool): - """ - Raised when a worker thread in an InterpreterPoolExecutor failed initializing. - """ + """Raised when a worker thread in an InterpreterPoolExecutor failed initializing.""" class InterpreterPoolExecutor(ThreadPoolExecutor): BROKEN: type[BrokenInterpreterPool] @@ -86,8 +84,7 @@ if sys.version_info >= (3, 14): initargs: tuple[()] = (), shared: Mapping[str, object] | None = None, ) -> None: - """ - Initializes a new InterpreterPoolExecutor instance. + """Initializes a new InterpreterPoolExecutor instance. Args: max_workers: The maximum number of interpreters that can be used to diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/concurrent/futures/process.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/concurrent/futures/process.pyi index a020c0c658..9908873ee9 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/concurrent/futures/process.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/concurrent/futures/process.pyi @@ -114,9 +114,7 @@ class _CallItem: def __init__(self, work_id: int, fn: Callable[..., Any], args: Iterable[Any], kwargs: Mapping[str, Any]) -> None: ... class _SafeQueue(Queue[Future[Any]]): - """ - Safe Queue set exception to the future object linked to a job - """ + """Safe Queue set exception to the future object linked to a job""" pending_work_items: dict[int, _WorkItem[Any]] if sys.version_info < (3, 12): @@ -145,13 +143,10 @@ class _SafeQueue(Queue[Future[Any]]): def _on_queue_feeder_error(self, e: Exception, obj: _CallItem) -> None: ... def _get_chunks(*iterables: Any, chunksize: int) -> Generator[tuple[Any, ...], None, None]: - """ - Iterates over zip()ed iterables in chunks. - """ + """Iterates over zip()ed iterables in chunks.""" def _process_chunk(fn: Callable[..., _T], chunk: Iterable[tuple[Any, ...]]) -> list[_T]: - """ - Processes a chunk of an iterable passed to map. + """Processes a chunk of an iterable passed to map. Runs the function passed to map() on a chunk of the iterable passed to map. @@ -167,17 +162,13 @@ if sys.version_info >= (3, 11): exception: Exception | None = None, exit_pid: int | None = None, ) -> None: - """ - Safely send back the given result or exception - """ + """Safely send back the given result or exception""" else: def _sendback_result( result_queue: SimpleQueue[_WorkItem[Any]], work_id: int, result: Any | None = None, exception: Exception | None = None ) -> None: - """ - Safely send back the given result or exception - """ + """Safely send back the given result or exception""" if sys.version_info >= (3, 11): def _process_worker( @@ -187,8 +178,7 @@ if sys.version_info >= (3, 11): initargs: tuple[Unpack[_Ts]], max_tasks: int | None = None, ) -> None: - """ - Evaluates calls from call_queue and places the results in result_queue. + """Evaluates calls from call_queue and places the results in result_queue. This worker is run in a separate process. @@ -208,8 +198,7 @@ else: initializer: Callable[[Unpack[_Ts]], object] | None, initargs: tuple[Unpack[_Ts]], ) -> None: - """ - Evaluates calls from call_queue and places the results in result_queue. + """Evaluates calls from call_queue and places the results in result_queue. This worker is run in a separate process. @@ -223,8 +212,7 @@ else: """ class _ExecutorManagerThread(Thread): - """ - Manages the communication between this process and the worker processes. + """Manages the communication between this process and the worker processes. The manager is run in a local thread. @@ -260,15 +248,13 @@ _system_limited: bool | None def _check_system_limits() -> None: ... def _chain_from_iterable_of_lists(iterable: Iterable[MutableSequence[Any]]) -> Any: - """ - Specialized implementation of itertools.chain.from_iterable. + """Specialized implementation of itertools.chain.from_iterable. Each item in *iterable* should be a list. This function is careful not to keep references to yielded objects. """ class BrokenProcessPool(BrokenExecutor): - """ - Raised when a process in a ProcessPoolExecutor terminated abruptly + """Raised when a process in a ProcessPoolExecutor terminated abruptly while a future was in the running state. """ @@ -299,8 +285,7 @@ class ProcessPoolExecutor(Executor): *, max_tasks_per_child: int | None = None, ) -> None: - """ - Initializes a new ProcessPoolExecutor instance. + """Initializes a new ProcessPoolExecutor instance. Args: max_workers: The maximum number of processes that can be used to @@ -348,8 +333,7 @@ class ProcessPoolExecutor(Executor): initializer: Callable[[], object] | None = None, initargs: tuple[()] = (), ) -> None: - """ - Initializes a new ProcessPoolExecutor instance. + """Initializes a new ProcessPoolExecutor instance. Args: max_workers: The maximum number of processes that can be used to @@ -391,8 +375,7 @@ class ProcessPoolExecutor(Executor): if sys.version_info >= (3, 14): def kill_workers(self) -> None: - """ - Attempts to kill the executor's workers. + """Attempts to kill the executor's workers. Iterates through all of the current worker processes and kills each one that is still alive. @@ -402,8 +385,7 @@ class ProcessPoolExecutor(Executor): """ def terminate_workers(self) -> None: - """ - Attempts to terminate the executor's workers. + """Attempts to terminate the executor's workers. Iterates through all of the current worker processes and terminates each one that is still alive. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/concurrent/futures/thread.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/concurrent/futures/thread.pyi index c06c3916e2..3e8b9ed594 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/concurrent/futures/thread.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/concurrent/futures/thread.pyi @@ -62,8 +62,7 @@ if sys.version_info >= (3, 14): def __init__(self, future: Future[Any], task: _Task) -> None: ... def run(self, ctx: WorkerContext) -> None: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ @@ -79,8 +78,7 @@ else: def __init__(self, future: Future[_S], fn: Callable[..., _S], args: Iterable[Any], kwargs: Mapping[str, Any]) -> None: ... def run(self) -> None: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ @@ -93,9 +91,7 @@ else: ) -> None: ... class BrokenThreadPool(BrokenExecutor): - """ - Raised when a worker thread in a ThreadPoolExecutor failed initializing. - """ + """Raised when a worker thread in a ThreadPoolExecutor failed initializing.""" class ThreadPoolExecutor(Executor): if sys.version_info >= (3, 14): @@ -136,8 +132,7 @@ class ThreadPoolExecutor(Executor): initializer: Callable[[], object] | None = None, initargs: tuple[()] = (), ) -> None: - """ - Initializes a new ThreadPoolExecutor instance. + """Initializes a new ThreadPoolExecutor instance. Args: max_workers: The maximum number of threads that can be used to diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/configparser.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/configparser.pyi index ac08fed0e1..c00fda29fd 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/configparser.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/configparser.pyi @@ -272,9 +272,7 @@ DEFAULTSECT: Final = "DEFAULT" MAX_INTERPOLATION_DEPTH: Final = 10 class Interpolation: - """ - Dummy interpolation that passes the value through with no changes. - """ + """Dummy interpolation that passes the value through with no changes.""" def before_get(self, parser: _Parser, section: _SectionName, option: str, value: str, defaults: _Section) -> str: ... def before_set(self, parser: _Parser, section: _SectionName, option: str, value: str) -> str: ... @@ -282,8 +280,7 @@ class Interpolation: def before_write(self, parser: _Parser, section: _SectionName, option: str, value: str) -> str: ... class BasicInterpolation(Interpolation): - """ - Interpolation as implemented in the classic ConfigParser. + """Interpolation as implemented in the classic ConfigParser. The option values can contain format strings which refer to other values in the same section, or values in the special default section. @@ -299,24 +296,20 @@ class BasicInterpolation(Interpolation): """ class ExtendedInterpolation(Interpolation): - """ - Advanced variant of interpolation, supports the syntax used by + """Advanced variant of interpolation, supports the syntax used by `zc.buildout`. Enables interpolation between sections. """ if sys.version_info < (3, 13): class LegacyInterpolation(Interpolation): - """ - Deprecated interpolation used in old versions of ConfigParser. + """Deprecated interpolation used in old versions of ConfigParser. Use BasicInterpolation or ExtendedInterpolation instead. """ def before_get(self, parser: _Parser, section: _SectionName, option: str, value: str, vars: _Section) -> str: ... class RawConfigParser(_Parser): - """ - ConfigParser that does not do interpolation. - """ + """ConfigParser that does not do interpolation.""" _SECT_TMPL: ClassVar[str] # undocumented _OPT_TMPL: ClassVar[str] # undocumented @@ -439,40 +432,32 @@ class RawConfigParser(_Parser): def __contains__(self, key: object) -> bool: ... def defaults(self) -> _Section: ... def sections(self) -> _SectionNameList: - """ - Return a list of section names, excluding [DEFAULT] - """ + """Return a list of section names, excluding [DEFAULT]""" def add_section(self, section: _SectionName) -> None: - """ - Create a new section in the configuration. + """Create a new section in the configuration. Raise DuplicateSectionError if a section by the specified name already exists. Raise ValueError if name is DEFAULT. """ def has_section(self, section: _SectionName) -> bool: - """ - Indicate whether the named section is present in the configuration. + """Indicate whether the named section is present in the configuration. The DEFAULT section is not acknowledged. """ def options(self, section: _SectionName) -> list[str]: - """ - Return a list of option names for the given section name. - """ + """Return a list of option names for the given section name.""" def has_option(self, section: _SectionName, option: str) -> bool: - """ - Check for the existence of a given option in a given section. + """Check for the existence of a given option in a given section. If the specified `section` is None or an empty string, DEFAULT is assumed. If the specified `section` does not exist, returns False. """ def read(self, filenames: StrOrBytesPath | Iterable[StrOrBytesPath], encoding: str | None = None) -> list[str]: - """ - Read and parse a filename or an iterable of filenames. + """Read and parse a filename or an iterable of filenames. Files that cannot be opened are silently ignored; this is designed so that you can specify an iterable of potential @@ -485,8 +470,7 @@ class RawConfigParser(_Parser): """ def read_file(self, f: Iterable[str], source: str | None = None) -> None: - """ - Like read() but the argument must be a file-like object. + """Like read() but the argument must be a file-like object. The `f` argument must be iterable, returning one line at a time. Optional second argument is the `source` specifying the name of the @@ -495,13 +479,10 @@ class RawConfigParser(_Parser): """ def read_string(self, string: str, source: str = "") -> None: - """ - Read configuration from a given string. - """ + """Read configuration from a given string.""" def read_dict(self, dictionary: Mapping[str, Mapping[str, Any]], source: str = "") -> None: - """ - Read configuration from a dictionary. + """Read configuration from a dictionary. Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type @@ -548,8 +529,7 @@ class RawConfigParser(_Parser): # This is incompatible with MutableMapping so we ignore the type @overload # type: ignore[override] def get(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> str | MaybeNone: - """ - Get an option value for a given section. + """Get an option value for a given section. If `vars` is provided, it must be a dictionary. The option is looked up in `vars` (if provided), `section`, and in `DEFAULTSECT` in that order. @@ -570,8 +550,7 @@ class RawConfigParser(_Parser): ) -> str | _T | MaybeNone: ... @overload def items(self, *, raw: bool = False, vars: _Section | None = None) -> ItemsView[str, SectionProxy]: - """ - Return a list of (name, value) tuples for each option in a section. + """Return a list of (name, value) tuples for each option in a section. All % interpolations are expanded in the return values, based on the defaults passed into the constructor, unless the optional argument @@ -585,13 +564,10 @@ class RawConfigParser(_Parser): @overload def items(self, section: _SectionName, raw: bool = False, vars: _Section | None = None) -> list[tuple[str, str]]: ... def set(self, section: _SectionName, option: str, value: str | None = None) -> None: - """ - Set an option. - """ + """Set an option.""" def write(self, fp: SupportsWrite[str], space_around_delimiters: bool = True) -> None: - """ - Write an .ini-format representation of the configuration state. + """Write an .ini-format representation of the configuration state. If `space_around_delimiters` is True (the default), delimiters between keys and values are surrounded by spaces. @@ -601,29 +577,22 @@ class RawConfigParser(_Parser): """ def remove_option(self, section: _SectionName, option: str) -> bool: - """ - Remove an option. - """ + """Remove an option.""" def remove_section(self, section: _SectionName) -> bool: - """ - Remove a file section. - """ + """Remove a file section.""" def optionxform(self, optionstr: str) -> str: ... @property def converters(self) -> ConverterMapping: ... class ConfigParser(RawConfigParser): - """ - ConfigParser implementing interpolation. - """ + """ConfigParser implementing interpolation.""" # This is incompatible with MutableMapping so we ignore the type @overload # type: ignore[override] def get(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> str: - """ - Get an option value for a given section. + """Get an option value for a given section. If `vars` is provided, it must be a dictionary. The option is looked up in `vars` (if provided), `section`, and in `DEFAULTSECT` in that order. @@ -645,19 +614,13 @@ class ConfigParser(RawConfigParser): if sys.version_info < (3, 12): class SafeConfigParser(ConfigParser): # deprecated alias - """ - ConfigParser alias for backwards compatibility purposes. - """ + """ConfigParser alias for backwards compatibility purposes.""" class SectionProxy(MutableMapping[str, str]): - """ - A proxy for a single section from a parser. - """ + """A proxy for a single section from a parser.""" def __init__(self, parser: RawConfigParser, name: str) -> None: - """ - Creates a view on a section of the specified `name` in `parser`. - """ + """Creates a view on a section of the specified `name` in `parser`.""" def __getitem__(self, key: str) -> str: ... def __setitem__(self, key: str, value: str) -> None: ... @@ -681,8 +644,7 @@ class SectionProxy(MutableMapping[str, str]): _impl: Any | None = None, **kwargs: Any, # passed to the underlying parser's get() method ) -> str | None: - """ - Get an option value. + """Get an option value. Unless `fallback` is provided, `None` will be returned if the option is not found. @@ -717,8 +679,7 @@ class SectionProxy(MutableMapping[str, str]): def __getattr__(self, key: str) -> Callable[..., Any]: ... class ConverterMapping(MutableMapping[str, _ConverterCallback | None]): - """ - Enables reuse of get*() methods between the parser and section proxies. + """Enables reuse of get*() methods between the parser and section proxies. If a parser class implements a getter directly, the value for the given key will be ``None``. The presence of the converter name here enables @@ -734,24 +695,19 @@ class ConverterMapping(MutableMapping[str, _ConverterCallback | None]): def __len__(self) -> int: ... class Error(Exception): - """ - Base class for ConfigParser exceptions. - """ + """Base class for ConfigParser exceptions.""" message: str def __init__(self, msg: str = "") -> None: ... class NoSectionError(Error): - """ - Raised when no section matches a requested option. - """ + """Raised when no section matches a requested option.""" section: _SectionName def __init__(self, section: _SectionName) -> None: ... class DuplicateSectionError(Error): - """ - Raised when a section is repeated in an input source. + """Raised when a section is repeated in an input source. Possible repetitions that raise this exception are: multiple creation using the API or in strict parsers when a section is found more than once @@ -764,8 +720,7 @@ class DuplicateSectionError(Error): def __init__(self, section: _SectionName, source: str | None = None, lineno: int | None = None) -> None: ... class DuplicateOptionError(Error): - """ - Raised by strict parsers when an option is repeated in an input source. + """Raised by strict parsers when an option is repeated in an input source. Current implementation raises this exception only when an option is found more than once in a single file, string or dictionary. @@ -778,50 +733,39 @@ class DuplicateOptionError(Error): def __init__(self, section: _SectionName, option: str, source: str | None = None, lineno: int | None = None) -> None: ... class NoOptionError(Error): - """ - A requested option was not found. - """ + """A requested option was not found.""" section: _SectionName option: str def __init__(self, option: str, section: _SectionName) -> None: ... class InterpolationError(Error): - """ - Base class for interpolation-related exceptions. - """ + """Base class for interpolation-related exceptions.""" section: _SectionName option: str def __init__(self, option: str, section: _SectionName, msg: str) -> None: ... class InterpolationDepthError(InterpolationError): - """ - Raised when substitutions are nested too deeply. - """ + """Raised when substitutions are nested too deeply.""" def __init__(self, option: str, section: _SectionName, rawval: object) -> None: ... class InterpolationMissingOptionError(InterpolationError): - """ - A string substitution required a setting which was not available. - """ + """A string substitution required a setting which was not available.""" reference: str def __init__(self, option: str, section: _SectionName, rawval: object, reference: str) -> None: ... class InterpolationSyntaxError(InterpolationError): - """ - Raised when the source text contains invalid syntax. + """Raised when the source text contains invalid syntax. Current implementation raises this exception when the source text into which substitutions are made does not conform to the required syntax. """ class ParsingError(Error): - """ - Raised when a configuration file does not follow legal syntax. - """ + """Raised when a configuration file does not follow legal syntax.""" source: str errors: list[tuple[int, str]] @@ -836,9 +780,7 @@ class ParsingError(Error): def append(self, lineno: int, line: str) -> None: ... class MissingSectionHeaderError(ParsingError): - """ - Raised when a key-value pair is found before any section header. - """ + """Raised when a key-value pair is found before any section header.""" lineno: int line: str @@ -846,9 +788,7 @@ class MissingSectionHeaderError(ParsingError): if sys.version_info >= (3, 13): class MultilineContinuationError(ParsingError): - """ - Raised when a key without value is followed by continuation line - """ + """Raised when a key without value is followed by continuation line""" lineno: int line: str @@ -856,8 +796,7 @@ if sys.version_info >= (3, 13): if sys.version_info >= (3, 14): class UnnamedSectionDisabledError(Error): - """ - Raised when an attempt to use UNNAMED_SECTION is made with the + """Raised when an attempt to use UNNAMED_SECTION is made with the feature disabled. """ @@ -865,8 +804,7 @@ if sys.version_info >= (3, 14): def __init__(self) -> None: ... class InvalidWriteError(Error): - """ - Raised when attempting to write data that the parser would read back differently. + """Raised when attempting to write data that the parser would read back differently. ex: writing a key which begins with the section header pattern would read back as a new section """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/contextlib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/contextlib.pyi index 22229bbca6..6b54d06027 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/contextlib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/contextlib.pyi @@ -51,53 +51,38 @@ _CM_EF = TypeVar("_CM_EF", bound=AbstractContextManager[Any, Any] | _ExitFunc) # allowlist for use as a Protocol. @runtime_checkable class AbstractContextManager(ABC, Protocol[_T_co, _ExitT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] - """ - An abstract base class for context managers. - """ + """An abstract base class for context managers.""" def __enter__(self) -> _T_co: - """ - Return `self` upon entering the runtime context. - """ + """Return `self` upon entering the runtime context.""" @abstractmethod def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / ) -> _ExitT_co: - """ - Raise any exception triggered within the runtime context. - """ + """Raise any exception triggered within the runtime context.""" # mypy and pyright object to this being both ABC and Protocol. # At runtime it inherits from ABC and is not a Protocol, but it is on the # allowlist for use as a Protocol. @runtime_checkable class AbstractAsyncContextManager(ABC, Protocol[_T_co, _ExitT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] - """ - An abstract base class for asynchronous context managers. - """ + """An abstract base class for asynchronous context managers.""" async def __aenter__(self) -> _T_co: - """ - Return `self` upon entering the runtime context. - """ + """Return `self` upon entering the runtime context.""" @abstractmethod async def __aexit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / ) -> _ExitT_co: - """ - Raise any exception triggered within the runtime context. - """ + """Raise any exception triggered within the runtime context.""" class ContextDecorator: - """ - A base class or mixin that enables context managers to work as decorators. - """ + """A base class or mixin that enables context managers to work as decorators.""" def _recreate_cm(self) -> Self: - """ - Return a recreated instance of self. + """Return a recreated instance of self. Allows an otherwise one-shot context manager like _GeneratorContextManager to support use as @@ -110,9 +95,7 @@ class ContextDecorator: def __call__(self, func: _F) -> _F: ... class _GeneratorContextManagerBase(Generic[_G_co]): - """ - Shared functionality for @contextmanager and @asynccontextmanager. - """ + """Shared functionality for @contextmanager and @asynccontextmanager.""" # Ideally this would use ParamSpec, but that requires (*args, **kwargs), which this isn't. see #6676 def __init__(self, func: Callable[..., _G_co], args: tuple[Any, ...], kwds: dict[str, Any]) -> None: ... @@ -126,17 +109,14 @@ class _GeneratorContextManager( AbstractContextManager[_T_co, bool | None], ContextDecorator, ): - """ - Helper for @contextmanager decorator. - """ + """Helper for @contextmanager decorator.""" def __exit__( self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> bool | None: ... def contextmanager(func: Callable[_P, Iterator[_T_co]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: - """ - @contextmanager decorator. + """@contextmanager decorator. Typical usage: @@ -167,14 +147,10 @@ if sys.version_info >= (3, 10): _AF = TypeVar("_AF", bound=Callable[..., Awaitable[Any]]) class AsyncContextDecorator: - """ - A base class or mixin that enables async context managers to work as decorators. - """ + """A base class or mixin that enables async context managers to work as decorators.""" def _recreate_cm(self) -> Self: - """ - Return a recreated instance of self. - """ + """Return a recreated instance of self.""" def __call__(self, func: _AF) -> _AF: ... @@ -183,9 +159,7 @@ if sys.version_info >= (3, 10): AbstractAsyncContextManager[_T_co, bool | None], AsyncContextDecorator, ): - """ - Helper for @asynccontextmanager decorator. - """ + """Helper for @asynccontextmanager decorator.""" async def __aexit__( self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None @@ -195,17 +169,14 @@ else: class _AsyncGeneratorContextManager( _GeneratorContextManagerBase[AsyncGenerator[_T_co, _SendT_contra]], AbstractAsyncContextManager[_T_co, bool | None] ): - """ - Helper for @asynccontextmanager decorator. - """ + """Helper for @asynccontextmanager decorator.""" async def __aexit__( self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> bool | None: ... def asynccontextmanager(func: Callable[_P, AsyncIterator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]: - """ - @asynccontextmanager decorator. + """@asynccontextmanager decorator. Typical usage: @@ -238,8 +209,7 @@ class _SupportsClose(Protocol): _SupportsCloseT = TypeVar("_SupportsCloseT", bound=_SupportsClose) class closing(AbstractContextManager[_SupportsCloseT, None]): - """ - Context to automatically close something at the end of a block. + """Context to automatically close something at the end of a block. Code like this: @@ -265,8 +235,7 @@ if sys.version_info >= (3, 10): _SupportsAcloseT = TypeVar("_SupportsAcloseT", bound=_SupportsAclose) class aclosing(AbstractAsyncContextManager[_SupportsAcloseT, None]): - """ - Async context manager for safely finalizing an asynchronously cleaned-up + """Async context manager for safely finalizing an asynchronously cleaned-up resource such as an async generator, calling its ``aclose()`` method. Code like this: @@ -287,8 +256,7 @@ if sys.version_info >= (3, 10): async def __aexit__(self, *exc_info: Unused) -> None: ... class suppress(AbstractContextManager[None, bool]): - """ - Context manager to suppress specified exceptions + """Context manager to suppress specified exceptions After the exception is suppressed, execution proceeds with the next statement following the with statement. @@ -310,8 +278,7 @@ class _RedirectStream(AbstractContextManager[_T_io, None]): ) -> None: ... class redirect_stdout(_RedirectStream[_T_io]): - """ - Context manager for temporarily redirecting stdout to another file. + """Context manager for temporarily redirecting stdout to another file. # How to send help() to stderr with redirect_stdout(sys.stderr): @@ -324,26 +291,20 @@ class redirect_stdout(_RedirectStream[_T_io]): """ class redirect_stderr(_RedirectStream[_T_io]): - """ - Context manager for temporarily redirecting stderr to another file. - """ + """Context manager for temporarily redirecting stderr to another file.""" class _BaseExitStack(Generic[_ExitT_co]): - """ - A base class for ExitStack and AsyncExitStack. - """ + """A base class for ExitStack and AsyncExitStack.""" def enter_context(self, cm: AbstractContextManager[_T, _ExitT_co]) -> _T: - """ - Enters the supplied context manager. + """Enters the supplied context manager. If successful, also pushes its __exit__ method as a callback and returns the result of the __enter__ method. """ def push(self, exit: _CM_EF) -> _CM_EF: - """ - Registers a callback with the standard __exit__ method signature. + """Registers a callback with the standard __exit__ method signature. Can suppress exceptions the same way __exit__ method can. Also accepts any object with an __exit__ method (registering a call @@ -351,22 +312,18 @@ class _BaseExitStack(Generic[_ExitT_co]): """ def callback(self, callback: Callable[_P, _T], /, *args: _P.args, **kwds: _P.kwargs) -> Callable[_P, _T]: - """ - Registers an arbitrary callback and arguments. + """Registers an arbitrary callback and arguments. Cannot suppress exceptions. """ def pop_all(self) -> Self: - """ - Preserve the context stack by transferring it to a new instance. - """ + """Preserve the context stack by transferring it to a new instance.""" # In reality this is a subclass of `AbstractContextManager`; # see #7961 for why we don't do that in the stub class ExitStack(_BaseExitStack[_ExitT_co], metaclass=abc.ABCMeta): - """ - Context manager for dynamic management of a stack of exit callbacks. + """Context manager for dynamic management of a stack of exit callbacks. For example: with ExitStack() as stack: @@ -377,9 +334,7 @@ class ExitStack(_BaseExitStack[_ExitT_co], metaclass=abc.ABCMeta): """ def close(self) -> None: - """ - Immediately unwind the context stack. - """ + """Immediately unwind the context stack.""" def __enter__(self) -> Self: ... def __exit__( @@ -394,8 +349,7 @@ _ACM_EF = TypeVar("_ACM_EF", bound=AbstractAsyncContextManager[Any, Any] | _Exit # In reality this is a subclass of `AbstractAsyncContextManager`; # see #7961 for why we don't do that in the stub class AsyncExitStack(_BaseExitStack[_ExitT_co], metaclass=abc.ABCMeta): - """ - Async context manager for dynamic management of a stack of exit + """Async context manager for dynamic management of a stack of exit callbacks. For example: @@ -408,16 +362,14 @@ class AsyncExitStack(_BaseExitStack[_ExitT_co], metaclass=abc.ABCMeta): """ async def enter_async_context(self, cm: AbstractAsyncContextManager[_T, _ExitT_co]) -> _T: - """ - Enters the supplied async context manager. + """Enters the supplied async context manager. If successful, also pushes its __aexit__ method as a callback and returns the result of the __aenter__ method. """ def push_async_exit(self, exit: _ACM_EF) -> _ACM_EF: - """ - Registers a coroutine function with the standard __aexit__ method + """Registers a coroutine function with the standard __aexit__ method signature. Can suppress exceptions the same way __aexit__ method can. @@ -428,16 +380,13 @@ class AsyncExitStack(_BaseExitStack[_ExitT_co], metaclass=abc.ABCMeta): def push_async_callback( self, callback: Callable[_P, Awaitable[_T]], /, *args: _P.args, **kwds: _P.kwargs ) -> Callable[_P, Awaitable[_T]]: - """ - Registers an arbitrary coroutine function and arguments. + """Registers an arbitrary coroutine function and arguments. Cannot suppress exceptions. """ async def aclose(self) -> None: - """ - Immediately unwind the context stack. - """ + """Immediately unwind the context stack.""" async def __aenter__(self) -> Self: ... async def __aexit__( @@ -446,8 +395,7 @@ class AsyncExitStack(_BaseExitStack[_ExitT_co], metaclass=abc.ABCMeta): if sys.version_info >= (3, 10): class nullcontext(AbstractContextManager[_T, None], AbstractAsyncContextManager[_T, None]): - """ - Context manager that does no additional processing. + """Context manager that does no additional processing. Used as a stand-in for a normal context manager, when a particular block of code is only sometimes used with a normal context manager: @@ -469,8 +417,7 @@ if sys.version_info >= (3, 10): else: class nullcontext(AbstractContextManager[_T, None]): - """ - Context manager that does no additional processing. + """Context manager that does no additional processing. Used as a stand-in for a normal context manager, when a particular block of code is only sometimes used with a normal context manager: @@ -492,9 +439,7 @@ if sys.version_info >= (3, 11): _T_fd_or_any_path = TypeVar("_T_fd_or_any_path", bound=FileDescriptorOrPath) class chdir(AbstractContextManager[None, None], Generic[_T_fd_or_any_path]): - """ - Non thread-safe context manager to change the current working directory. - """ + """Non thread-safe context manager to change the current working directory.""" path: _T_fd_or_any_path def __init__(self, path: _T_fd_or_any_path) -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/copy.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/copy.pyi index 0c669ee76d..9c8a3eb876 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/copy.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/copy.pyi @@ -68,15 +68,13 @@ PyStringMap: Any # Note: memo and _nil are internal kwargs. def deepcopy(x: _T, memo: dict[int, Any] | None = None, _nil: Any = []) -> _T: - """ - Deep copy operation on arbitrary Python objects. + """Deep copy operation on arbitrary Python objects. See the module's __doc__ string for more info. """ def copy(x: _T) -> _T: - """ - Shallow copy operation on arbitrary Python objects. + """Shallow copy operation on arbitrary Python objects. See the module's __doc__ string for more info. """ @@ -84,8 +82,7 @@ def copy(x: _T) -> _T: if sys.version_info >= (3, 13): __all__ += ["replace"] def replace(obj: _SR, /, **changes: Any) -> _SR: - """ - Return a new object replacing specified fields with new values. + """Return a new object replacing specified fields with new values. This is especially useful for immutable objects, like named tuples or frozen dataclasses. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/copyreg.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/copyreg.pyi index 4113a017be..9afdc2f62d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/copyreg.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/copyreg.pyi @@ -21,14 +21,10 @@ def pickle( ) -> None: ... def constructor(object: Callable[[_Reduce[_T]], _T]) -> None: ... def add_extension(module: Hashable, name: Hashable, code: SupportsInt) -> None: - """ - Register an extension code. - """ + """Register an extension code.""" def remove_extension(module: Hashable, name: Hashable, code: int) -> None: - """ - Unregister an extension code. For testing only. - """ + """Unregister an extension code. For testing only.""" def clear_extension_cache() -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/crypt.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/crypt.pyi index 380040af31..8bfe1eec2e 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/crypt.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/crypt.pyi @@ -14,8 +14,7 @@ if sys.platform != "win32": total_size: int class _Method(_MethodBase): - """ - Class representing a salt method per the Modular Crypt Format or the + """Class representing a salt method per the Modular Crypt Format or the legacy 2-character crypt method. """ @@ -26,15 +25,13 @@ if sys.platform != "win32": METHOD_BLOWFISH: Final[_Method] methods: list[_Method] def mksalt(method: _Method | None = None, *, rounds: int | None = None) -> str: - """ - Generate a salt for the specified method. + """Generate a salt for the specified method. If not specified, the strongest available method will be used. """ def crypt(word: str, salt: str | _Method | None = None) -> str: - """ - Return a string representing the one-way hash of a password, with a salt + """Return a string representing the one-way hash of a password, with a salt prepended. If ``salt`` is not specified or is ``None``, the strongest diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/csv.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/csv.pyi index 48b653bef9..d64bfcd0f3 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/csv.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/csv.pyi @@ -1,4 +1,5 @@ """ + CSV parsing and writing. This module provides classes that assist in the reading and writing @@ -123,8 +124,7 @@ if sys.version_info < (3, 13): _T = TypeVar("_T") class Dialect: - """ - Describe a CSV dialect. + """Describe a CSV dialect. This must be subclassed (see csv.excel). Valid attributes are: delimiter, quotechar, escapechar, doublequote, skipinitialspace, @@ -142,19 +142,13 @@ class Dialect: def __init__(self) -> None: ... class excel(Dialect): - """ - Describe the usual properties of Excel-generated CSV files. - """ + """Describe the usual properties of Excel-generated CSV files.""" class excel_tab(excel): - """ - Describe the usual properties of Excel-generated TAB-delimited files. - """ + """Describe the usual properties of Excel-generated TAB-delimited files.""" class unix_dialect(Dialect): - """ - Describe the usual properties of Unix-generated CSV files. - """ + """Describe the usual properties of Unix-generated CSV files.""" class DictReader(Generic[_T]): fieldnames: Sequence[_T] | None @@ -203,8 +197,7 @@ class DictReader(Generic[_T]): def __next__(self) -> dict[_T | Any, str | Any]: ... if sys.version_info >= (3, 12): def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ @@ -236,22 +229,18 @@ class DictWriter(Generic[_T]): def writerows(self, rowdicts: Iterable[Mapping[_T, Any]]) -> None: ... if sys.version_info >= (3, 12): def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ class Sniffer: - """ - "Sniffs" the format of a CSV file (i.e. delimiter, quotechar) + """ "Sniffs" the format of a CSV file (i.e. delimiter, quotechar) Returns a Dialect object. """ preferred: list[str] def sniff(self, sample: str, delimiters: str | None = None) -> type[Dialect]: - """ - Returns a dialect (or None) corresponding to the sample - """ + """Returns a dialect (or None) corresponding to the sample""" def has_header(self, sample: str) -> bool: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/__init__.pyi index a6de16191a..0ae1f81fbe 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/__init__.pyi @@ -49,8 +49,7 @@ if sys.version_info >= (3, 14): @overload @deprecated("ctypes.POINTER with string") def POINTER(cls: str) -> type[Any]: - """ - Create and return a new ctypes pointer type. + """Create and return a new ctypes pointer type. Pointer types are cached and reused internally, so calling this function repeatedly is cheap. @@ -61,8 +60,7 @@ if sys.version_info >= (3, 14): @overload def POINTER(cls: type[_CT]) -> type[_Pointer[_CT]]: ... def pointer(obj: _CT) -> _Pointer[_CT]: - """ - Create a new pointer instance, pointing to 'obj'. + """Create a new pointer instance, pointing to 'obj'. The returned object is of the type POINTER(type(obj)). Note that if you just want to pass a pointer to an object to a foreign function call, you @@ -94,8 +92,7 @@ else: _NameTypes: TypeAlias = str | None class CDLL: - """ - An instance of this class represents a loaded dll/shared + """An instance of this class represents a loaded dll/shared library, exporting functions using the standard C calling convention (named 'cdecl' on Windows). @@ -127,12 +124,20 @@ class CDLL: def __getitem__(self, name_or_ordinal: str) -> _NamedFuncPointer: ... if sys.platform == "win32": - class OleDLL(CDLL): ... - class WinDLL(CDLL): ... + class OleDLL(CDLL): + """This class represents a dll exporting functions using the + Windows stdcall calling convention, and returning HRESULT. + HRESULT error values are automatically raised as OSError + exceptions. + """ + + class WinDLL(CDLL): + """This class represents a dll exporting functions using the + Windows stdcall calling convention. + """ class PyDLL(CDLL): - """ - This class represents the Python library itself. It allows + """This class represents the Python library itself. It allows accessing Python API functions. The GIL is not released, and Python exceptions are handled correctly. """ @@ -143,8 +148,7 @@ class LibraryLoader(Generic[_DLLT]): def __getitem__(self, name: str) -> _DLLT: ... def LoadLibrary(self, name: str) -> _DLLT: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ @@ -176,8 +180,7 @@ def CFUNCTYPE( use_errno: bool = False, use_last_error: bool = False, ) -> type[_CFunctionType]: - """ - CFUNCTYPE(restype, *argtypes, + """CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False) -> function prototype. restype: the result type @@ -216,8 +219,7 @@ _CastT = TypeVar("_CastT", bound=_CanCastTo) def cast(obj: _CData | _CDataType | _CArgObject | int, typ: type[_CastT]) -> _CastT: ... def create_string_buffer(init: int | bytes, size: int | None = None) -> Array[c_char]: - """ - create_string_buffer(aBytes) -> character array + """create_string_buffer(aBytes) -> character array create_string_buffer(anInteger) -> character array create_string_buffer(aBytes, anInteger) -> character array """ @@ -225,8 +227,7 @@ def create_string_buffer(init: int | bytes, size: int | None = None) -> Array[c_ c_buffer = create_string_buffer def create_unicode_buffer(init: int | str, size: int | None = None) -> Array[c_wchar]: - """ - create_unicode_buffer(aString) -> character array + """create_unicode_buffer(aString) -> character array create_unicode_buffer(anInteger) -> character array create_unicode_buffer(aString, anInteger) -> character array """ @@ -264,8 +265,7 @@ class _MemsetFunctionType(_CFunctionType): memset: _MemsetFunctionType def string_at(ptr: _CVoidConstPLike, size: int = -1) -> bytes: - """ - string_at(ptr[, size]) -> string + """string_at(ptr[, size]) -> string Return the byte string at void *ptr. """ @@ -274,16 +274,14 @@ if sys.platform == "win32": def WinError(code: int | None = None, descr: str | None = None) -> OSError: ... def wstring_at(ptr: _CVoidConstPLike, size: int = -1) -> str: - """ - wstring_at(ptr[, size]) -> string + """wstring_at(ptr[, size]) -> string Return the wide-character string at void *ptr. """ if sys.version_info >= (3, 14): def memoryview_at(ptr: _CVoidConstPLike, size: int, readonly: bool = False) -> memoryview: - """ - memoryview_at(ptr, size[, readonly]) -> memoryview + """memoryview_at(ptr, size[, readonly]) -> memoryview Return a memoryview representing the memory at void *ptr. """ @@ -292,8 +290,7 @@ class py_object(_CanCastTo, _SimpleCData[_T]): _type_: ClassVar[Literal["O"]] if sys.version_info >= (3, 14): def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/_endian.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/_endian.pyi index 4b5c55aadd..b6a5814991 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/_endian.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/_endian.pyi @@ -4,23 +4,15 @@ from ctypes import Structure, Union # At runtime, the native endianness is an alias for Structure, # while the other is a subclass with a metaclass added in. class BigEndianStructure(Structure): - """ - Structure with big endian byte order - """ + """Structure with big endian byte order""" class LittleEndianStructure(Structure): - """ - Structure base class - """ + """Structure base class""" # Same thing for these: one is an alias of Union at runtime if sys.version_info >= (3, 11): class BigEndianUnion(Union): - """ - Union with big endian byte order - """ + """Union with big endian byte order""" class LittleEndianUnion(Union): - """ - Union base class - """ + """Union base class""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/macholib/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/macholib/__init__.pyi index 106c61e635..2115e69b15 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/macholib/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/macholib/__init__.pyi @@ -1,4 +1,5 @@ """ + Enough Mach-O to make your head spin. See the relevant header files in /usr/include/mach-o diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/macholib/dyld.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/macholib/dyld.pyi index 37be9bd241..35cfa15fc1 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/macholib/dyld.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/macholib/dyld.pyi @@ -1,4 +1,5 @@ """ + dyld emulation """ @@ -9,13 +10,10 @@ from ctypes.macholib.framework import framework_info as framework_info __all__ = ["dyld_find", "framework_find", "framework_info", "dylib_info"] def dyld_find(name: str, executable_path: str | None = None, env: Mapping[str, str] | None = None) -> str: - """ - Find a library or framework using dyld semantics - """ + """Find a library or framework using dyld semantics""" def framework_find(fn: str, executable_path: str | None = None, env: Mapping[str, str] | None = None) -> str: - """ - Find a framework using dyld semantics in a very loose manner. + """Find a framework using dyld semantics in a very loose manner. Will take input such as: Python diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/macholib/dylib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/macholib/dylib.pyi index 58ece6cc99..1817727536 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/macholib/dylib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/macholib/dylib.pyi @@ -1,4 +1,5 @@ """ + Generic dylib path manipulation """ @@ -16,8 +17,7 @@ class _DylibInfo(TypedDict): suffix: str | None def dylib_info(filename: str) -> _DylibInfo | None: - """ - A dylib name can take one of the following four forms: + """A dylib name can take one of the following four forms: Location/Name.SomeVersion_Suffix.dylib Location/Name.SomeVersion.dylib Location/Name_Suffix.dylib diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/macholib/framework.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/macholib/framework.pyi index f12f2b3fd1..917103a4bf 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/macholib/framework.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/macholib/framework.pyi @@ -1,4 +1,5 @@ """ + Generic framework path manipulation """ @@ -16,8 +17,7 @@ class _FrameworkInfo(TypedDict): suffix: str | None def framework_info(filename: str) -> _FrameworkInfo | None: - """ - A framework name can take one of the following four forms: + """A framework name can take one of the following four forms: Location/Name.framework/Versions/SomeVersion/Name_Suffix Location/Name.framework/Versions/SomeVersion/Name Location/Name.framework/Name_Suffix diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/util.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/util.pyi index 34ac7193bd..dc1a251365 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/util.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/ctypes/util.pyi @@ -3,12 +3,11 @@ import sys def find_library(name: str) -> str | None: ... if sys.platform == "win32": - def find_msvcrt() -> str | None: ... + def find_msvcrt() -> str | None: + """Return the name of the VC runtime dll""" if sys.version_info >= (3, 14): def dllist() -> list[str]: - """ - Return a list of loaded shared libraries in the current process. - """ + """Return a list of loaded shared libraries in the current process.""" def test() -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/curses/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/curses/__init__.pyi index c864e04ab5..81fe812aef 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/curses/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/curses/__init__.pyi @@ -34,8 +34,7 @@ COLORS: int COLOR_PAIRS: int def wrapper(func: Callable[Concatenate[window, _P], _T], /, *arg: _P.args, **kwds: _P.kwargs) -> _T: - """ - Wrapper function that initializes curses and calls another function, + """Wrapper function that initializes curses and calls another function, restoring normal keyboard/screen behavior on error. The callable object 'func' is then passed the main window 'stdscr' as its first argument, followed by any other arguments passed to diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/curses/textpad.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/curses/textpad.pyi index e25aadcd32..db2d0e14e4 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/curses/textpad.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/curses/textpad.pyi @@ -6,14 +6,12 @@ from _curses import window from collections.abc import Callable def rectangle(win: window, uly: int, ulx: int, lry: int, lrx: int) -> None: - """ - Draw a rectangle with corners at the provided upper-left + """Draw a rectangle with corners at the provided upper-left and lower-right coordinates. """ class Textbox: - """ - Editing widget using the interior of a window object. + """Editing widget using the interior of a window object. Supports the following Emacs-like key bindings: Ctrl-A Go to left edge of window. @@ -40,16 +38,10 @@ class Textbox: stripspaces: bool def __init__(self, win: window, insert_mode: bool = False) -> None: ... def edit(self, validate: Callable[[int], int] | None = None) -> str: - """ - Edit in the widget window and collect the results. - """ + """Edit in the widget window and collect the results.""" def do_command(self, ch: str | int) -> None: - """ - Process a single editing command. - """ + """Process a single editing command.""" def gather(self) -> str: - """ - Collect and return the contents of the window. - """ + """Collect and return the contents of the window.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/dataclasses.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/dataclasses.pyi index fa2cf771e4..6a749a73a8 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/dataclasses.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/dataclasses.pyi @@ -65,8 +65,7 @@ if sys.version_info >= (3, 10): @overload def asdict(obj: DataclassInstance) -> dict[str, Any]: - """ - Return the fields of a dataclass instance as a new dictionary mapping + """Return the fields of a dataclass instance as a new dictionary mapping field names to field values. Example usage:: @@ -89,8 +88,7 @@ def asdict(obj: DataclassInstance) -> dict[str, Any]: def asdict(obj: DataclassInstance, *, dict_factory: Callable[[list[tuple[str, Any]]], _T]) -> _T: ... @overload def astuple(obj: DataclassInstance) -> tuple[Any, ...]: - """ - Return the fields of a dataclass instance as a new tuple of field values. + """Return the fields of a dataclass instance as a new tuple of field values. Example usage:: @@ -128,8 +126,7 @@ if sys.version_info >= (3, 11): slots: bool = False, weakref_slot: bool = False, ) -> type[_T]: - """ - Add dunder methods based on the fields defined in the class. + """Add dunder methods based on the fields defined in the class. Examines PEP 526 __annotations__ to determine fields. @@ -176,8 +173,7 @@ elif sys.version_info >= (3, 10): kw_only: bool = False, slots: bool = False, ) -> type[_T]: - """ - Returns the same class as was passed in, with dunder methods + """Returns the same class as was passed in, with dunder methods added based on the fields defined in the class. Examines PEP 526 __annotations__ to determine fields. @@ -221,8 +217,7 @@ else: unsafe_hash: bool = False, frozen: bool = False, ) -> type[_T]: - """ - Returns the same class as was passed in, with dunder methods + """Returns the same class as was passed in, with dunder methods added based on the fields defined in the class. Examines PEP 526 __annotations__ to determine fields. @@ -307,8 +302,7 @@ class Field(Generic[_T]): def __set_name__(self, owner: Type[Any], name: str) -> None: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ @@ -329,8 +323,7 @@ if sys.version_info >= (3, 14): kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ..., doc: str | None = None, ) -> _T: - """ - Return an object to identify dataclass fields. + """Return an object to identify dataclass fields. default is the default value of the field. default_factory is a 0-argument function called to initialize a field's value. If init @@ -386,8 +379,7 @@ elif sys.version_info >= (3, 10): metadata: Mapping[Any, Any] | None = None, kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ..., ) -> _T: - """ - Return an object to identify dataclass fields. + """Return an object to identify dataclass fields. default is the default value of the field. default_factory is a 0-argument function called to initialize a field's value. If init @@ -440,8 +432,7 @@ else: compare: bool = True, metadata: Mapping[Any, Any] | None = None, ) -> _T: - """ - Return an object to identify dataclass fields. + """Return an object to identify dataclass fields. default is the default value of the field. default_factory is a 0-argument function called to initialize a field's value. If init @@ -479,8 +470,7 @@ else: ) -> Any: ... def fields(class_or_instance: DataclassInstance | type[DataclassInstance]) -> tuple[Field[Any], ...]: - """ - Return a tuple describing the fields of this dataclass. + """Return a tuple describing the fields of this dataclass. Accepts a dataclass or an instance of one. Tuple elements are of type Field. @@ -489,8 +479,7 @@ def fields(class_or_instance: DataclassInstance | type[DataclassInstance]) -> tu # HACK: `obj: Never` typing matches if object argument is using `Any` type. @overload def is_dataclass(obj: Never) -> TypeIs[DataclassInstance | type[DataclassInstance]]: # type: ignore[narrowed-type-not-subtype] # pyright: ignore[reportGeneralTypeIssues] - """ - Returns True if obj is a dataclass or an instance of a + """Returns True if obj is a dataclass or an instance of a dataclass. """ @@ -529,8 +518,7 @@ if sys.version_info >= (3, 14): module: str | None = None, decorator: _DataclassFactory = ..., ) -> type: - """ - Return a new dynamically created dataclass. + """Return a new dynamically created dataclass. The dataclass name will be 'cls_name'. 'fields' is an iterable of either (name), (name, type) or (name, type, Field) objects. If type is @@ -575,8 +563,7 @@ elif sys.version_info >= (3, 12): weakref_slot: bool = False, module: str | None = None, ) -> type: - """ - Return a new dynamically created dataclass. + """Return a new dynamically created dataclass. The dataclass name will be 'cls_name'. 'fields' is an iterable of either (name), (name, type) or (name, type, Field) objects. If type is @@ -620,8 +607,7 @@ elif sys.version_info >= (3, 11): slots: bool = False, weakref_slot: bool = False, ) -> type: - """ - Return a new dynamically created dataclass. + """Return a new dynamically created dataclass. The dataclass name will be 'cls_name'. 'fields' is an iterable of either (name), (name, type) or (name, type, Field) objects. If type is @@ -661,8 +647,7 @@ elif sys.version_info >= (3, 10): kw_only: bool = False, slots: bool = False, ) -> type: - """ - Return a new dynamically created dataclass. + """Return a new dynamically created dataclass. The dataclass name will be 'cls_name'. 'fields' is an iterable of either (name), (name, type) or (name, type, Field) objects. If type is @@ -699,8 +684,7 @@ else: unsafe_hash: bool = False, frozen: bool = False, ) -> type: - """ - Return a new dynamically created dataclass. + """Return a new dynamically created dataclass. The dataclass name will be 'cls_name'. 'fields' is an iterable of either (name), (name, type) or (name, type, Field) objects. If type is @@ -724,8 +708,7 @@ else: """ def replace(obj: _DataclassT, /, **changes: Any) -> _DataclassT: - """ - Return a new object replacing specified fields with new values. + """Return a new object replacing specified fields with new values. This is especially useful for frozen classes. Example usage:: diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/datetime.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/datetime.pyi index 5f42414b56..bf42260e88 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/datetime.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/datetime.pyi @@ -20,60 +20,42 @@ MINYEAR: Final = 1 MAXYEAR: Final = 9999 class tzinfo: - """ - Abstract base class for time zone info objects. - """ + """Abstract base class for time zone info objects.""" @abstractmethod def tzname(self, dt: datetime | None, /) -> str | None: - """ - datetime -> string name of time zone. - """ + """datetime -> string name of time zone.""" @abstractmethod def utcoffset(self, dt: datetime | None, /) -> timedelta | None: - """ - datetime -> timedelta showing offset from UTC, negative values indicating West of UTC - """ + """datetime -> timedelta showing offset from UTC, negative values indicating West of UTC""" @abstractmethod def dst(self, dt: datetime | None, /) -> timedelta | None: - """ - datetime -> DST offset as timedelta positive east of UTC. - """ + """datetime -> DST offset as timedelta positive east of UTC.""" def fromutc(self, dt: datetime, /) -> datetime: - """ - datetime in UTC -> datetime in local time. - """ + """datetime in UTC -> datetime in local time.""" # Alias required to avoid name conflicts with date(time).tzinfo. _TzInfo: TypeAlias = tzinfo @final class timezone(tzinfo): - """ - Fixed offset from UTC implementation of tzinfo. - """ + """Fixed offset from UTC implementation of tzinfo.""" utc: ClassVar[timezone] min: ClassVar[timezone] max: ClassVar[timezone] def __new__(cls, offset: timedelta, name: str = ...) -> Self: ... def tzname(self, dt: datetime | None, /) -> str: - """ - If name is specified when timezone is created, returns the name. Otherwise returns offset as 'UTC(+|-)HH:MM'. - """ + """If name is specified when timezone is created, returns the name. Otherwise returns offset as 'UTC(+|-)HH:MM'.""" def utcoffset(self, dt: datetime | None, /) -> timedelta: - """ - Return fixed offset. - """ + """Return fixed offset.""" def dst(self, dt: datetime | None, /) -> None: - """ - Return None. - """ + """Return None.""" def __hash__(self) -> int: ... def __eq__(self, value: object, /) -> bool: ... @@ -94,9 +76,7 @@ class _IsoCalendarDate(tuple[int, int, int]): def weekday(self) -> int: ... class date: - """ - date(year, month, day) --> date object - """ + """date(year, month, day) --> date object""" min: ClassVar[date] max: ClassVar[date] @@ -104,8 +84,7 @@ class date: def __new__(cls, year: SupportsIndex, month: SupportsIndex, day: SupportsIndex) -> Self: ... @classmethod def fromtimestamp(cls, timestamp: float, /) -> Self: - """ - Create a date from a POSIX timestamp. + """Create a date from a POSIX timestamp. The timestamp is a number, e.g. created via time.time(), that is interpreted as local time. @@ -113,26 +92,19 @@ class date: @classmethod def today(cls) -> Self: - """ - Current date or datetime: same as self.__class__.fromtimestamp(time.time()). - """ + """Current date or datetime: same as self.__class__.fromtimestamp(time.time()).""" @classmethod def fromordinal(cls, n: int, /) -> Self: - """ - int -> date corresponding to a proleptic Gregorian ordinal. - """ + """int -> date corresponding to a proleptic Gregorian ordinal.""" @classmethod def fromisoformat(cls, date_string: str, /) -> Self: - """ - str -> Construct a date from a string in ISO 8601 format. - """ + """str -> Construct a date from a string in ISO 8601 format.""" @classmethod def fromisocalendar(cls, year: int, week: int, day: int) -> Self: - """ - int, int, int -> Construct a date from the ISO year, week number and weekday. + """int, int, int -> Construct a date from the ISO year, week number and weekday. This is the inverse of the date.isocalendar() function """ @@ -144,58 +116,38 @@ class date: @property def day(self) -> int: ... def ctime(self) -> str: - """ - Return ctime() style string. - """ + """Return ctime() style string.""" if sys.version_info >= (3, 14): @classmethod def strptime(cls, date_string: str, format: str, /) -> Self: - """ - string, format -> new date parsed from a string (like time.strptime()). - """ + """string, format -> new date parsed from a string (like time.strptime()).""" # On <3.12, the name of the parameter in the pure-Python implementation # didn't match the name in the C implementation, # meaning it is only *safe* to pass it as a keyword argument on 3.12+ if sys.version_info >= (3, 12): def strftime(self, format: str) -> str: - """ - format -> strftime() style string. - """ + """format -> strftime() style string.""" else: def strftime(self, format: str, /) -> str: - """ - format -> strftime() style string. - """ + """format -> strftime() style string.""" def __format__(self, fmt: str, /) -> str: - """ - Formats self with strftime. - """ + """Formats self with strftime.""" def isoformat(self) -> str: - """ - Return string in ISO 8601 format, YYYY-MM-DD. - """ + """Return string in ISO 8601 format, YYYY-MM-DD.""" def timetuple(self) -> struct_time: - """ - Return time tuple, compatible with time.localtime(). - """ + """Return time tuple, compatible with time.localtime().""" def toordinal(self) -> int: - """ - Return proleptic Gregorian ordinal. January 1 of year 1 is day 1. - """ + """Return proleptic Gregorian ordinal. January 1 of year 1 is day 1.""" if sys.version_info >= (3, 13): def __replace__(self, /, *, year: SupportsIndex = ..., month: SupportsIndex = ..., day: SupportsIndex = ...) -> Self: - """ - The same as replace(). - """ + """The same as replace().""" def replace(self, year: SupportsIndex = ..., month: SupportsIndex = ..., day: SupportsIndex = ...) -> Self: - """ - Return date with new specified fields. - """ + """Return date with new specified fields.""" def __le__(self, value: date, /) -> bool: ... def __lt__(self, value: date, /) -> bool: ... @@ -203,20 +155,14 @@ class date: def __gt__(self, value: date, /) -> bool: ... def __eq__(self, value: object, /) -> bool: ... def __add__(self, value: timedelta, /) -> Self: - """ - Return self+value. - """ + """Return self+value.""" def __radd__(self, value: timedelta, /) -> Self: - """ - Return value+self. - """ + """Return value+self.""" @overload def __sub__(self, value: datetime, /) -> NoReturn: - """ - Return self-value. - """ + """Return self-value.""" @overload def __sub__(self, value: Self, /) -> timedelta: ... @@ -224,25 +170,20 @@ class date: def __sub__(self, value: timedelta, /) -> Self: ... def __hash__(self) -> int: ... def weekday(self) -> int: - """ - Return the day of the week represented by the date. + """Return the day of the week represented by the date. Monday == 0 ... Sunday == 6 """ def isoweekday(self) -> int: - """ - Return the day of the week represented by the date. + """Return the day of the week represented by the date. Monday == 1 ... Sunday == 7 """ def isocalendar(self) -> _IsoCalendarDate: - """ - Return a named tuple containing ISO year, week number, and weekday. - """ + """Return a named tuple containing ISO year, week number, and weekday.""" class time: - """ - time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object + """time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object All arguments are optional. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints. @@ -280,8 +221,7 @@ class time: def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... def isoformat(self, timespec: str = ...) -> str: - """ - Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM]. + """Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM]. The optional argument timespec specifies the number of additional terms of the time to include. Valid options are 'auto', 'hours', 'minutes', @@ -290,48 +230,32 @@ class time: @classmethod def fromisoformat(cls, time_string: str, /) -> Self: - """ - string -> time from a string in ISO 8601 format - """ + """string -> time from a string in ISO 8601 format""" if sys.version_info >= (3, 14): @classmethod def strptime(cls, date_string: str, format: str, /) -> Self: - """ - string, format -> new time parsed from a string (like time.strptime()). - """ + """string, format -> new time parsed from a string (like time.strptime()).""" # On <3.12, the name of the parameter in the pure-Python implementation # didn't match the name in the C implementation, # meaning it is only *safe* to pass it as a keyword argument on 3.12+ if sys.version_info >= (3, 12): def strftime(self, format: str) -> str: - """ - format -> strftime() style string. - """ + """format -> strftime() style string.""" else: def strftime(self, format: str, /) -> str: - """ - format -> strftime() style string. - """ + """format -> strftime() style string.""" def __format__(self, fmt: str, /) -> str: - """ - Formats self with strftime. - """ + """Formats self with strftime.""" def utcoffset(self) -> timedelta | None: - """ - Return self.tzinfo.utcoffset(self). - """ + """Return self.tzinfo.utcoffset(self).""" def tzname(self) -> str | None: - """ - Return self.tzinfo.tzname(self). - """ + """Return self.tzinfo.tzname(self).""" def dst(self) -> timedelta | None: - """ - Return self.tzinfo.dst(self). - """ + """Return self.tzinfo.dst(self).""" if sys.version_info >= (3, 13): def __replace__( self, @@ -344,9 +268,7 @@ class time: tzinfo: _TzInfo | None = ..., fold: int = ..., ) -> Self: - """ - The same as replace(). - """ + """The same as replace().""" def replace( self, @@ -358,16 +280,13 @@ class time: *, fold: int = ..., ) -> Self: - """ - Return time with new specified fields. - """ + """Return time with new specified fields.""" _Date: TypeAlias = date _Time: TypeAlias = time class timedelta: - """ - Difference between two datetime values. + """Difference between two datetime values. timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) @@ -390,97 +309,63 @@ class timedelta: ) -> Self: ... @property def days(self) -> int: - """ - Number of days. - """ + """Number of days.""" @property def seconds(self) -> int: - """ - Number of seconds (>= 0 and less than 1 day). - """ + """Number of seconds (>= 0 and less than 1 day).""" @property def microseconds(self) -> int: - """ - Number of microseconds (>= 0 and less than 1 second). - """ + """Number of microseconds (>= 0 and less than 1 second).""" def total_seconds(self) -> float: - """ - Total seconds in the duration. - """ + """Total seconds in the duration.""" def __add__(self, value: timedelta, /) -> timedelta: - """ - Return self+value. - """ + """Return self+value.""" def __radd__(self, value: timedelta, /) -> timedelta: - """ - Return value+self. - """ + """Return value+self.""" def __sub__(self, value: timedelta, /) -> timedelta: - """ - Return self-value. - """ + """Return self-value.""" def __rsub__(self, value: timedelta, /) -> timedelta: - """ - Return value-self. - """ + """Return value-self.""" def __neg__(self) -> timedelta: - """ - -self - """ + """-self""" def __pos__(self) -> timedelta: - """ - +self - """ + """+self""" def __abs__(self) -> timedelta: - """ - abs(self) - """ + """abs(self)""" def __mul__(self, value: float, /) -> timedelta: - """ - Return self*value. - """ + """Return self*value.""" def __rmul__(self, value: float, /) -> timedelta: - """ - Return value*self. - """ + """Return value*self.""" @overload def __floordiv__(self, value: timedelta, /) -> int: - """ - Return self//value. - """ + """Return self//value.""" @overload def __floordiv__(self, value: int, /) -> timedelta: ... @overload def __truediv__(self, value: timedelta, /) -> float: - """ - Return self/value. - """ + """Return self/value.""" @overload def __truediv__(self, value: float, /) -> timedelta: ... def __mod__(self, value: timedelta, /) -> timedelta: - """ - Return self%value. - """ + """Return self%value.""" def __divmod__(self, value: timedelta, /) -> tuple[int, timedelta]: - """ - Return divmod(self, value). - """ + """Return divmod(self, value).""" def __le__(self, value: timedelta, /) -> bool: ... def __lt__(self, value: timedelta, /) -> bool: ... @@ -488,15 +373,12 @@ class timedelta: def __gt__(self, value: timedelta, /) -> bool: ... def __eq__(self, value: object, /) -> bool: ... def __bool__(self) -> bool: - """ - True if self else False - """ + """True if self else False""" def __hash__(self) -> int: ... class datetime(date): - """ - datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]) + """datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]) The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints. @@ -535,27 +417,20 @@ class datetime(date): if sys.version_info >= (3, 12): @classmethod def fromtimestamp(cls, timestamp: float, tz: _TzInfo | None = ...) -> Self: - """ - timestamp[, tz] -> tz's local time from POSIX timestamp. - """ + """timestamp[, tz] -> tz's local time from POSIX timestamp.""" else: @classmethod def fromtimestamp(cls, timestamp: float, /, tz: _TzInfo | None = ...) -> Self: - """ - timestamp[, tz] -> tz's local time from POSIX timestamp. - """ + """timestamp[, tz] -> tz's local time from POSIX timestamp.""" @classmethod @deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .fromtimestamp(datetime.timezone.utc)") def utcfromtimestamp(cls, t: float, /) -> Self: - """ - Construct a naive UTC datetime from a POSIX timestamp. - """ + """Construct a naive UTC datetime from a POSIX timestamp.""" @classmethod def now(cls, tz: _TzInfo | None = None) -> Self: - """ - Returns new datetime object representing current time local to tz. + """Returns new datetime object representing current time local to tz. tz Timezone object. @@ -566,40 +441,26 @@ class datetime(date): @classmethod @deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .now(datetime.timezone.utc)") def utcnow(cls) -> Self: - """ - Return a new datetime representing UTC day and time. - """ + """Return a new datetime representing UTC day and time.""" @classmethod def combine(cls, date: _Date, time: _Time, tzinfo: _TzInfo | None = ...) -> Self: - """ - date, time -> datetime with same date and time fields - """ + """date, time -> datetime with same date and time fields""" def timestamp(self) -> float: - """ - Return POSIX timestamp as float. - """ + """Return POSIX timestamp as float.""" def utctimetuple(self) -> struct_time: - """ - Return UTC time tuple, compatible with time.localtime(). - """ + """Return UTC time tuple, compatible with time.localtime().""" def date(self) -> _Date: - """ - Return date object with same year, month and day. - """ + """Return date object with same year, month and day.""" def time(self) -> _Time: - """ - Return time object with same time but with tzinfo=None. - """ + """Return time object with same time but with tzinfo=None.""" def timetz(self) -> _Time: - """ - Return time object with same time and tzinfo. - """ + """Return time object with same time and tzinfo.""" if sys.version_info >= (3, 13): def __replace__( self, @@ -615,9 +476,7 @@ class datetime(date): tzinfo: _TzInfo | None = ..., fold: int = ..., ) -> Self: - """ - The same as replace(). - """ + """The same as replace().""" def replace( self, @@ -632,18 +491,13 @@ class datetime(date): *, fold: int = ..., ) -> Self: - """ - Return datetime with new specified fields. - """ + """Return datetime with new specified fields.""" def astimezone(self, tz: _TzInfo | None = ...) -> Self: - """ - tz -> convert to local time in new timezone tz - """ + """tz -> convert to local time in new timezone tz""" def isoformat(self, sep: str = ..., timespec: str = ...) -> str: - """ - [sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM]. + """[sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM]. sep is used to separate the year from the time, and defaults to 'T'. The optional argument timespec specifies the number of additional terms of the time to include. Valid options are 'auto', 'hours', 'minutes', @@ -652,24 +506,16 @@ class datetime(date): @classmethod def strptime(cls, date_string: str, format: str, /) -> Self: - """ - string, format -> new datetime parsed from a string (like time.strptime()). - """ + """string, format -> new datetime parsed from a string (like time.strptime()).""" def utcoffset(self) -> timedelta | None: - """ - Return self.tzinfo.utcoffset(self). - """ + """Return self.tzinfo.utcoffset(self).""" def tzname(self) -> str | None: - """ - Return self.tzinfo.tzname(self). - """ + """Return self.tzinfo.tzname(self).""" def dst(self) -> timedelta | None: - """ - Return self.tzinfo.dst(self). - """ + """Return self.tzinfo.dst(self).""" def __le__(self, value: datetime, /) -> bool: ... # type: ignore[override] def __lt__(self, value: datetime, /) -> bool: ... # type: ignore[override] @@ -679,9 +525,7 @@ class datetime(date): def __hash__(self) -> int: ... @overload # type: ignore[override] def __sub__(self, value: Self, /) -> timedelta: - """ - Return self-value. - """ + """Return self-value.""" @overload def __sub__(self, value: timedelta, /) -> Self: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/dbm/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/dbm/__init__.pyi index 94335a3e64..e71fc13286 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/dbm/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/dbm/__init__.pyi @@ -127,8 +127,7 @@ error: tuple[type[_error], type[OSError]] if sys.version_info >= (3, 11): def whichdb(filename: StrOrBytesPath) -> str | None: - """ - Guess which db package to use to open a db file. + """Guess which db package to use to open a db file. Return values: @@ -141,8 +140,7 @@ if sys.version_info >= (3, 11): """ def open(file: StrOrBytesPath, flag: _TFlags = "r", mode: int = 0o666) -> _Database: - """ - Open or create database at path given by *file*. + """Open or create database at path given by *file*. Optional argument *flag* can be 'r' (default) for read-only access, 'w' for read-write access of an existing database, 'c' for read-write access @@ -155,8 +153,7 @@ if sys.version_info >= (3, 11): else: def whichdb(filename: str) -> str | None: - """ - Guess which db package to use to open a db file. + """Guess which db package to use to open a db file. Return values: @@ -169,8 +166,7 @@ else: """ def open(file: str, flag: _TFlags = "r", mode: int = 0o666) -> _Database: - """ - Open or create database at path given by *file*. + """Open or create database at path given by *file*. Optional argument *flag* can be 'r' (default) for read-only access, 'w' for read-write access of an existing database, 'c' for read-write access diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/dbm/dumb.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/dbm/dumb.pyi index fae26d5d38..c7b349520f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/dbm/dumb.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/dbm/dumb.pyi @@ -55,8 +55,7 @@ class _Database(MutableMapping[_KeyType, bytes]): if sys.version_info >= (3, 11): def open(file: StrOrBytesPath, flag: str = "c", mode: int = 0o666) -> _Database: - """ - Open the database file, filename, and return corresponding object. + """Open the database file, filename, and return corresponding object. The flag argument, used to control how the database is opened in the other DBM implementations, supports only the semantics of 'c' and 'n' @@ -71,8 +70,7 @@ if sys.version_info >= (3, 11): else: def open(file: str, flag: str = "c", mode: int = 0o666) -> _Database: - """ - Open the database file, filename, and return corresponding object. + """Open the database file, filename, and return corresponding object. The flag argument, used to control how the database is opened in the other DBM implementations, supports only the semantics of 'c' and 'n' diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/dbm/sqlite3.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/dbm/sqlite3.pyi index e564340109..b4b53b0212 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/dbm/sqlite3.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/dbm/sqlite3.pyi @@ -27,8 +27,7 @@ class _Database(MutableMapping[bytes, bytes]): def __exit__(self, *args: Unused) -> None: ... def open(filename: StrOrBytesPath, /, flag: Literal["r", "w,", "c", "n"] = "r", mode: int = 0o666) -> _Database: - """ - Open a dbm.sqlite3 database and return the dbm object. + """Open a dbm.sqlite3 database and return the dbm object. The 'filename' parameter is the name of the database file. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/decimal.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/decimal.pyi index 175d9ca5bf..f693c43cd2 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/decimal.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/decimal.pyi @@ -150,9 +150,7 @@ class _ContextManager: def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... class DecimalTuple(NamedTuple): - """ - DecimalTuple(sign, digits, exponent) - """ + """DecimalTuple(sign, digits, exponent)""" sign: int digits: tuple[int, ...] @@ -174,8 +172,7 @@ class Underflow(Inexact, Rounded, Subnormal): ... class FloatOperation(DecimalException, TypeError): ... class Decimal: - """ - Construct a new Decimal object. 'value' can be an integer, string, tuple, + """Construct a new Decimal object. 'value' can be an integer, string, tuple, or another Decimal object. If no value is given, return Decimal('0'). The context does not affect the conversion and is only passed to determine if the InvalidOperation trap is active. @@ -185,8 +182,7 @@ class Decimal: if sys.version_info >= (3, 14): @classmethod def from_number(cls, number: Decimal | float, /) -> Self: - """ - Class method that converts a real number to a decimal number, exactly. + """Class method that converts a real number to a decimal number, exactly. >>> Decimal.from_number(314) # int Decimal('314') @@ -198,8 +194,7 @@ class Decimal: @classmethod def from_float(cls, f: float, /) -> Self: - """ - Class method that converts a float to a decimal number, exactly. + """Class method that converts a float to a decimal number, exactly. Since 0.1 is not exactly representable in binary floating point, Decimal.from_float(0.1) is not the same as Decimal('0.1'). @@ -214,13 +209,10 @@ class Decimal: """ def __bool__(self) -> bool: - """ - True if self else False - """ + """True if self else False""" def compare(self, other: _Decimal, context: Context | None = None) -> Decimal: - """ - Compare self to other. Return a decimal value: + """Compare self to other. Return a decimal value: a or b is a NaN ==> Decimal('NaN') a < b ==> Decimal('-1') @@ -230,13 +222,10 @@ class Decimal: def __hash__(self) -> int: ... def as_tuple(self) -> DecimalTuple: - """ - Return a tuple representation of the number. - """ + """Return a tuple representation of the number.""" def as_integer_ratio(self) -> tuple[int, int]: - """ - Decimal.as_integer_ratio() -> (int, int) + """Decimal.as_integer_ratio() -> (int, int) Return a pair of integers, whose ratio is exactly equal to the original Decimal and with a positive denominator. The ratio is in lowest terms. @@ -244,8 +233,7 @@ class Decimal: """ def to_eng_string(self, context: Context | None = None) -> str: - """ - Convert to an engineering-type string. Engineering notation has an exponent + """Convert to an engineering-type string. Engineering notation has an exponent which is a multiple of 3, so there are up to 3 digits left of the decimal place. For example, Decimal('123E+1') is converted to Decimal('1.23E+3'). @@ -254,103 +242,66 @@ class Decimal: """ def __abs__(self) -> Decimal: - """ - abs(self) - """ + """abs(self)""" def __add__(self, value: _Decimal, /) -> Decimal: - """ - Return self+value. - """ + """Return self+value.""" def __divmod__(self, value: _Decimal, /) -> tuple[Decimal, Decimal]: - """ - Return divmod(self, value). - """ + """Return divmod(self, value).""" def __eq__(self, value: object, /) -> bool: ... def __floordiv__(self, value: _Decimal, /) -> Decimal: - """ - Return self//value. - """ + """Return self//value.""" def __ge__(self, value: _ComparableNum, /) -> bool: ... def __gt__(self, value: _ComparableNum, /) -> bool: ... def __le__(self, value: _ComparableNum, /) -> bool: ... def __lt__(self, value: _ComparableNum, /) -> bool: ... def __mod__(self, value: _Decimal, /) -> Decimal: - """ - Return self%value. - """ + """Return self%value.""" def __mul__(self, value: _Decimal, /) -> Decimal: - """ - Return self*value. - """ + """Return self*value.""" def __neg__(self) -> Decimal: - """ - -self - """ + """-self""" def __pos__(self) -> Decimal: - """ - +self - """ + """+self""" def __pow__(self, value: _Decimal, mod: _Decimal | None = None, /) -> Decimal: - """ - Return pow(self, value, mod). - """ + """Return pow(self, value, mod).""" def __radd__(self, value: _Decimal, /) -> Decimal: - """ - Return value+self. - """ + """Return value+self.""" def __rdivmod__(self, value: _Decimal, /) -> tuple[Decimal, Decimal]: - """ - Return divmod(value, self). - """ + """Return divmod(value, self).""" def __rfloordiv__(self, value: _Decimal, /) -> Decimal: - """ - Return value//self. - """ + """Return value//self.""" def __rmod__(self, value: _Decimal, /) -> Decimal: - """ - Return value%self. - """ + """Return value%self.""" def __rmul__(self, value: _Decimal, /) -> Decimal: - """ - Return value*self. - """ + """Return value*self.""" def __rsub__(self, value: _Decimal, /) -> Decimal: - """ - Return value-self. - """ + """Return value-self.""" def __rtruediv__(self, value: _Decimal, /) -> Decimal: - """ - Return value/self. - """ + """Return value/self.""" def __sub__(self, value: _Decimal, /) -> Decimal: - """ - Return self-value. - """ + """Return self-value.""" def __truediv__(self, value: _Decimal, /) -> Decimal: - """ - Return self/value. - """ + """Return self/value.""" def remainder_near(self, other: _Decimal, context: Context | None = None) -> Decimal: - """ - Return the remainder from dividing self by other. This differs from + """Return the remainder from dividing self by other. This differs from self % other in that the sign of the remainder is chosen so as to minimize its absolute value. More precisely, the return value is self - n * other where n is the integer nearest to the exact value of self / other, and @@ -360,14 +311,10 @@ class Decimal: """ def __float__(self) -> float: - """ - float(self) - """ + """float(self)""" def __int__(self) -> int: - """ - int(self) - """ + """int(self)""" def __trunc__(self) -> int: ... @property @@ -375,9 +322,7 @@ class Decimal: @property def imag(self) -> Decimal: ... def conjugate(self) -> Decimal: - """ - Return self. - """ + """Return self.""" def __complex__(self) -> complex: ... @overload @@ -387,8 +332,7 @@ class Decimal: def __floor__(self) -> int: ... def __ceil__(self) -> int: ... def fma(self, other: _Decimal, third: _Decimal, context: Context | None = None) -> Decimal: - """ - Fused multiply-add. Return self*other+third with no rounding of the + """Fused multiply-add. Return self*other+third with no rounding of the intermediate product self*other. >>> Decimal(2).fma(3, 5) @@ -396,13 +340,10 @@ class Decimal: """ def __rpow__(self, value: _Decimal, mod: Context | None = None, /) -> Decimal: - """ - Return pow(value, self, mod). - """ + """Return pow(value, self, mod).""" def normalize(self, context: Context | None = None) -> Decimal: - """ - Normalize the number by stripping the rightmost trailing zeros and + """Normalize the number by stripping the rightmost trailing zeros and converting any result equal to Decimal('0') to Decimal('0e0'). Used for producing canonical values for members of an equivalence class. For example, Decimal('32.100') and Decimal('0.321000e+2') both normalize @@ -410,8 +351,7 @@ class Decimal: """ def quantize(self, exp: _Decimal, rounding: str | None = None, context: Context | None = None) -> Decimal: - """ - Return a value equal to the first operand after rounding and having the + """Return a value equal to the first operand after rounding and having the exponent of the second operand. >>> Decimal('1.41421356').quantize(Decimal('1.000')) @@ -432,8 +372,7 @@ class Decimal: """ def same_quantum(self, other: _Decimal, context: Context | None = None) -> bool: - """ - Test whether self and other have the same exponent or whether both are NaN. + """Test whether self and other have the same exponent or whether both are NaN. This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise @@ -441,65 +380,53 @@ class Decimal: """ def to_integral_exact(self, rounding: str | None = None, context: Context | None = None) -> Decimal: - """ - Round to the nearest integer, signaling Inexact or Rounded as appropriate if + """Round to the nearest integer, signaling Inexact or Rounded as appropriate if rounding occurs. The rounding mode is determined by the rounding parameter if given, else by the given context. If neither parameter is given, then the rounding mode of the current default context is used. """ def to_integral_value(self, rounding: str | None = None, context: Context | None = None) -> Decimal: - """ - Round to the nearest integer without signaling Inexact or Rounded. The + """Round to the nearest integer without signaling Inexact or Rounded. The rounding mode is determined by the rounding parameter if given, else by the given context. If neither parameter is given, then the rounding mode of the current default context is used. """ def to_integral(self, rounding: str | None = None, context: Context | None = None) -> Decimal: - """ - Identical to the to_integral_value() method. The to_integral() name has been + """Identical to the to_integral_value() method. The to_integral() name has been kept for compatibility with older versions. """ def sqrt(self, context: Context | None = None) -> Decimal: - """ - Return the square root of the argument to full precision. The result is + """Return the square root of the argument to full precision. The result is correctly rounded using the ROUND_HALF_EVEN rounding mode. """ def max(self, other: _Decimal, context: Context | None = None) -> Decimal: - """ - Maximum of self and other. If one operand is a quiet NaN and the other is + """Maximum of self and other. If one operand is a quiet NaN and the other is numeric, the numeric operand is returned. """ def min(self, other: _Decimal, context: Context | None = None) -> Decimal: - """ - Minimum of self and other. If one operand is a quiet NaN and the other is + """Minimum of self and other. If one operand is a quiet NaN and the other is numeric, the numeric operand is returned. """ def adjusted(self) -> int: - """ - Return the adjusted exponent of the number. Defined as exp + digits - 1. - """ + """Return the adjusted exponent of the number. Defined as exp + digits - 1.""" def canonical(self) -> Decimal: - """ - Return the canonical encoding of the argument. Currently, the encoding + """Return the canonical encoding of the argument. Currently, the encoding of a Decimal instance is always canonical, so this operation returns its argument unchanged. """ def compare_signal(self, other: _Decimal, context: Context | None = None) -> Decimal: - """ - Identical to compare, except that all NaNs signal. - """ + """Identical to compare, except that all NaNs signal.""" def compare_total(self, other: _Decimal, context: Context | None = None) -> Decimal: - """ - Compare two operands using their abstract representation rather than + """Compare two operands using their abstract representation rather than their numerical value. Similar to the compare() method, but the result gives a total ordering on Decimal instances. Two Decimal instances with the same numeric value but different representations compare unequal @@ -520,8 +447,7 @@ class Decimal: """ def compare_total_mag(self, other: _Decimal, context: Context | None = None) -> Decimal: - """ - Compare two operands using their abstract representation rather than their + """Compare two operands using their abstract representation rather than their value as in compare_total(), but ignoring the sign of each operand. x.compare_total_mag(y) is equivalent to x.copy_abs().compare_total(y.copy_abs()). @@ -532,20 +458,17 @@ class Decimal: """ def copy_abs(self) -> Decimal: - """ - Return the absolute value of the argument. This operation is unaffected by + """Return the absolute value of the argument. This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. """ def copy_negate(self) -> Decimal: - """ - Return the negation of the argument. This operation is unaffected by context + """Return the negation of the argument. This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. """ def copy_sign(self, other: _Decimal, context: Context | None = None) -> Decimal: - """ - Return a copy of the first operand with the sign set to be the same as the + """Return a copy of the first operand with the sign set to be the same as the sign of the second operand. For example: >>> Decimal('2.3').copy_sign(Decimal('-1.5')) @@ -557,150 +480,120 @@ class Decimal: """ def exp(self, context: Context | None = None) -> Decimal: - """ - Return the value of the (natural) exponential function e**x at the given + """Return the value of the (natural) exponential function e**x at the given number. The function always uses the ROUND_HALF_EVEN mode and the result is correctly rounded. """ def is_canonical(self) -> bool: - """ - Return True if the argument is canonical and False otherwise. Currently, + """Return True if the argument is canonical and False otherwise. Currently, a Decimal instance is always canonical, so this operation always returns True. """ def is_finite(self) -> bool: - """ - Return True if the argument is a finite number, and False if the argument + """Return True if the argument is a finite number, and False if the argument is infinite or a NaN. """ def is_infinite(self) -> bool: - """ - Return True if the argument is either positive or negative infinity and + """Return True if the argument is either positive or negative infinity and False otherwise. """ def is_nan(self) -> bool: - """ - Return True if the argument is a (quiet or signaling) NaN and False + """Return True if the argument is a (quiet or signaling) NaN and False otherwise. """ def is_normal(self, context: Context | None = None) -> bool: - """ - Return True if the argument is a normal finite non-zero number with an + """Return True if the argument is a normal finite non-zero number with an adjusted exponent greater than or equal to Emin. Return False if the argument is zero, subnormal, infinite or a NaN. """ def is_qnan(self) -> bool: - """ - Return True if the argument is a quiet NaN, and False otherwise. - """ + """Return True if the argument is a quiet NaN, and False otherwise.""" def is_signed(self) -> bool: - """ - Return True if the argument has a negative sign and False otherwise. + """Return True if the argument has a negative sign and False otherwise. Note that both zeros and NaNs can carry signs. """ def is_snan(self) -> bool: - """ - Return True if the argument is a signaling NaN and False otherwise. - """ + """Return True if the argument is a signaling NaN and False otherwise.""" def is_subnormal(self, context: Context | None = None) -> bool: - """ - Return True if the argument is subnormal, and False otherwise. A number is + """Return True if the argument is subnormal, and False otherwise. A number is subnormal if it is non-zero, finite, and has an adjusted exponent less than Emin. """ def is_zero(self) -> bool: - """ - Return True if the argument is a (positive or negative) zero and False + """Return True if the argument is a (positive or negative) zero and False otherwise. """ def ln(self, context: Context | None = None) -> Decimal: - """ - Return the natural (base e) logarithm of the operand. The function always + """Return the natural (base e) logarithm of the operand. The function always uses the ROUND_HALF_EVEN mode and the result is correctly rounded. """ def log10(self, context: Context | None = None) -> Decimal: - """ - Return the base ten logarithm of the operand. The function always uses the + """Return the base ten logarithm of the operand. The function always uses the ROUND_HALF_EVEN mode and the result is correctly rounded. """ def logb(self, context: Context | None = None) -> Decimal: - """ - For a non-zero number, return the adjusted exponent of the operand as a + """For a non-zero number, return the adjusted exponent of the operand as a Decimal instance. If the operand is a zero, then Decimal('-Infinity') is returned and the DivisionByZero condition is raised. If the operand is an infinity then Decimal('Infinity') is returned. """ def logical_and(self, other: _Decimal, context: Context | None = None) -> Decimal: - """ - Return the digit-wise 'and' of the two (logical) operands. - """ + """Return the digit-wise 'and' of the two (logical) operands.""" def logical_invert(self, context: Context | None = None) -> Decimal: - """ - Return the digit-wise inversion of the (logical) operand. - """ + """Return the digit-wise inversion of the (logical) operand.""" def logical_or(self, other: _Decimal, context: Context | None = None) -> Decimal: - """ - Return the digit-wise 'or' of the two (logical) operands. - """ + """Return the digit-wise 'or' of the two (logical) operands.""" def logical_xor(self, other: _Decimal, context: Context | None = None) -> Decimal: - """ - Return the digit-wise 'exclusive or' of the two (logical) operands. - """ + """Return the digit-wise 'exclusive or' of the two (logical) operands.""" def max_mag(self, other: _Decimal, context: Context | None = None) -> Decimal: - """ - Similar to the max() method, but the comparison is done using the absolute + """Similar to the max() method, but the comparison is done using the absolute values of the operands. """ def min_mag(self, other: _Decimal, context: Context | None = None) -> Decimal: - """ - Similar to the min() method, but the comparison is done using the absolute + """Similar to the min() method, but the comparison is done using the absolute values of the operands. """ def next_minus(self, context: Context | None = None) -> Decimal: - """ - Return the largest number representable in the given context (or in the + """Return the largest number representable in the given context (or in the current default context if no context is given) that is smaller than the given operand. """ def next_plus(self, context: Context | None = None) -> Decimal: - """ - Return the smallest number representable in the given context (or in the + """Return the smallest number representable in the given context (or in the current default context if no context is given) that is larger than the given operand. """ def next_toward(self, other: _Decimal, context: Context | None = None) -> Decimal: - """ - If the two operands are unequal, return the number closest to the first + """If the two operands are unequal, return the number closest to the first operand in the direction of the second operand. If both operands are numerically equal, return a copy of the first operand with the sign set to be the same as the sign of the second operand. """ def number_class(self, context: Context | None = None) -> str: - """ - Return a string describing the class of the operand. The returned value + """Return a string describing the class of the operand. The returned value is one of the following ten strings: * '-Infinity', indicating that the operand is negative infinity. @@ -716,14 +609,12 @@ class Decimal: """ def radix(self) -> Decimal: - """ - Return Decimal(10), the radix (base) in which the Decimal class does + """Return Decimal(10), the radix (base) in which the Decimal class does all its arithmetic. Included for compatibility with the specification. """ def rotate(self, other: _Decimal, context: Context | None = None) -> Decimal: - """ - Return the result of rotating the digits of the first operand by an amount + """Return the result of rotating the digits of the first operand by an amount specified by the second operand. The second operand must be an integer in the range -precision through precision. The absolute value of the second operand gives the number of places to rotate. If the second operand is @@ -734,15 +625,13 @@ class Decimal: """ def scaleb(self, other: _Decimal, context: Context | None = None) -> Decimal: - """ - Return the first operand with the exponent adjusted the second. Equivalently, + """Return the first operand with the exponent adjusted the second. Equivalently, return the first operand multiplied by 10**other. The second operand must be an integer. """ def shift(self, other: _Decimal, context: Context | None = None) -> Decimal: - """ - Return the result of shifting the digits of the first operand by an amount + """Return the result of shifting the digits of the first operand by an amount specified by the second operand. The second operand must be an integer in the range -precision through precision. The absolute value of the second operand gives the number of places to shift. If the second operand is @@ -757,8 +646,7 @@ class Decimal: def __format__(self, specifier: str, context: Context | None = None, /) -> str: ... class Context: - """ - The context affects almost all operations and controls rounding, + """The context affects almost all operations and controls rounding, Over/Underflow, raising of exceptions and much more. A new context can be constructed as follows: @@ -795,278 +683,179 @@ class Context: ) -> None: ... def __reduce__(self) -> tuple[type[Self], tuple[Any, ...]]: ... def clear_flags(self) -> None: - """ - Reset all flags to False. - """ + """Reset all flags to False.""" def clear_traps(self) -> None: - """ - Set all traps to False. - """ + """Set all traps to False.""" def copy(self) -> Context: - """ - Return a duplicate of the context with all flags cleared. - """ + """Return a duplicate of the context with all flags cleared.""" def __copy__(self) -> Context: ... # see https://github.com/python/cpython/issues/94107 __hash__: ClassVar[None] # type: ignore[assignment] def Etiny(self) -> int: - """ - Return a value equal to Emin - prec + 1, which is the minimum exponent value + """Return a value equal to Emin - prec + 1, which is the minimum exponent value for subnormal results. When underflow occurs, the exponent is set to Etiny. """ def Etop(self) -> int: - """ - Return a value equal to Emax - prec + 1. This is the maximum exponent + """Return a value equal to Emax - prec + 1. This is the maximum exponent if the _clamp field of the context is set to 1 (IEEE clamp mode). Etop() must not be negative. """ def create_decimal(self, num: _DecimalNew = "0", /) -> Decimal: - """ - Create a new Decimal instance from num, using self as the context. Unlike the + """Create a new Decimal instance from num, using self as the context. Unlike the Decimal constructor, this function observes the context limits. """ def create_decimal_from_float(self, f: float, /) -> Decimal: - """ - Create a new Decimal instance from float f. Unlike the Decimal.from_float() + """Create a new Decimal instance from float f. Unlike the Decimal.from_float() class method, this function observes the context limits. """ def abs(self, x: _Decimal, /) -> Decimal: - """ - Return the absolute value of x. - """ + """Return the absolute value of x.""" def add(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Return the sum of x and y. - """ + """Return the sum of x and y.""" def canonical(self, x: Decimal, /) -> Decimal: - """ - Return a new instance of x. - """ + """Return a new instance of x.""" def compare(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Compare x and y numerically. - """ + """Compare x and y numerically.""" def compare_signal(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Compare x and y numerically. All NaNs signal. - """ + """Compare x and y numerically. All NaNs signal.""" def compare_total(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Compare x and y using their abstract representation. - """ + """Compare x and y using their abstract representation.""" def compare_total_mag(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Compare x and y using their abstract representation, ignoring sign. - """ + """Compare x and y using their abstract representation, ignoring sign.""" def copy_abs(self, x: _Decimal, /) -> Decimal: - """ - Return a copy of x with the sign set to 0. - """ + """Return a copy of x with the sign set to 0.""" def copy_decimal(self, x: _Decimal, /) -> Decimal: - """ - Return a copy of Decimal x. - """ + """Return a copy of Decimal x.""" def copy_negate(self, x: _Decimal, /) -> Decimal: - """ - Return a copy of x with the sign inverted. - """ + """Return a copy of x with the sign inverted.""" def copy_sign(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Copy the sign from y to x. - """ + """Copy the sign from y to x.""" def divide(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Return x divided by y. - """ + """Return x divided by y.""" def divide_int(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Return x divided by y, truncated to an integer. - """ + """Return x divided by y, truncated to an integer.""" def divmod(self, x: _Decimal, y: _Decimal, /) -> tuple[Decimal, Decimal]: - """ - Return quotient and remainder of the division x / y. - """ + """Return quotient and remainder of the division x / y.""" def exp(self, x: _Decimal, /) -> Decimal: - """ - Return e ** x. - """ + """Return e ** x.""" def fma(self, x: _Decimal, y: _Decimal, z: _Decimal, /) -> Decimal: - """ - Return x multiplied by y, plus z. - """ + """Return x multiplied by y, plus z.""" def is_canonical(self, x: _Decimal, /) -> bool: - """ - Return True if x is canonical, False otherwise. - """ + """Return True if x is canonical, False otherwise.""" def is_finite(self, x: _Decimal, /) -> bool: - """ - Return True if x is finite, False otherwise. - """ + """Return True if x is finite, False otherwise.""" def is_infinite(self, x: _Decimal, /) -> bool: - """ - Return True if x is infinite, False otherwise. - """ + """Return True if x is infinite, False otherwise.""" def is_nan(self, x: _Decimal, /) -> bool: - """ - Return True if x is a qNaN or sNaN, False otherwise. - """ + """Return True if x is a qNaN or sNaN, False otherwise.""" def is_normal(self, x: _Decimal, /) -> bool: - """ - Return True if x is a normal number, False otherwise. - """ + """Return True if x is a normal number, False otherwise.""" def is_qnan(self, x: _Decimal, /) -> bool: - """ - Return True if x is a quiet NaN, False otherwise. - """ + """Return True if x is a quiet NaN, False otherwise.""" def is_signed(self, x: _Decimal, /) -> bool: - """ - Return True if x is negative, False otherwise. - """ + """Return True if x is negative, False otherwise.""" def is_snan(self, x: _Decimal, /) -> bool: - """ - Return True if x is a signaling NaN, False otherwise. - """ + """Return True if x is a signaling NaN, False otherwise.""" def is_subnormal(self, x: _Decimal, /) -> bool: - """ - Return True if x is subnormal, False otherwise. - """ + """Return True if x is subnormal, False otherwise.""" def is_zero(self, x: _Decimal, /) -> bool: - """ - Return True if x is a zero, False otherwise. - """ + """Return True if x is a zero, False otherwise.""" def ln(self, x: _Decimal, /) -> Decimal: - """ - Return the natural (base e) logarithm of x. - """ + """Return the natural (base e) logarithm of x.""" def log10(self, x: _Decimal, /) -> Decimal: - """ - Return the base 10 logarithm of x. - """ + """Return the base 10 logarithm of x.""" def logb(self, x: _Decimal, /) -> Decimal: - """ - Return the exponent of the magnitude of the operand's MSD. - """ + """Return the exponent of the magnitude of the operand's MSD.""" def logical_and(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Digit-wise and of x and y. - """ + """Digit-wise and of x and y.""" def logical_invert(self, x: _Decimal, /) -> Decimal: - """ - Invert all digits of x. - """ + """Invert all digits of x.""" def logical_or(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Digit-wise or of x and y. - """ + """Digit-wise or of x and y.""" def logical_xor(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Digit-wise xor of x and y. - """ + """Digit-wise xor of x and y.""" def max(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Compare the values numerically and return the maximum. - """ + """Compare the values numerically and return the maximum.""" def max_mag(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Compare the values numerically with their sign ignored. - """ + """Compare the values numerically with their sign ignored.""" def min(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Compare the values numerically and return the minimum. - """ + """Compare the values numerically and return the minimum.""" def min_mag(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Compare the values numerically with their sign ignored. - """ + """Compare the values numerically with their sign ignored.""" def minus(self, x: _Decimal, /) -> Decimal: - """ - Minus corresponds to the unary prefix minus operator in Python, but applies + """Minus corresponds to the unary prefix minus operator in Python, but applies the context to the result. """ def multiply(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Return the product of x and y. - """ + """Return the product of x and y.""" def next_minus(self, x: _Decimal, /) -> Decimal: - """ - Return the largest representable number smaller than x. - """ + """Return the largest representable number smaller than x.""" def next_plus(self, x: _Decimal, /) -> Decimal: - """ - Return the smallest representable number larger than x. - """ + """Return the smallest representable number larger than x.""" def next_toward(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Return the number closest to x, in the direction towards y. - """ + """Return the number closest to x, in the direction towards y.""" def normalize(self, x: _Decimal, /) -> Decimal: - """ - Reduce x to its simplest form. Alias for reduce(x). - """ + """Reduce x to its simplest form. Alias for reduce(x).""" def number_class(self, x: _Decimal, /) -> str: - """ - Return an indication of the class of x. - """ + """Return an indication of the class of x.""" def plus(self, x: _Decimal, /) -> Decimal: - """ - Plus corresponds to the unary prefix plus operator in Python, but applies + """Plus corresponds to the unary prefix plus operator in Python, but applies the context to the result. """ def power(self, a: _Decimal, b: _Decimal, modulo: _Decimal | None = None) -> Decimal: - """ - Compute a**b. If 'a' is negative, then 'b' must be integral. The result + """Compute a**b. If 'a' is negative, then 'b' must be integral. The result will be inexact unless 'a' is integral and the result is finite and can be expressed exactly in 'precision' digits. In the Python version the result is always correctly rounded, in the C version the result is almost @@ -1082,78 +871,50 @@ class Context: """ def quantize(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Return a value equal to x (rounded), having the exponent of y. - """ + """Return a value equal to x (rounded), having the exponent of y.""" def radix(self) -> Decimal: - """ - Return 10. - """ + """Return 10.""" def remainder(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Return the remainder from integer division. The sign of the result, + """Return the remainder from integer division. The sign of the result, if non-zero, is the same as that of the original dividend. """ def remainder_near(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Return x - y * n, where n is the integer nearest the exact value of x / y + """Return x - y * n, where n is the integer nearest the exact value of x / y (if the result is 0 then its sign will be the sign of x). """ def rotate(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Return a copy of x, rotated by y places. - """ + """Return a copy of x, rotated by y places.""" def same_quantum(self, x: _Decimal, y: _Decimal, /) -> bool: - """ - Return True if the two operands have the same exponent. - """ + """Return True if the two operands have the same exponent.""" def scaleb(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Return the first operand after adding the second value to its exp. - """ + """Return the first operand after adding the second value to its exp.""" def shift(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Return a copy of x, shifted by y places. - """ + """Return a copy of x, shifted by y places.""" def sqrt(self, x: _Decimal, /) -> Decimal: - """ - Square root of a non-negative number to context precision. - """ + """Square root of a non-negative number to context precision.""" def subtract(self, x: _Decimal, y: _Decimal, /) -> Decimal: - """ - Return the difference between x and y. - """ + """Return the difference between x and y.""" def to_eng_string(self, x: _Decimal, /) -> str: - """ - Convert a number to a string, using engineering notation. - """ + """Convert a number to a string, using engineering notation.""" def to_sci_string(self, x: _Decimal, /) -> str: - """ - Convert a number to a string using scientific notation. - """ + """Convert a number to a string using scientific notation.""" def to_integral_exact(self, x: _Decimal, /) -> Decimal: - """ - Round to an integer. Signal if the result is rounded or inexact. - """ + """Round to an integer. Signal if the result is rounded or inexact.""" def to_integral_value(self, x: _Decimal, /) -> Decimal: - """ - Round to an integer. - """ + """Round to an integer.""" def to_integral(self, x: _Decimal, /) -> Decimal: - """ - Identical to to_integral_value(x). - """ + """Identical to to_integral_value(x).""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/difflib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/difflib.pyi index 1a2a8b6e2d..5826b5dc41 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/difflib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/difflib.pyi @@ -1,4 +1,5 @@ """ + Module difflib -- helpers for computing deltas between objects. Function get_close_matches(word, possibilities, n=3, cutoff=0.6): @@ -48,17 +49,14 @@ __all__ = [ _T = TypeVar("_T") class Match(NamedTuple): - """ - Match(a, b, size) - """ + """Match(a, b, size)""" a: int b: int size: int class SequenceMatcher(Generic[_T]): - """ - SequenceMatcher is a flexible class for comparing pairs of sequences of + """SequenceMatcher is a flexible class for comparing pairs of sequences of any type, so long as the sequence elements are hashable. The basic algorithm predates, and is a little fancier than, an algorithm published in the late 1980's by Ratcliff and Obershelp under the @@ -133,8 +131,7 @@ class SequenceMatcher(Generic[_T]): @overload def __init__(self, isjunk: Callable[[_T], bool] | None, a: Sequence[_T], b: Sequence[_T], autojunk: bool = True) -> None: - """ - Construct a SequenceMatcher. + """Construct a SequenceMatcher. Optional arg isjunk is None (the default), or a one-argument function that takes a sequence element and returns true iff the @@ -168,8 +165,7 @@ class SequenceMatcher(Generic[_T]): autojunk: bool = True, ) -> None: ... def set_seqs(self, a: Sequence[_T], b: Sequence[_T]) -> None: - """ - Set the two sequences to be compared. + """Set the two sequences to be compared. >>> s = SequenceMatcher() >>> s.set_seqs("abcd", "bcde") @@ -178,8 +174,7 @@ class SequenceMatcher(Generic[_T]): """ def set_seq1(self, a: Sequence[_T]) -> None: - """ - Set the first sequence to be compared. + """Set the first sequence to be compared. The second sequence to be compared is not changed. @@ -200,8 +195,7 @@ class SequenceMatcher(Generic[_T]): """ def set_seq2(self, b: Sequence[_T]) -> None: - """ - Set the second sequence to be compared. + """Set the second sequence to be compared. The first sequence to be compared is not changed. @@ -222,8 +216,7 @@ class SequenceMatcher(Generic[_T]): """ def find_longest_match(self, alo: int = 0, ahi: int | None = None, blo: int = 0, bhi: int | None = None) -> Match: - """ - Find longest matching block in a[alo:ahi] and b[blo:bhi]. + """Find longest matching block in a[alo:ahi] and b[blo:bhi]. By default it will find the longest match in the entirety of a and b. @@ -269,8 +262,7 @@ class SequenceMatcher(Generic[_T]): """ def get_matching_blocks(self) -> list[Match]: - """ - Return list of triples describing matching subsequences. + """Return list of triples describing matching subsequences. Each triple is of the form (i, j, n), and means that a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in @@ -289,8 +281,7 @@ class SequenceMatcher(Generic[_T]): """ def get_opcodes(self) -> list[tuple[Literal["replace", "delete", "insert", "equal"], int, int, int, int]]: - """ - Return list of 5-tuples describing how to turn a into b. + """Return list of 5-tuples describing how to turn a into b. Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the @@ -319,8 +310,7 @@ class SequenceMatcher(Generic[_T]): """ def get_grouped_opcodes(self, n: int = 3) -> Iterable[list[tuple[str, int, int, int, int]]]: - """ - Isolate change clusters by eliminating ranges with no changes. + """Isolate change clusters by eliminating ranges with no changes. Return a generator of groups with up to n lines of context. Each group is in the same format as returned by get_opcodes(). @@ -345,8 +335,7 @@ class SequenceMatcher(Generic[_T]): """ def ratio(self) -> float: - """ - Return a measure of the sequences' similarity (float in [0,1]). + """Return a measure of the sequences' similarity (float in [0,1]). Where T is the total number of elements in both sequences, and M is the number of matches, this is 2.0*M / T. @@ -368,32 +357,28 @@ class SequenceMatcher(Generic[_T]): """ def quick_ratio(self) -> float: - """ - Return an upper bound on ratio() relatively quickly. + """Return an upper bound on ratio() relatively quickly. This isn't defined beyond that it is an upper bound on .ratio(), and is faster to compute. """ def real_quick_ratio(self) -> float: - """ - Return an upper bound on ratio() very quickly. + """Return an upper bound on ratio() very quickly. This isn't defined beyond that it is an upper bound on .ratio(), and is faster to compute than either .ratio() or .quick_ratio(). """ def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ @overload def get_close_matches(word: AnyStr, possibilities: Iterable[AnyStr], n: int = 3, cutoff: float = 0.6) -> list[AnyStr]: - """ - Use SequenceMatcher to return list of the best "good enough" matches. + """Use SequenceMatcher to return list of the best "good enough" matches. word is a sequence for which close matches are desired (typically a string). @@ -427,8 +412,7 @@ def get_close_matches( ) -> list[Sequence[_T]]: ... class Differ: - """ - Differ is a class for comparing sequences of lines of text, and + """Differ is a class for comparing sequences of lines of text, and producing human-readable differences or deltas. Differ uses SequenceMatcher both to compare sequences of lines, and to compare sequences of characters within similar (near-matching) lines. @@ -513,8 +497,7 @@ class Differ: """ def __init__(self, linejunk: Callable[[str], bool] | None = None, charjunk: Callable[[str], bool] | None = None) -> None: - """ - Construct a text differencer, with optional filters. + """Construct a text differencer, with optional filters. The two optional keyword parameters are for filter functions: @@ -533,8 +516,7 @@ class Differ: """ def compare(self, a: Sequence[str], b: Sequence[str]) -> Iterator[str]: - """ - Compare two sequences of lines; generate the resulting delta. + """Compare two sequences of lines; generate the resulting delta. Each sequence must contain individual single-line strings ending with newlines. Such sequences can be obtained from the `readlines()` method @@ -559,8 +541,7 @@ class Differ: """ def IS_LINE_JUNK(line: str, pat: Any = ...) -> bool: # pat is undocumented - """ - Return True for ignorable line: if `line` is blank or contains a single '#'. + """Return True for ignorable line: if `line` is blank or contains a single '#'. Examples: @@ -573,8 +554,7 @@ def IS_LINE_JUNK(line: str, pat: Any = ...) -> bool: # pat is undocumented """ def IS_CHARACTER_JUNK(ch: str, ws: str = " \t") -> bool: # ws is undocumented - """ - Return True for ignorable character: iff `ch` is a space or tab. + """Return True for ignorable character: iff `ch` is a space or tab. Examples: @@ -598,8 +578,7 @@ def unified_diff( n: int = 3, lineterm: str = "\n", ) -> Iterator[str]: - """ - Compare two sequences of lines; generate the delta as a unified diff. + """Compare two sequences of lines; generate the delta as a unified diff. Unified diffs are a compact way of showing line changes and a few lines of context. The number of context lines is set by 'n' which @@ -647,8 +626,7 @@ def context_diff( n: int = 3, lineterm: str = "\n", ) -> Iterator[str]: - """ - Compare two sequences of lines; generate the delta as a context diff. + """Compare two sequences of lines; generate the delta as a context diff. Context diffs are a compact way of showing line changes and a few lines of context. The number of context lines is set by 'n' which @@ -695,8 +673,7 @@ def ndiff( linejunk: Callable[[str], bool] | None = None, charjunk: Callable[[str], bool] | None = ..., ) -> Iterator[str]: - """ - Compare `a` and `b` (lists of strings); return a `Differ`-style delta. + """Compare `a` and `b` (lists of strings); return a `Differ`-style delta. Optional keyword parameters `linejunk` and `charjunk` are for filter functions, or can be None: @@ -731,8 +708,7 @@ def ndiff( """ class HtmlDiff: - """ - For producing HTML side by side comparison with change highlights. + """For producing HTML side by side comparison with change highlights. This class can be used to create an HTML table (or a complete HTML file containing the table) showing a side by side, line by line comparison @@ -754,8 +730,7 @@ class HtmlDiff: linejunk: Callable[[str], bool] | None = None, charjunk: Callable[[str], bool] | None = ..., ) -> None: - """ - HtmlDiff instance initializer + """HtmlDiff instance initializer Arguments: tabsize -- tab stop spacing, defaults to 8. @@ -777,8 +752,7 @@ class HtmlDiff: *, charset: str = "utf-8", ) -> str: - """ - Returns HTML file of side by side comparison with change highlights + """Returns HTML file of side by side comparison with change highlights Arguments: fromlines -- list of "from" lines @@ -804,8 +778,7 @@ class HtmlDiff: context: bool = False, numlines: int = 5, ) -> str: - """ - Returns HTML table of side by side comparison with change highlights + """Returns HTML table of side by side comparison with change highlights Arguments: fromlines -- list of "from" lines @@ -822,8 +795,7 @@ class HtmlDiff: """ def restore(delta: Iterable[str], which: int) -> Iterator[str]: - """ - Generate one of the two sequences that generated a delta. + """Generate one of the two sequences that generated a delta. Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract lines originating from file 1 or 2 (parameter `which`), stripping off line @@ -855,8 +827,7 @@ def diff_bytes( n: int = 3, lineterm: bytes | bytearray = b"\n", ) -> Iterator[bytes]: - """ - Compare `a` and `b`, two sequences of lines represented as bytes rather + """Compare `a` and `b`, two sequences of lines represented as bytes rather than str. This is a wrapper for `dfunc`, which is typically either unified_diff() or context_diff(). Inputs are losslessly converted to strings so that `dfunc` only has to worry about strings, and encoded diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/dis.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/dis.pyi index f32660243a..7970d386f9 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/dis.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/dis.pyi @@ -49,9 +49,7 @@ _HaveCodeType: TypeAlias = types.MethodType | types.FunctionType | types.CodeTyp if sys.version_info >= (3, 11): class Positions(NamedTuple): - """ - Positions(lineno, end_lineno, col_offset, end_col_offset) - """ + """Positions(lineno, end_lineno, col_offset, end_col_offset)""" lineno: int | None = None end_lineno: int | None = None @@ -60,9 +58,7 @@ if sys.version_info >= (3, 11): if sys.version_info >= (3, 13): class _Instruction(NamedTuple): - """ - _Instruction(opname, opcode, arg, argval, argrepr, offset, start_offset, starts_line, line_number, label, positions, cache_info) - """ + """_Instruction(opname, opcode, arg, argval, argrepr, offset, start_offset, starts_line, line_number, label, positions, cache_info)""" opname: str opcode: int @@ -79,9 +75,7 @@ if sys.version_info >= (3, 13): elif sys.version_info >= (3, 11): class _Instruction(NamedTuple): - """ - _Instruction(opname, opcode, arg, argval, argrepr, offset, starts_line, is_jump_target, positions) - """ + """_Instruction(opname, opcode, arg, argval, argrepr, offset, starts_line, is_jump_target, positions)""" opname: str opcode: int @@ -95,9 +89,7 @@ elif sys.version_info >= (3, 11): else: class _Instruction(NamedTuple): - """ - _Instruction(opname, opcode, arg, argval, argrepr, offset, starts_line, is_jump_target) - """ + """_Instruction(opname, opcode, arg, argval, argrepr, offset, starts_line, is_jump_target)""" opname: str opcode: int @@ -109,8 +101,7 @@ else: is_jump_target: bool class Instruction(_Instruction): - """ - Details for a bytecode operation. + """Details for a bytecode operation. Defined fields: opname - human readable name for operation @@ -135,51 +126,40 @@ class Instruction(_Instruction): if sys.version_info >= (3, 13): @property def oparg(self) -> int: - """ - Alias for Instruction.arg. - """ + """Alias for Instruction.arg.""" @property def baseopcode(self) -> int: - """ - Numeric code for the base operation if operation is specialized. + """Numeric code for the base operation if operation is specialized. Otherwise equal to Instruction.opcode. """ @property def baseopname(self) -> str: - """ - Human readable name for the base operation if operation is specialized. + """Human readable name for the base operation if operation is specialized. Otherwise equal to Instruction.opname. """ @property def cache_offset(self) -> int: - """ - Start index of the cache entries following the operation. - """ + """Start index of the cache entries following the operation.""" @property def end_offset(self) -> int: - """ - End index of the cache entries following the operation. - """ + """End index of the cache entries following the operation.""" @property def jump_target(self) -> int: - """ - Bytecode index of the jump target if this is a jump operation. + """Bytecode index of the jump target if this is a jump operation. Otherwise return None. """ @property def is_jump_target(self) -> bool: - """ - True if other code jumps to here, otherwise False - """ + """True if other code jumps to here, otherwise False""" if sys.version_info >= (3, 14): @staticmethod def make( @@ -197,8 +177,7 @@ class Instruction(_Instruction): ) -> Instruction: ... class Bytecode: - """ - The bytecode operations of a piece of code + """The bytecode operations of a piece of code Instantiate this with a function, method, other compiled object, string of code, or a code object (as returned by compile()). @@ -253,53 +232,39 @@ class Bytecode: if sys.version_info >= (3, 11): @classmethod def from_traceback(cls, tb: types.TracebackType, *, show_caches: bool = False, adaptive: bool = False) -> Self: - """ - Construct a Bytecode from the given traceback - """ + """Construct a Bytecode from the given traceback""" else: @classmethod def from_traceback(cls, tb: types.TracebackType) -> Self: - """ - Construct a Bytecode from the given traceback - """ + """Construct a Bytecode from the given traceback""" def __iter__(self) -> Iterator[Instruction]: ... def info(self) -> str: - """ - Return formatted information about the code object. - """ + """Return formatted information about the code object.""" def dis(self) -> str: - """ - Return a formatted view of the bytecode operations. - """ + """Return a formatted view of the bytecode operations.""" COMPILER_FLAG_NAMES: dict[int, str] def findlabels(code: _HaveCodeType) -> list[int]: - """ - Detect all offsets in a byte code which are jump targets. + """Detect all offsets in a byte code which are jump targets. Return the list of offsets. """ def findlinestarts(code: _HaveCodeType) -> Iterator[tuple[int, int]]: - """ - Find the offsets in a byte code which are start of lines in the source. + """Find the offsets in a byte code which are start of lines in the source. Generate pairs (offset, lineno) lineno will be an integer or None the offset does not have a source line. """ def pretty_flags(flags: int) -> str: - """ - Return pretty representation of code flags. - """ + """Return pretty representation of code flags.""" def code_info(x: _HaveCodeType | str) -> str: - """ - Formatted details of methods, functions, or code. - """ + """Formatted details of methods, functions, or code.""" if sys.version_info >= (3, 14): # 3.14 added `show_positions` @@ -313,8 +278,7 @@ if sys.version_info >= (3, 14): show_offsets: bool = False, show_positions: bool = False, ) -> None: - """ - Disassemble classes, methods, functions, and other compiled objects. + """Disassemble classes, methods, functions, and other compiled objects. With no argument, disassemble the last traceback. @@ -333,9 +297,7 @@ if sys.version_info >= (3, 14): show_offsets: bool = False, show_positions: bool = False, ) -> None: - """ - Disassemble a code object. - """ + """Disassemble a code object.""" def distb( tb: types.TracebackType | None = None, @@ -346,9 +308,7 @@ if sys.version_info >= (3, 14): show_offsets: bool = False, show_positions: bool = False, ) -> None: - """ - Disassemble a traceback (default: last traceback). - """ + """Disassemble a traceback (default: last traceback).""" elif sys.version_info >= (3, 13): # 3.13 added `show_offsets` @@ -361,8 +321,7 @@ elif sys.version_info >= (3, 13): adaptive: bool = False, show_offsets: bool = False, ) -> None: - """ - Disassemble classes, methods, functions, and other compiled objects. + """Disassemble classes, methods, functions, and other compiled objects. With no argument, disassemble the last traceback. @@ -380,9 +339,7 @@ elif sys.version_info >= (3, 13): adaptive: bool = False, show_offsets: bool = False, ) -> None: - """ - Disassemble a code object. - """ + """Disassemble a code object.""" def distb( tb: types.TracebackType | None = None, @@ -392,9 +349,7 @@ elif sys.version_info >= (3, 13): adaptive: bool = False, show_offsets: bool = False, ) -> None: - """ - Disassemble a traceback (default: last traceback). - """ + """Disassemble a traceback (default: last traceback).""" elif sys.version_info >= (3, 11): # 3.11 added `show_caches` and `adaptive` @@ -406,8 +361,7 @@ elif sys.version_info >= (3, 11): show_caches: bool = False, adaptive: bool = False, ) -> None: - """ - Disassemble classes, methods, functions, and other compiled objects. + """Disassemble classes, methods, functions, and other compiled objects. With no argument, disassemble the last traceback. @@ -419,23 +373,18 @@ elif sys.version_info >= (3, 11): def disassemble( co: _HaveCodeType, lasti: int = -1, *, file: IO[str] | None = None, show_caches: bool = False, adaptive: bool = False ) -> None: - """ - Disassemble a code object. - """ + """Disassemble a code object.""" def distb( tb: types.TracebackType | None = None, *, file: IO[str] | None = None, show_caches: bool = False, adaptive: bool = False ) -> None: - """ - Disassemble a traceback (default: last traceback). - """ + """Disassemble a traceback (default: last traceback).""" else: def dis( x: _HaveCodeType | str | bytes | bytearray | None = None, *, file: IO[str] | None = None, depth: int | None = None ) -> None: - """ - Disassemble classes, methods, functions, and other compiled objects. + """Disassemble classes, methods, functions, and other compiled objects. With no argument, disassemble the last traceback. @@ -445,22 +394,17 @@ else: """ def disassemble(co: _HaveCodeType, lasti: int = -1, *, file: IO[str] | None = None) -> None: - """ - Disassemble a code object. - """ + """Disassemble a code object.""" def distb(tb: types.TracebackType | None = None, *, file: IO[str] | None = None) -> None: - """ - Disassemble a traceback (default: last traceback). - """ + """Disassemble a traceback (default: last traceback).""" if sys.version_info >= (3, 13): # 3.13 made `show_cache` `None` by default def get_instructions( x: _HaveCodeType, *, first_line: int | None = None, show_caches: bool | None = None, adaptive: bool = False ) -> Iterator[Instruction]: - """ - Iterator for the opcodes in methods, functions or code + """Iterator for the opcodes in methods, functions or code Generates a series of Instruction named tuples giving the details of each operations in the supplied code. @@ -475,8 +419,7 @@ elif sys.version_info >= (3, 11): def get_instructions( x: _HaveCodeType, *, first_line: int | None = None, show_caches: bool = False, adaptive: bool = False ) -> Iterator[Instruction]: - """ - Iterator for the opcodes in methods, functions or code + """Iterator for the opcodes in methods, functions or code Generates a series of Instruction named tuples giving the details of each operations in the supplied code. @@ -489,8 +432,7 @@ elif sys.version_info >= (3, 11): else: def get_instructions(x: _HaveCodeType, *, first_line: int | None = None) -> Iterator[Instruction]: - """ - Iterator for the opcodes in methods, functions or code + """Iterator for the opcodes in methods, functions or code Generates a series of Instruction named tuples giving the details of each operations in the supplied code. @@ -502,8 +444,7 @@ else: """ def show_code(co: _HaveCodeType, *, file: IO[str] | None = None) -> None: - """ - Print details of methods, functions, or code to *file*. + """Print details of methods, functions, or code to *file*. If *file* is not provided, the output is printed on stdout. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/_msvccompiler.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/_msvccompiler.pyi index bba9373b72..ecd10d4f5c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/_msvccompiler.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/_msvccompiler.pyi @@ -1,3 +1,13 @@ +""" +distutils._msvccompiler + +Contains MSVCCompiler, an implementation of the abstract CCompiler class +for Microsoft Visual Studio 2015. + +The module is compatible with VS 2015 and later. You can find legacy support +for older versions in distutils.msvc9compiler and distutils.msvccompiler. +""" + from _typeshed import Incomplete from distutils.ccompiler import CCompiler from typing import ClassVar, Final @@ -6,6 +16,10 @@ PLAT_SPEC_TO_RUNTIME: Final[dict[str, str]] PLAT_TO_VCVARS: Final[dict[str, str]] class MSVCCompiler(CCompiler): + """Concrete class that implements an interface to Microsoft Visual C++, + as defined by the CCompiler abstract class. + """ + compiler_type: ClassVar[str] executables: ClassVar[dict[Incomplete, Incomplete]] res_extension: ClassVar[str] diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/archive_util.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/archive_util.pyi index 376b6c676d..2057ca7af1 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/archive_util.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/archive_util.pyi @@ -19,8 +19,7 @@ def make_archive( owner: str | None = None, group: str | None = None, ) -> str: - """ - Create an archive file (eg. zip or tar). + """Create an archive file (eg. zip or tar). 'base_name' is the name of the file to create, minus any format-specific extension; 'format' is the archive format: one of "zip", "tar", "gztar", @@ -57,8 +56,7 @@ def make_tarball( owner: str | None = None, group: str | None = None, ) -> str: - """ - Create a (possibly compressed) tar file from all the files under + """Create a (possibly compressed) tar file from all the files under 'base_dir'. 'compress' must be "gzip" (the default), "bzip2", "xz", "compress", or @@ -75,8 +73,7 @@ def make_tarball( """ def make_zipfile(base_name: str, base_dir: str, verbose: bool | Literal[0, 1] = 0, dry_run: bool | Literal[0, 1] = 0) -> str: - """ - Create a zip file from all the files under 'base_dir'. + """Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/bcppcompiler.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/bcppcompiler.pyi index 350d047d97..a08461d2ed 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/bcppcompiler.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/bcppcompiler.pyi @@ -8,7 +8,6 @@ for the Borland C++ compiler. from distutils.ccompiler import CCompiler class BCPPCompiler(CCompiler): - """ - Concrete class that implements an interface to the Borland C/C++ + """Concrete class that implements an interface to the Borland C/C++ compiler, as defined by the CCompiler abstract class. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/ccompiler.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/ccompiler.pyi index 34940e14ec..5cbb709a09 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/ccompiler.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/ccompiler.pyi @@ -17,8 +17,7 @@ _Ts = TypeVarTuple("_Ts") def gen_lib_options( compiler: CCompiler, library_dirs: list[str], runtime_library_dirs: list[str], libraries: list[str] ) -> list[str]: - """ - Generate linker options for searching library directories and + """Generate linker options for searching library directories and linking with specific libraries. 'libraries' and 'library_dirs' are, respectively, lists of library names (not filenames!) and search directories. Returns a list of command-line options suitable for use @@ -26,8 +25,7 @@ def gen_lib_options( """ def gen_preprocess_options(macros: list[_Macro], include_dirs: list[str]) -> list[str]: - """ - Generate C pre-processor options (-D, -U, -I) as used by at least + """Generate C pre-processor options (-D, -U, -I) as used by at least two types of compilers: the typical Unix compiler and Visual C++. 'macros' is the usual thing, a list of 1- or 2-tuples, where (name,) means undefine (-U) macro 'name', and (name,value) means define (-D) @@ -38,8 +36,7 @@ def gen_preprocess_options(macros: list[_Macro], include_dirs: list[str]) -> lis """ def get_default_compiler(osname: str | None = None, platform: str | None = None) -> str: - """ - Determine the default compiler to use for the given platform. + """Determine the default compiler to use for the given platform. osname should be one of the standard Python OS names (i.e. the ones returned by os.name) and platform the common value @@ -56,8 +53,7 @@ def new_compiler( dry_run: bool | Literal[0, 1] = 0, force: bool | Literal[0, 1] = 0, ) -> CCompiler: - """ - Generate an instance of some CCompiler subclass for the supplied + """Generate an instance of some CCompiler subclass for the supplied platform/compiler combination. 'plat' defaults to 'os.name' (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler for that platform. Currently only 'posix' and 'nt' are supported, and @@ -69,14 +65,12 @@ def new_compiler( """ def show_compilers() -> None: - """ - Print list of available compilers (used by the "--help-compiler" + """Print list of available compilers (used by the "--help-compiler" options to "build", "build_ext", "build_clib"). """ class CCompiler: - """ - Abstract base class to define the interface that must be implemented + """Abstract base class to define the interface that must be implemented by real compiler classes. Also has some utility methods used by several compiler classes. @@ -103,16 +97,14 @@ class CCompiler: self, verbose: bool | Literal[0, 1] = 0, dry_run: bool | Literal[0, 1] = 0, force: bool | Literal[0, 1] = 0 ) -> None: ... def add_include_dir(self, dir: str) -> None: - """ - Add 'dir' to the list of directories that will be searched for + """Add 'dir' to the list of directories that will be searched for header files. The compiler is instructed to search directories in the order in which they are supplied by successive calls to 'add_include_dir()'. """ def set_include_dirs(self, dirs: list[str]) -> None: - """ - Set the list of directories that will be searched to 'dirs' (a + """Set the list of directories that will be searched to 'dirs' (a list of strings). Overrides any preceding calls to 'add_include_dir()'; subsequence calls to 'add_include_dir()' add to the list passed to 'set_include_dirs()'. This does not affect @@ -121,8 +113,7 @@ class CCompiler: """ def add_library(self, libname: str) -> None: - """ - Add 'libname' to the list of libraries that will be included in + """Add 'libname' to the list of libraries that will be included in all links driven by this compiler object. Note that 'libname' should *not* be the name of a file containing a library, but the name of the library itself: the actual filename will be inferred by @@ -137,45 +128,39 @@ class CCompiler: """ def set_libraries(self, libnames: list[str]) -> None: - """ - Set the list of libraries to be included in all links driven by + """Set the list of libraries to be included in all links driven by this compiler object to 'libnames' (a list of strings). This does not affect any standard system libraries that the linker may include by default. """ def add_library_dir(self, dir: str) -> None: - """ - Add 'dir' to the list of directories that will be searched for + """Add 'dir' to the list of directories that will be searched for libraries specified to 'add_library()' and 'set_libraries()'. The linker will be instructed to search for libraries in the order they are supplied to 'add_library_dir()' and/or 'set_library_dirs()'. """ def set_library_dirs(self, dirs: list[str]) -> None: - """ - Set the list of library search directories to 'dirs' (a list of + """Set the list of library search directories to 'dirs' (a list of strings). This does not affect any standard library search path that the linker may search by default. """ def add_runtime_library_dir(self, dir: str) -> None: - """ - Add 'dir' to the list of directories that will be searched for + """Add 'dir' to the list of directories that will be searched for shared libraries at runtime. """ def set_runtime_library_dirs(self, dirs: list[str]) -> None: - """ - Set the list of directories to search for shared libraries at + """Set the list of directories to search for shared libraries at runtime to 'dirs' (a list of strings). This does not affect any standard search path that the runtime linker may search by default. """ def define_macro(self, name: str, value: str | None = None) -> None: - """ - Define a preprocessor macro for all compilations driven by this + """Define a preprocessor macro for all compilations driven by this compiler object. The optional parameter 'value' should be a string; if it is not supplied, then the macro will be defined without an explicit value and the exact outcome depends on the @@ -183,8 +168,7 @@ class CCompiler: """ def undefine_macro(self, name: str) -> None: - """ - Undefine a preprocessor macro for all compilations driven by + """Undefine a preprocessor macro for all compilations driven by this compiler object. If the same macro is defined by 'define_macro()' and undefined by 'undefine_macro()' the last call takes precedence (including multiple redefinitions or @@ -194,30 +178,26 @@ class CCompiler: """ def add_link_object(self, object: str) -> None: - """ - Add 'object' to the list of object files (or analogues, such as + """Add 'object' to the list of object files (or analogues, such as explicitly named library files or the output of "resource compilers") to be included in every link driven by this compiler object. """ def set_link_objects(self, objects: list[str]) -> None: - """ - Set the list of object files (or analogues) to be included in + """Set the list of object files (or analogues) to be included in every link to 'objects'. This does not affect any standard object files that the linker may include by default (such as system libraries). """ def detect_language(self, sources: str | list[str]) -> str | None: - """ - Detect the language of a given file, or list of files. Uses + """Detect the language of a given file, or list of files. Uses language_map, and language_order to do the job. """ def find_library_file(self, dirs: list[str], lib: str, debug: bool | Literal[0, 1] = 0) -> str | None: - """ - Search the specified list of directories for a static or shared + """Search the specified list of directories for a static or shared library file 'lib' and return the full path to that file. If 'debug' true, look for a debugging version (if that makes sense on the current platform). Return None if 'lib' wasn't found in any of @@ -232,33 +212,28 @@ class CCompiler: libraries: list[str] | None = None, library_dirs: list[str] | None = None, ) -> bool: - """ - Return a boolean indicating whether funcname is supported on + """Return a boolean indicating whether funcname is supported on the current platform. The optional arguments can be used to augment the compilation environment. """ def library_dir_option(self, dir: str) -> str: - """ - Return the compiler option to add 'dir' to the list of + """Return the compiler option to add 'dir' to the list of directories searched for libraries. """ def library_option(self, lib: str) -> str: - """ - Return the compiler option to add 'lib' to the list of libraries + """Return the compiler option to add 'lib' to the list of libraries linked into the shared library or executable. """ def runtime_library_dir_option(self, dir: str) -> str: - """ - Return the compiler option to add 'dir' to the list of + """Return the compiler option to add 'dir' to the list of directories searched for runtime libraries. """ def set_executables(self, **args: str) -> None: - """ - Define the executables (and options for them) that will be run + """Define the executables (and options for them) that will be run to perform the various stages of compilation. The exact set of executables that may be specified here depends on the compiler class (via the 'executables' class attribute), but most will have: @@ -286,8 +261,7 @@ class CCompiler: extra_postargs: list[str] | None = None, depends: list[str] | None = None, ) -> list[str]: - """ - Compile one or more source files. + """Compile one or more source files. 'sources' must be a list of filenames, most likely C/C++ files, but in reality anything that can be handled by a @@ -344,8 +318,7 @@ class CCompiler: debug: bool | Literal[0, 1] = 0, target_lang: str | None = None, ) -> None: - """ - Link a bunch of stuff together to create a static library file. + """Link a bunch of stuff together to create a static library file. The "bunch of stuff" consists of the list of object files supplied as 'objects', the extra object files supplied to 'add_link_object()' and/or 'set_link_objects()', the libraries @@ -384,8 +357,7 @@ class CCompiler: build_temp: str | None = None, target_lang: str | None = None, ) -> None: - """ - Link a bunch of stuff together to create an executable or + """Link a bunch of stuff together to create an executable or shared library file. The "bunch of stuff" consists of the list of object files supplied @@ -481,8 +453,7 @@ class CCompiler: extra_preargs: list[str] | None = None, extra_postargs: list[str] | None = None, ) -> None: - """ - Preprocess a single C/C++ source file, named in 'source'. + """Preprocess a single C/C++ source file, named in 'source'. Output will be written to file named 'output_file', or stdout if 'output_file' not supplied. 'macros' is a list of macro definitions as for 'compile()', which will augment the macros set diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/cmd.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/cmd.pyi index a5c4520961..908a40af4d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/cmd.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/cmd.pyi @@ -37,8 +37,7 @@ _CommandT = TypeVar("_CommandT", bound=Command) _Ts = TypeVarTuple("_Ts") class Command: - """ - Abstract base class for defining command classes, the "worker bees" + """Abstract base class for defining command classes, the "worker bees" of the Distutils. A useful analogy for command classes is to think of them as subroutines with local variables called "options". The options are "declared" in 'initialize_options()' and "defined" (given their @@ -58,8 +57,7 @@ class Command: # Any to work around variance issues sub_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]] def __init__(self, dist: Distribution) -> None: - """ - Create and initialize a new Command object. Most importantly, + """Create and initialize a new Command object. Most importantly, invokes the 'initialize_options()' method, which is the real initializer and depends on the actual command being instantiated. @@ -67,8 +65,7 @@ class Command: @abstractmethod def initialize_options(self) -> None: - """ - Set default values for all the options that this command + """Set default values for all the options that this command supports. Note that these defaults may be overridden by other commands, by the setup script, by config files, or by the command-line. Thus, this is not the place to code dependencies @@ -80,8 +77,7 @@ class Command: @abstractmethod def finalize_options(self) -> None: - """ - Set final values for all the options that this command supports. + """Set final values for all the options that this command supports. This is always called as late as possible, ie. after any option assignments from the command-line or from other commands have been done. Thus, this is the place to code option dependencies: if @@ -94,8 +90,7 @@ class Command: @abstractmethod def run(self) -> None: - """ - A command's raison d'etre: carry out the action it exists to + """A command's raison d'etre: carry out the action it exists to perform, controlled by the options initialized in 'initialize_options()', customized by other commands, the setup script, the command-line, and config files, and finalized in @@ -106,41 +101,34 @@ class Command: """ def announce(self, msg: str, level: int = 1) -> None: - """ - If the current verbosity level is of greater than or equal to + """If the current verbosity level is of greater than or equal to 'level' print 'msg' to stdout. """ def debug_print(self, msg: str) -> None: - """ - Print 'msg' to stdout if the global DEBUG (taken from the + """Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true. """ def ensure_string(self, option: str, default: str | None = None) -> None: - """ - Ensure that 'option' is a string; if not defined, set it to + """Ensure that 'option' is a string; if not defined, set it to 'default'. """ def ensure_string_list(self, option: str) -> None: - """ - Ensure that 'option' is a list of strings. If 'option' is + """Ensure that 'option' is a list of strings. If 'option' is currently a string, we split it either on /,\\s*/ or /\\s+/, so "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become ["foo", "bar", "baz"]. """ def ensure_filename(self, option: str) -> None: - """ - Ensure that 'option' is the name of an existing file. - """ + """Ensure that 'option' is the name of an existing file.""" def ensure_dirname(self, option: str) -> None: ... def get_command_name(self) -> str: ... def set_undefined_options(self, src_cmd: str, *option_pairs: tuple[str, str]) -> None: - """ - Set the values of any "undefined" options from corresponding + """Set the values of any "undefined" options from corresponding option values in some other command object. "Undefined" here means "is None", which is the convention used to indicate that an option has not been changed between 'initialize_options()' and @@ -156,8 +144,7 @@ class Command: # NOTE: This list comes directly from the distutils/command folder. Minus bdist_msi and bdist_wininst. @overload def get_finalized_command(self, command: Literal["bdist"], create: bool | Literal[0, 1] = 1) -> bdist: - """ - Wrapper around Distribution's 'get_command_obj()' method: find + """Wrapper around Distribution's 'get_command_obj()' method: find (create if necessary and 'create' is true) the command object for 'command', call its 'ensure_finalized()' method, and return the finalized command object. @@ -266,15 +253,13 @@ class Command: @overload def reinitialize_command(self, command: _CommandT, reinit_subcommands: bool | Literal[0, 1] = 0) -> _CommandT: ... def run_command(self, command: str) -> None: - """ - Run some other command: uses the 'run_command()' method of + """Run some other command: uses the 'run_command()' method of Distribution, which creates and finalizes the command object if necessary and then invokes its 'run()' method. """ def get_sub_commands(self) -> list[str]: - """ - Determine the sub-commands that are relevant in the current + """Determine the sub-commands that are relevant in the current distribution (ie., that need to be run). This is based on the 'sub_commands' class attribute: each tuple in that list may include a method that we call to determine if the subcommand needs to be @@ -296,8 +281,7 @@ class Command: link: str | None = None, level: Unused = 1, ) -> tuple[_StrPathT | str, bool]: - """ - Copy a file respecting verbose, dry-run and force flags. (The + """Copy a file respecting verbose, dry-run and force flags. (The former two default to whatever is in the Distribution object, and the latter defaults to false for commands that don't define it.) """ @@ -321,23 +305,18 @@ class Command: preserve_symlinks: bool | Literal[0, 1] = 0, level: Unused = 1, ) -> list[str]: - """ - Copy an entire directory tree respecting verbose, dry-run, + """Copy an entire directory tree respecting verbose, dry-run, and force flags. """ @overload def move_file(self, src: StrPath, dst: _StrPathT, level: Unused = 1) -> _StrPathT | str: - """ - Move a file respecting dry-run flag. - """ + """Move a file respecting dry-run flag.""" @overload def move_file(self, src: BytesPath, dst: _BytesPathT, level: Unused = 1) -> _BytesPathT | bytes: ... def spawn(self, cmd: Iterable[str], search_path: bool | Literal[0, 1] = 1, level: Unused = 1) -> None: - """ - Spawn an external command respecting dry-run flag. - """ + """Spawn an external command respecting dry-run flag.""" @overload def make_archive( @@ -369,8 +348,7 @@ class Command: skip_msg: str | None = None, level: Unused = 1, ) -> None: - """ - Special case of 'execute()' for operations that process one or + """Special case of 'execute()' for operations that process one or more input files and generate one output file. Works just like 'execute()', except the operation is skipped and a different message printed if 'outfile' already exists and is newer than all diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/bdist.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/bdist.pyi index 2562576b5f..b368d1411f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/bdist.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/bdist.pyi @@ -12,9 +12,7 @@ from typing import ClassVar from ..cmd import Command def show_formats() -> None: - """ - Print list of available formats (arguments to "--format" option). - """ + """Print list of available formats (arguments to "--format" option).""" class bdist(Command): description: str diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/bdist_msi.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/bdist_msi.pyi index d677f81d14..668342e0b5 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/bdist_msi.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/bdist_msi.pyi @@ -1,3 +1,8 @@ +""" + +Implements the bdist_msi command. +""" + import sys from _typeshed import Incomplete from typing import ClassVar, Literal @@ -8,12 +13,47 @@ if sys.platform == "win32": from msilib import Control, Dialog class PyDialog(Dialog): - def __init__(self, *args, **kw) -> None: ... - def title(self, title) -> None: ... - def back(self, title, next, name: str = "Back", active: bool | Literal[0, 1] = 1) -> Control: ... - def cancel(self, title, next, name: str = "Cancel", active: bool | Literal[0, 1] = 1) -> Control: ... - def next(self, title, next, name: str = "Next", active: bool | Literal[0, 1] = 1) -> Control: ... - def xbutton(self, name, title, next, xpos) -> Control: ... + """Dialog class with a fixed layout: controls at the top, then a ruler, + then a list of buttons: back, next, cancel. Optionally a bitmap at the + left. + """ + + def __init__(self, *args, **kw) -> None: + """Dialog(database, name, x, y, w, h, attributes, title, first, + default, cancel, bitmap=true) + """ + + def title(self, title) -> None: + """Set the title text of the dialog at the top.""" + + def back(self, title, next, name: str = "Back", active: bool | Literal[0, 1] = 1) -> Control: + """Add a back button with a given title, the tab-next button, + its name in the Control table, possibly initially disabled. + + Return the button, so that events can be associated + """ + + def cancel(self, title, next, name: str = "Cancel", active: bool | Literal[0, 1] = 1) -> Control: + """Add a cancel button with a given title, the tab-next button, + its name in the Control table, possibly initially disabled. + + Return the button, so that events can be associated + """ + + def next(self, title, next, name: str = "Next", active: bool | Literal[0, 1] = 1) -> Control: + """Add a Next button with a given title, the tab-next button, + its name in the Control table, possibly initially disabled. + + Return the button, so that events can be associated + """ + + def xbutton(self, name, title, next, xpos) -> Control: + """Add a button with a given title, the tab-next button, + its name in the Control table, giving its x position; the + y-position is aligned with the other buttons. + + Return the button, so that events can be associated + """ class bdist_msi(Command): description: str @@ -39,7 +79,18 @@ if sys.platform == "win32": db: Incomplete def run(self) -> None: ... def add_files(self) -> None: ... - def add_find_python(self) -> None: ... + def add_find_python(self) -> None: + """Adds code to the installer to compute the location of Python. + + Properties PYTHON.MACHINE.X.Y and PYTHON.USER.X.Y will be set from the + registry for each version of Python. + + Properties TARGETDIRX.Y will be set from PYTHON.USER.X.Y if defined, + else from PYTHON.MACHINE.X.Y. + + Properties PYTHONX.Y will be set to TARGETDIRX.Y\\python.exe + """ + def add_scripts(self) -> None: ... def add_ui(self) -> None: ... def get_installer_filename(self, fullname): ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/build_clib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/build_clib.pyi index 37449f7c0b..4fd9c6a64b 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/build_clib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/build_clib.pyi @@ -32,8 +32,7 @@ class build_clib(Command): def finalize_options(self) -> None: ... def run(self) -> None: ... def check_library_list(self, libraries) -> None: - """ - Ensure that the list of libraries is valid. + """Ensure that the list of libraries is valid. `library` is presumably provided as a command option 'libraries'. This method checks that it is a list of 2-tuples, where the tuples diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/build_ext.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/build_ext.pyi index e7a1c15ae0..1cbdad8e9d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/build_ext.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/build_ext.pyi @@ -47,8 +47,7 @@ class build_ext(Command): def finalize_options(self) -> None: ... def run(self) -> None: ... def check_extensions_list(self, extensions) -> None: - """ - Ensure that the list of extensions (presumably provided as a + """Ensure that the list of extensions (presumably provided as a command option 'extensions') is valid, i.e. it is a list of Extension objects. We also support the old-style list of 2-tuples, where the tuples are (ext_name, build_info), which are converted to @@ -63,53 +62,46 @@ class build_ext(Command): def build_extensions(self) -> None: ... def build_extension(self, ext) -> None: ... def swig_sources(self, sources, extension): - """ - Walk the list of source files in 'sources', looking for SWIG + """Walk the list of source files in 'sources', looking for SWIG interface (.i) files. Run SWIG on all that are found, and return a modified 'sources' list with SWIG source files replaced by the generated C (or C++) files. """ def find_swig(self): - """ - Return the name of the SWIG executable. On Unix, this is + """Return the name of the SWIG executable. On Unix, this is just "swig" -- it should be in the PATH. Tries a bit harder on Windows. """ def get_ext_fullpath(self, ext_name: str) -> str: - """ - Returns the path of the filename for a given extension. + """Returns the path of the filename for a given extension. The file is located in `build_lib` or directly in the package (inplace option). """ def get_ext_fullname(self, ext_name: str) -> str: - """ - Returns the fullname of a given extension name. + """Returns the fullname of a given extension name. Adds the `package.` prefix """ def get_ext_filename(self, ext_name: str) -> str: - """ - Convert the name of an extension (eg. "foo.bar") into the name + """Convert the name of an extension (eg. "foo.bar") into the name of the file from which it will be loaded (eg. "foo/bar.so", or "foo\\bar.pyd"). """ def get_export_symbols(self, ext): - """ - Return the list of symbols that a shared extension has to + """Return the list of symbols that a shared extension has to export. This either uses 'ext.export_symbols' or, if it's not provided, "PyInit_" + module_name. Only relevant on Windows, where the .pyd file (DLL) must export the module "PyInit_" function. """ def get_libraries(self, ext): - """ - Return the list of libraries to link against when building a + """Return the list of libraries to link against when building a shared extension. On most platforms, this is just 'ext.libraries'; on Windows, we add the Python library (eg. python20.dll). """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/build_py.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/build_py.pyi index 3327763d06..7bc04cfaa8 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/build_py.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/build_py.pyi @@ -29,23 +29,16 @@ class build_py(Command): def finalize_options(self) -> None: ... def run(self) -> None: ... def get_data_files(self): - """ - Generate list of '(package,src_dir,build_dir,filenames)' tuples - """ + """Generate list of '(package,src_dir,build_dir,filenames)' tuples""" def find_data_files(self, package, src_dir): - """ - Return filenames for package's data files in 'src_dir' - """ + """Return filenames for package's data files in 'src_dir'""" def build_package_data(self) -> None: - """ - Copy data files into build directory - """ + """Copy data files into build directory""" def get_package_dir(self, package): - """ - Return the directory, relative to the top of the source + """Return the directory, relative to the top of the source distribution, where package 'package' should be found (at least according to the 'package_dir' option, if any). """ @@ -54,8 +47,7 @@ class build_py(Command): def check_module(self, module, module_file): ... def find_package_modules(self, package, package_dir): ... def find_modules(self): - """ - Finds individually-specified Python modules, ie. those listed by + """Finds individually-specified Python modules, ie. those listed by module name in 'self.py_modules'. Returns a list of tuples (package, module_base, filename): 'package' is a tuple of the path through package-space to the module; 'module_base' is the bare (no @@ -65,8 +57,7 @@ class build_py(Command): """ def find_all_modules(self): - """ - Compute the list of all modules that will be built, whether + """Compute the list of all modules that will be built, whether they are specified one-module-at-a-time ('self.py_modules') or by whole packages ('self.packages'). Return a list of tuples (package, module, module_file), just like 'find_modules()' and diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/build_scripts.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/build_scripts.pyi index e8d25f6bcb..1d8563fff1 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/build_scripts.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/build_scripts.pyi @@ -26,8 +26,7 @@ class build_scripts(Command): def get_source_files(self): ... def run(self) -> None: ... def copy_scripts(self): - """ - Copy each script listed in 'self.scripts'; if it's marked as a + """Copy each script listed in 'self.scripts'; if it's marked as a Python script in the Unix way (first line matches 'first_line_re', ie. starts with "\\#!" and contains "python"), then adjust the first line to refer to the current Python interpreter as we copy. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/check.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/check.pyi index 0318100da8..746bcc8fe2 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/check.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/check.pyi @@ -32,9 +32,7 @@ class SilentReporter(_Reporter): HAS_DOCUTILS: Final[bool] class check(Command): - """ - This command checks the meta-data of the package. - """ + """This command checks the meta-data of the package.""" description: str user_options: ClassVar[list[tuple[str, str, str]]] @@ -43,24 +41,17 @@ class check(Command): metadata: int strict: int def initialize_options(self) -> None: - """ - Sets default values for options. - """ + """Sets default values for options.""" def finalize_options(self) -> None: ... def warn(self, msg): - """ - Counts the number of warnings that occurs. - """ + """Counts the number of warnings that occurs.""" def run(self) -> None: - """ - Runs the command. - """ + """Runs the command.""" def check_metadata(self) -> None: - """ - Ensures that all required elements of meta-data are supplied. + """Ensures that all required elements of meta-data are supplied. Required fields: name, version, URL @@ -72,6 +63,4 @@ class check(Command): """ def check_restructuredtext(self) -> None: - """ - Checks if the long string fields are reST-compliant. - """ + """Checks if the long string fields are reST-compliant.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/config.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/config.pyi index 5ea637652e..a5d6a0982d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/config.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/config.pyi @@ -42,8 +42,7 @@ class config(Command): include_dirs: Sequence[str] | None = None, lang: str = "c", ) -> bool: - """ - Construct a source file from 'body' (a string containing lines + """Construct a source file from 'body' (a string containing lines of C/C++ code) and 'headers' (a list of header files to include) and run it through the preprocessor. Return true if the preprocessor succeeded, false if there were any errors. @@ -58,8 +57,7 @@ class config(Command): include_dirs: Sequence[str] | None = None, lang: str = "c", ) -> bool: - """ - Construct a source file (just like 'try_cpp()'), run it through + """Construct a source file (just like 'try_cpp()'), run it through the preprocessor, and return true if any line of the output matches 'pattern'. 'pattern' should either be a compiled regex object or a string containing a regex. If both 'body' and 'headers' are None, @@ -70,8 +68,7 @@ class config(Command): def try_compile( self, body: str, headers: Sequence[str] | None = None, include_dirs: Sequence[str] | None = None, lang: str = "c" ) -> bool: - """ - Try to compile a source file built from 'body' and 'headers'. + """Try to compile a source file built from 'body' and 'headers'. Return true on success, false otherwise. """ @@ -84,8 +81,7 @@ class config(Command): library_dirs: Sequence[str] | None = None, lang: str = "c", ) -> bool: - """ - Try to compile and link a source file, built from 'body' and + """Try to compile and link a source file, built from 'body' and 'headers', to executable form. Return true on success, false otherwise. """ @@ -99,8 +95,7 @@ class config(Command): library_dirs: Sequence[str] | None = None, lang: str = "c", ) -> bool: - """ - Try to compile, link to an executable, and run a program + """Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Return true on success, false otherwise. """ @@ -115,8 +110,7 @@ class config(Command): decl: bool | Literal[0, 1] = 0, call: bool | Literal[0, 1] = 0, ) -> bool: - """ - Determine if function 'func' is available by constructing a + """Determine if function 'func' is available by constructing a source file that refers to 'func', and compiles and links it. If everything succeeds, returns true; otherwise returns false. @@ -138,8 +132,7 @@ class config(Command): include_dirs: Sequence[str] | None = None, other_libraries: list[str] = [], ) -> bool: - """ - Determine if 'library' is available to be linked against, + """Determine if 'library' is available to be linked against, without actually checking that any particular symbols are provided by it. 'headers' will be used in constructing the source file to be compiled, but the only effect of this is to check if all the @@ -151,15 +144,13 @@ class config(Command): def check_header( self, header: str, include_dirs: Sequence[str] | None = None, library_dirs: Sequence[str] | None = None, lang: str = "c" ) -> bool: - """ - Determine if the system header file named by 'header_file' + """Determine if the system header file named by 'header_file' exists and can be found by the preprocessor; return true if so, false otherwise. """ def dump_file(filename: StrOrBytesPath, head=None) -> None: - """ - Dumps a file content into log.info. + """Dumps a file content into log.info. If head is not None, will be dumped before the file content. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/install.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/install.pyi index cc6d034f1c..a0e8b00011 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/install.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/install.pyi @@ -50,109 +50,74 @@ class install(Command): build_lib: Incomplete record: Incomplete def initialize_options(self) -> None: - """ - Initializes options. - """ + """Initializes options.""" config_vars: Incomplete install_libbase: Incomplete def finalize_options(self) -> None: - """ - Finalizes options. - """ + """Finalizes options.""" def dump_dirs(self, msg) -> None: - """ - Dumps the list of user options. - """ + """Dumps the list of user options.""" def finalize_unix(self) -> None: - """ - Finalizes options for posix platforms. - """ + """Finalizes options for posix platforms.""" def finalize_other(self) -> None: - """ - Finalizes options for non-posix platforms - """ + """Finalizes options for non-posix platforms""" def select_scheme(self, name) -> None: - """ - Sets the install directories by applying the install schemes. - """ + """Sets the install directories by applying the install schemes.""" def expand_basedirs(self) -> None: - """ - Calls `os.path.expanduser` on install_base, install_platbase and + """Calls `os.path.expanduser` on install_base, install_platbase and root. """ def expand_dirs(self) -> None: - """ - Calls `os.path.expanduser` on install dirs. - """ + """Calls `os.path.expanduser` on install dirs.""" def convert_paths(self, *names) -> None: - """ - Call `convert_path` over `names`. - """ + """Call `convert_path` over `names`.""" path_file: Incomplete extra_dirs: Incomplete def handle_extra_path(self) -> None: - """ - Set `path_file` and `extra_dirs` using `extra_path`. - """ + """Set `path_file` and `extra_dirs` using `extra_path`.""" def change_roots(self, *names) -> None: - """ - Change the install directories pointed by name using root. - """ + """Change the install directories pointed by name using root.""" def create_home_path(self) -> None: - """ - Create directories under ~. - """ + """Create directories under ~.""" def run(self) -> None: - """ - Runs the command. - """ + """Runs the command.""" def create_path_file(self) -> None: - """ - Creates the .pth file - """ + """Creates the .pth file""" def get_outputs(self): - """ - Assembles the outputs of all the sub-commands. - """ + """Assembles the outputs of all the sub-commands.""" def get_inputs(self): - """ - Returns the inputs of all the sub-commands - """ + """Returns the inputs of all the sub-commands""" def has_lib(self): - """ - Returns true if the current distribution has any Python + """Returns true if the current distribution has any Python modules to install. """ def has_headers(self): - """ - Returns true if the current distribution has any headers to + """Returns true if the current distribution has any headers to install. """ def has_scripts(self): - """ - Returns true if the current distribution has any scripts to. + """Returns true if the current distribution has any scripts to. install. """ def has_data(self): - """ - Returns true if the current distribution has any data to. + """Returns true if the current distribution has any data to. install. """ # Any to work around variance issues diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/install_egg_info.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/install_egg_info.pyi index 59f8e22f3b..c50d2e23dc 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/install_egg_info.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/install_egg_info.pyi @@ -11,9 +11,7 @@ from typing import ClassVar from ..cmd import Command class install_egg_info(Command): - """ - Install an .egg-info file for the package - """ + """Install an .egg-info file for the package""" description: ClassVar[str] user_options: ClassVar[list[tuple[str, str, str]]] @@ -26,23 +24,20 @@ class install_egg_info(Command): def get_outputs(self) -> list[str]: ... def safe_name(name): - """ - Convert an arbitrary string to a standard distribution name + """Convert an arbitrary string to a standard distribution name Any runs of non-alphanumeric/. characters are replaced with a single '-'. """ def safe_version(version): - """ - Convert an arbitrary string to a standard version string + """Convert an arbitrary string to a standard version string Spaces become dots, and all other non-alphanumeric characters become dashes, with runs of multiple dashes condensed to a single dash. """ def to_filename(name): - """ - Convert a project or version name to its filename-escaped form + """Convert a project or version name to its filename-escaped form Any '-' characters are currently replaced with '_'. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/install_lib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/install_lib.pyi index b993b234e2..8bc650c2cd 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/install_lib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/install_lib.pyi @@ -30,15 +30,13 @@ class install_lib(Command): def install(self): ... def byte_compile(self, files) -> None: ... def get_outputs(self): - """ - Return the list of files that would be installed if this command + """Return the list of files that would be installed if this command were actually run. Not affected by the "dry-run" flag or whether modules have actually been built yet. """ def get_inputs(self): - """ - Get the list of files that are input to this command, ie. the + """Get the list of files that are input to this command, ie. the files that get installed as they are named in the build tree. The files in this list correspond one-to-one to the output filenames returned by 'get_outputs()'. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/register.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/register.pyi index 2cd70e4aa9..e146411bad 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/register.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/register.pyi @@ -19,23 +19,16 @@ class register(PyPIRCCommand): def finalize_options(self) -> None: ... def run(self) -> None: ... def check_metadata(self) -> None: - """ - Deprecated API. - """ + """Deprecated API.""" def classifiers(self) -> None: - """ - Fetch the list of classifiers from the server. - """ + """Fetch the list of classifiers from the server.""" def verify_metadata(self) -> None: - """ - Send the metadata to the package index server to be checked. - """ + """Send the metadata to the package index server to be checked.""" def send_metadata(self) -> None: - """ - Send the metadata to the package index server. + """Send the metadata to the package index server. Well, do the following: 1. figure who the user is, and then @@ -64,6 +57,4 @@ class register(PyPIRCCommand): def build_post_data(self, action): ... def post_to_server(self, data, auth=None): - """ - Post a query to the server, and return a string response. - """ + """Post a query to the server, and return a string response.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/sdist.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/sdist.pyi index a617888d47..ac68fb52a2 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/sdist.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/sdist.pyi @@ -11,16 +11,14 @@ from typing import Any, ClassVar from ..cmd import Command def show_formats() -> None: - """ - Print all possible values for the 'formats' option (used by + """Print all possible values for the 'formats' option (used by the "--help-formats" command-line option). """ class sdist(Command): description: str def checking_metadata(self): - """ - Callable used for the check sub-command. + """Callable used for the check sub-command. Placed here so user_options can view it """ @@ -49,13 +47,10 @@ class sdist(Command): filelist: Incomplete def run(self) -> None: ... def check_metadata(self) -> None: - """ - Deprecated API. - """ + """Deprecated API.""" def get_file_list(self) -> None: - """ - Figure out the list of files to include in the source + """Figure out the list of files to include in the source distribution, and put it in 'self.filelist'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all @@ -63,8 +58,7 @@ class sdist(Command): """ def add_defaults(self) -> None: - """ - Add all the default files to self.filelist: + """Add all the default files to self.filelist: - README or README.txt - setup.py - test/test*.py @@ -79,16 +73,14 @@ class sdist(Command): """ def read_template(self) -> None: - """ - Read and parse manifest template file named by self.template. + """Read and parse manifest template file named by self.template. (usually "MANIFEST.in") The parsing and processing is done by 'self.filelist', which updates itself accordingly. """ def prune_file_list(self) -> None: - """ - Prune off branches that might slip into the file list as created + """Prune off branches that might slip into the file list as created by 'read_template()', but really don't belong there: * the build tree (typically "build") * the release tree itself (only an issue if we ran "sdist" @@ -97,22 +89,19 @@ class sdist(Command): """ def write_manifest(self) -> None: - """ - Write the file list in 'self.filelist' (presumably as filled in + """Write the file list in 'self.filelist' (presumably as filled in by 'add_defaults()' and 'read_template()') to the manifest file named by 'self.manifest'. """ def read_manifest(self) -> None: - """ - Read the manifest file (named by 'self.manifest') and use it to + """Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution. """ def make_release_tree(self, base_dir, files) -> None: - """ - Create the directory tree that will become the source + """Create the directory tree that will become the source distribution archive. All directories implied by the filenames in 'files' are created under 'base_dir', and then we hard link or copy (if hard linking is unavailable) those files into place. @@ -122,8 +111,7 @@ class sdist(Command): """ def make_distribution(self) -> None: - """ - Create the source distribution(s). First, we create the release + """Create the source distribution(s). First, we create the release tree with 'make_release_tree()'; then, we create all required archive files (according to 'self.formats') from the release tree. Finally, we clean up by blowing away the release tree (unless @@ -132,7 +120,6 @@ class sdist(Command): """ def get_archive_files(self): - """ - Return the list of archive files created when the command + """Return the list of archive files created when the command was run, or None if the command hasn't run yet. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/upload.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/upload.pyi index a34bcb86f8..817c98a234 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/upload.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/command/upload.pyi @@ -1,4 +1,5 @@ """ + distutils.command.upload Implements the Distutils 'upload' subcommand (upload package to a package diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/config.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/config.pyi index 6e0a8ba94d..ac9ab00d4c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/config.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/config.pyi @@ -12,9 +12,7 @@ from typing import ClassVar DEFAULT_PYPIRC: str class PyPIRCCommand(Command): - """ - Base command that knows how to handle the .pypirc file - """ + """Base command that knows how to handle the .pypirc file""" DEFAULT_REPOSITORY: ClassVar[str] DEFAULT_REALM: ClassVar[str] @@ -23,19 +21,14 @@ class PyPIRCCommand(Command): user_options: ClassVar[list[tuple[str, str | None, str]]] boolean_options: ClassVar[list[str]] def initialize_options(self) -> None: - """ - Initialize options. - """ + """Initialize options.""" def finalize_options(self) -> None: - """ - Finalizes options. - """ + """Finalizes options.""" @abstractmethod def run(self) -> None: - """ - A command's raison d'etre: carry out the action it exists to + """A command's raison d'etre: carry out the action it exists to perform, controlled by the options initialized in 'initialize_options()', customized by other commands, the setup script, the command-line, and config files, and finalized in diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/core.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/core.pyi index 7216c1d5a2..d509df7241 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/core.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/core.pyi @@ -64,8 +64,7 @@ def setup( # Custom Distributions could accept more params **attrs: Any, ) -> Distribution: - """ - The gateway to the Distutils: do everything your setup script needs + """The gateway to the Distutils: do everything your setup script needs to do, in a highly flexible and user-driven way. Briefly: create a Distribution instance; find and parse config files; parse the command line; run each Distutils command found there, customized by the options @@ -98,8 +97,7 @@ def setup( """ def run_setup(script_name: str, script_args: list[str] | None = None, stop_after: str = "run") -> Distribution: - """ - Run a setup script in a somewhat controlled environment, and + """Run a setup script in a somewhat controlled environment, and return the Distribution instance that drives things. This is useful if you need to find out the distribution meta-data (passed as keyword args from 'script' to 'setup()', or the contents of the diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/cygwinccompiler.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/cygwinccompiler.pyi index 4f3c6cb477..b5846f5c4e 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/cygwinccompiler.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/cygwinccompiler.pyi @@ -13,28 +13,22 @@ from re import Pattern from typing import Final, Literal def get_msvcr() -> list[str] | None: - """ - Include the appropriate MSVC runtime library if Python was built + """Include the appropriate MSVC runtime library if Python was built with MSVC 7.0 or later. """ class CygwinCCompiler(UnixCCompiler): - """ - Handles the Cygwin port of the GNU C compiler to Windows. - """ + """Handles the Cygwin port of the GNU C compiler to Windows.""" class Mingw32CCompiler(CygwinCCompiler): - """ - Handles the Mingw32 port of the GNU C compiler to Windows. - """ + """Handles the Mingw32 port of the GNU C compiler to Windows.""" CONFIG_H_OK: Final = "ok" CONFIG_H_NOTOK: Final = "not ok" CONFIG_H_UNCERTAIN: Final = "uncertain" def check_config_h() -> tuple[Literal["ok", "not ok", "uncertain"], str]: - """ - Check if the current Python installation appears amenable to building + """Check if the current Python installation appears amenable to building extensions with GCC. Returns a tuple (status, details), where 'status' is one of the following @@ -54,13 +48,10 @@ def check_config_h() -> tuple[Literal["ok", "not ok", "uncertain"], str]: RE_VERSION: Final[Pattern[bytes]] def get_versions() -> tuple[LooseVersion | None, ...]: - """ - Try to find out the versions of gcc, ld and dllwrap. + """Try to find out the versions of gcc, ld and dllwrap. If not possible it returns None for it. """ def is_cygwingcc() -> bool: - """ - Try to determine if the gcc that would be used is from cygwin. - """ + """Try to determine if the gcc that would be used is from cygwin.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/dep_util.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/dep_util.pyi index 454045e10f..ad2495b530 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/dep_util.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/dep_util.pyi @@ -14,8 +14,7 @@ _SourcesT = TypeVar("_SourcesT", bound=StrOrBytesPath) _TargetsT = TypeVar("_TargetsT", bound=StrOrBytesPath) def newer(source: StrOrBytesPath, target: StrOrBytesPath) -> bool | Literal[1]: - """ - Return true if 'source' exists and is more recently modified than + """Return true if 'source' exists and is more recently modified than 'target', or if 'source' exists and 'target' doesn't. Return false if both exist and 'target' is the same age or younger than 'source'. Raise DistutilsFileError if 'source' does not exist. @@ -24,8 +23,7 @@ def newer(source: StrOrBytesPath, target: StrOrBytesPath) -> bool | Literal[1]: def newer_pairwise( sources: SupportsLenAndGetItem[_SourcesT], targets: SupportsLenAndGetItem[_TargetsT] ) -> tuple[list[_SourcesT], list[_TargetsT]]: - """ - Walk two filename lists in parallel, testing if each source is newer + """Walk two filename lists in parallel, testing if each source is newer than its corresponding target. Return a pair of lists (sources, targets) where source is newer than target, according to the semantics of 'newer()'. @@ -34,8 +32,7 @@ def newer_pairwise( def newer_group( sources: Iterable[StrOrBytesPath], target: StrOrBytesPath, missing: Literal["error", "ignore", "newer"] = "error" ) -> Literal[0, 1]: - """ - Return true if 'target' is out-of-date with respect to any file + """Return true if 'target' is out-of-date with respect to any file listed in 'sources'. In other words, if 'target' exists and is newer than every file in 'sources', return false; otherwise return true. 'missing' controls what we do when a source file is missing; the diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/dir_util.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/dir_util.pyi index 4dd35f5edf..ee75fc6a02 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/dir_util.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/dir_util.pyi @@ -9,8 +9,7 @@ from collections.abc import Iterable from typing import Literal def mkpath(name: str, mode: int = 0o777, verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0) -> list[str]: - """ - Create a directory and any missing ancestor directories. + """Create a directory and any missing ancestor directories. If the directory already exists (or if 'name' is the empty string, which means the current directory, which of course exists), then do nothing. @@ -27,8 +26,7 @@ def create_tree( verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0, ) -> None: - """ - Create all the empty directories under 'base_dir' needed to put 'files' + """Create all the empty directories under 'base_dir' needed to put 'files' there. 'base_dir' is just the name of a directory which doesn't necessarily @@ -48,8 +46,7 @@ def copy_tree( verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0, ) -> list[str]: - """ - Copy an entire directory tree 'src' to a new location 'dst'. + """Copy an entire directory tree 'src' to a new location 'dst'. Both 'src' and 'dst' must be directory names. If 'src' is not a directory, raise DistutilsFileError. If 'dst' does not exist, it is @@ -70,8 +67,7 @@ def copy_tree( """ def remove_tree(directory: StrOrBytesPath, verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0) -> None: - """ - Recursively remove an entire directory tree. + """Recursively remove an entire directory tree. Any errors are ignored (apart from being reported to stdout if 'verbose' is true). diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/dist.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/dist.pyi index df7f7b2b2c..528a1912b7 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/dist.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/dist.pyi @@ -38,8 +38,7 @@ _OptionsList: TypeAlias = list[tuple[str, str | None, str, int] | tuple[str, str _CommandT = TypeVar("_CommandT", bound=Command) class DistributionMetadata: - """ - Dummy class to hold the distribution meta-data: name, version, + """Dummy class to hold the distribution meta-data: name, version, author, and so forth. """ @@ -62,19 +61,13 @@ class DistributionMetadata: requires: list[str] | None obsoletes: list[str] | None def read_pkg_file(self, file: IO[str]) -> None: - """ - Reads the metadata values from a file object. - """ + """Reads the metadata values from a file object.""" def write_pkg_info(self, base_dir: StrPath) -> None: - """ - Write the PKG-INFO file into the release tree. - """ + """Write the PKG-INFO file into the release tree.""" def write_pkg_file(self, file: SupportsWrite[str]) -> None: - """ - Write the PKG-INFO format data to a file object. - """ + """Write the PKG-INFO format data to a file object.""" def get_name(self) -> str: ... def get_version(self) -> str: ... @@ -102,8 +95,7 @@ class DistributionMetadata: def set_obsoletes(self, value: Iterable[str]) -> None: ... class Distribution: - """ - The core of the Distutils. Most of the work hiding behind 'setup' + """The core of the Distutils. Most of the work hiding behind 'setup' is really done within a Distribution instance, which farms the work out to the Distutils commands specified on the command line. @@ -119,8 +111,7 @@ class Distribution: cmdclass: dict[str, type[Command]] metadata: DistributionMetadata def __init__(self, attrs: MutableMapping[str, Incomplete] | None = None) -> None: - """ - Construct a new Distribution instance: initialize all the + """Construct a new Distribution instance: initialize all the attributes of a Distribution, and then use 'attrs' (a dictionary mapping attribute names to values) to assign some of those attributes their "real" values. (Any attributes not mentioned in @@ -131,8 +122,7 @@ class Distribution: """ def get_option_dict(self, command: str) -> dict[str, tuple[str, str]]: - """ - Get the option dictionary for a given command. If that + """Get the option dictionary for a given command. If that command's option dictionary hasn't been created yet, then create it and return the new dictionary; otherwise, return the existing option dictionary. @@ -170,8 +160,7 @@ class Distribution: want_user_cfg: bool def dump_option_dicts(self, header=None, commands=None, indent: str = "") -> None: ... def find_config_files(self): - """ - Find as many configuration files as should be processed for this + """Find as many configuration files as should be processed for this platform, and return a list of filenames in the order in which they should be parsed. The filenames returned are guaranteed to exist (modulo nasty race conditions). @@ -187,8 +176,7 @@ class Distribution: """ commands: Incomplete def parse_command_line(self): - """ - Parse the setup script's command line, taken from the + """Parse the setup script's command line, taken from the 'script_args' instance attribute (which defaults to 'sys.argv[1:]' -- see 'setup()' in core.py). This list is first processed for "global options" -- options that set attributes of the Distribution @@ -208,29 +196,25 @@ class Distribution: """ def finalize_options(self) -> None: - """ - Set final values for all the options on the Distribution + """Set final values for all the options on the Distribution instance, analogous to the .finalize_options() method of Command objects. """ def handle_display_options(self, option_order): - """ - If there were any non-global "display-only" options + """If there were any non-global "display-only" options (--help-commands or the metadata display options) on the command line, display the requested info and return true; else return false. """ def print_command_list(self, commands, header, max_length) -> None: - """ - Print a subset of the list of all commands -- used by + """Print a subset of the list of all commands -- used by 'print_commands()'. """ def print_commands(self) -> None: - """ - Print out a help message listing all available commands with a + """Print out a help message listing all available commands with a description of each. The list is divided into "standard commands" (listed in distutils.command.__all__) and "extra commands" (mentioned in self.cmdclass, but not a standard command). The @@ -239,8 +223,7 @@ class Distribution: """ def get_command_list(self): - """ - Get a list of (command, description) tuples. + """Get a list of (command, description) tuples. The list is divided into "standard commands" (listed in distutils.command.__all__) and "extra commands" (mentioned in self.cmdclass, but not a standard command). The descriptions come @@ -248,14 +231,11 @@ class Distribution: """ def get_command_packages(self): - """ - Return a list of packages from which commands are loaded. - """ + """Return a list of packages from which commands are loaded.""" # NOTE: This list comes directly from the distutils/command folder. Minus bdist_msi and bdist_wininst. @overload def get_command_obj(self, command: Literal["bdist"], create: Literal[1, True] = 1) -> bdist: - """ - Return the command object for 'command'. Normally this object + """Return the command object for 'command'. Normally this object is cached on a previous call to 'get_command_obj()'; if no command object for 'command' is in the cache, then we either create and return it (if 'create' is true) or return None. @@ -306,8 +286,7 @@ class Distribution: def get_command_obj(self, command: str, create: Literal[0, False]) -> Command | None: ... @overload def get_command_class(self, command: Literal["bdist"]) -> type[bdist]: - """ - Return the class that implements the Distutils command named by + """Return the class that implements the Distutils command named by 'command'. First we check the 'cmdclass' dictionary; if the command is mentioned there, we fetch the class object from the dictionary and return it. Otherwise we load the command module @@ -361,8 +340,7 @@ class Distribution: def get_command_class(self, command: str) -> type[Command]: ... @overload def reinitialize_command(self, command: Literal["bdist"], reinit_subcommands: bool = False) -> bdist: - """ - Reinitializes a command to the state it was in when first + """Reinitializes a command to the state it was in when first returned by 'get_command_obj()': ie., initialized but not yet finalized. This provides the opportunity to sneak option values in programmatically, overriding or supplementing @@ -427,15 +405,13 @@ class Distribution: def reinitialize_command(self, command: _CommandT, reinit_subcommands: bool = False) -> _CommandT: ... def announce(self, msg, level: int = 2) -> None: ... def run_commands(self) -> None: - """ - Run each command that was seen on the setup script command line. + """Run each command that was seen on the setup script command line. Uses the list of commands found and cache of command objects created by 'get_command_obj()'. """ def run_command(self, command: str) -> None: - """ - Do whatever it takes to run a command (including nothing at all, + """Do whatever it takes to run a command (including nothing at all, if the command has already been run). Specifically: if we have already created and run the command named by 'command', return silently without doing anything. If the command named by 'command' diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/errors.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/errors.pyi index d0975f3a6f..70161cf24d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/errors.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/errors.pyi @@ -11,45 +11,36 @@ symbols whose names start with "Distutils" and end with "Error". """ class DistutilsError(Exception): - """ - The root of all Distutils evil. - """ + """The root of all Distutils evil.""" class DistutilsModuleError(DistutilsError): - """ - Unable to load an expected module, or to find an expected class + """Unable to load an expected module, or to find an expected class within some module (in particular, command modules and classes). """ class DistutilsClassError(DistutilsError): - """ - Some command class (or possibly distribution class, if anyone + """Some command class (or possibly distribution class, if anyone feels a need to subclass Distribution) is found not to be holding up its end of the bargain, ie. implementing some part of the "command "interface. """ class DistutilsGetoptError(DistutilsError): - """ - The option table provided to 'fancy_getopt()' is bogus. - """ + """The option table provided to 'fancy_getopt()' is bogus.""" class DistutilsArgError(DistutilsError): - """ - Raised by fancy_getopt in response to getopt.error -- ie. an + """Raised by fancy_getopt in response to getopt.error -- ie. an error in the command line usage. """ class DistutilsFileError(DistutilsError): - """ - Any problems in the filesystem: expected file not found, etc. + """Any problems in the filesystem: expected file not found, etc. Typically this is for problems that we detect before OSError could be raised. """ class DistutilsOptionError(DistutilsError): - """ - Syntactic/semantic errors in command options, such as use of + """Syntactic/semantic errors in command options, such as use of mutually conflicting options, or inconsistent options, badly-spelled values, etc. No distinction is made between option values originating in the setup script, the command line, config @@ -58,68 +49,50 @@ class DistutilsOptionError(DistutilsError): """ class DistutilsSetupError(DistutilsError): - """ - For errors that can be definitely blamed on the setup script, + """For errors that can be definitely blamed on the setup script, such as invalid keyword arguments to 'setup()'. """ class DistutilsPlatformError(DistutilsError): - """ - We don't know how to do something on the current platform (but + """We don't know how to do something on the current platform (but we do know how to do it on some platform) -- eg. trying to compile C files on a platform not supported by a CCompiler subclass. """ class DistutilsExecError(DistutilsError): - """ - Any problems executing an external program (such as the C + """Any problems executing an external program (such as the C compiler, when compiling C files). """ class DistutilsInternalError(DistutilsError): - """ - Internal inconsistencies or impossibilities (obviously, this + """Internal inconsistencies or impossibilities (obviously, this should never be seen if the code is working!). """ class DistutilsTemplateError(DistutilsError): - """ - Syntax error in a file list template. - """ + """Syntax error in a file list template.""" class DistutilsByteCompileError(DistutilsError): - """ - Byte compile error. - """ + """Byte compile error.""" class CCompilerError(Exception): - """ - Some compile/link operation failed. - """ + """Some compile/link operation failed.""" class PreprocessError(CCompilerError): - """ - Failure to preprocess one or more C/C++ files. - """ + """Failure to preprocess one or more C/C++ files.""" class CompileError(CCompilerError): - """ - Failure to compile one or more C/C++ source files. - """ + """Failure to compile one or more C/C++ source files.""" class LibError(CCompilerError): - """ - Failure to create a static library from one or more C/C++ object + """Failure to create a static library from one or more C/C++ object files. """ class LinkError(CCompilerError): - """ - Failure to link one or more C/C++ object files into an executable + """Failure to link one or more C/C++ object files into an executable or shared library file. """ class UnknownFileError(CCompilerError): - """ - Attempt to process an unknown file type. - """ + """Attempt to process an unknown file type.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/extension.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/extension.pyi index 75fb246e15..a43db1d7eb 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/extension.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/extension.pyi @@ -6,8 +6,7 @@ modules in setup scripts. """ class Extension: - """ - Just a collection of attributes that describes an extension + """Just a collection of attributes that describes an extension module and everything needed to build it (hopefully in a portable way, but there are hooks that let you be as unportable as you need). diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/fancy_getopt.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/fancy_getopt.pyi index d67745bd0c..509634ccad 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/fancy_getopt.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/fancy_getopt.pyi @@ -23,8 +23,7 @@ neg_alias_re: Final[Pattern[str]] longopt_xlate: Final[dict[int, int]] class FancyGetopt: - """ - Wrapper around the standard 'getopt()' module that provides some + """Wrapper around the standard 'getopt()' module that provides some handy extra functionality: * short and long options are tied together * options have help strings, and help text can be assembled @@ -41,8 +40,7 @@ class FancyGetopt: def getopt( self, args: _SliceableT[_StrSequenceT_co] | None = None, object: None = None ) -> tuple[_StrSequenceT_co, OptionDummy]: - """ - Parse command-line options in args. Store as attributes on object. + """Parse command-line options in args. Store as attributes on object. If 'args' is None or not supplied, uses 'sys.argv[1:]'. If 'object' is None or not supplied, creates a new OptionDummy @@ -58,15 +56,13 @@ class FancyGetopt: self, args: _SliceableT[_StrSequenceT_co] | None, object: Any ) -> _StrSequenceT_co: ... # object is an arbitrary non-slotted object def get_option_order(self) -> list[tuple[str, str]]: - """ - Returns the list of (option, value) tuples processed by the + """Returns the list of (option, value) tuples processed by the previous run of 'getopt()'. Raises RuntimeError if 'getopt()' hasn't been called yet. """ def generate_help(self, header: str | None = None) -> list[str]: - """ - Generate help text (a list of strings, one per suggested line of + """Generate help text (a list of strings, one per suggested line of output) from the option table for this FancyGetopt object. """ @@ -83,27 +79,23 @@ def fancy_getopt( WS_TRANS: Final[dict[int, str]] def wrap_text(text: str, width: int) -> list[str]: - """ - wrap_text(text : string, width : int) -> [string] + """wrap_text(text : string, width : int) -> [string] Split 'text' into multiple lines of no more than 'width' characters each, and return the list of strings that results. """ def translate_longopt(opt: str) -> str: - """ - Convert a long option name to a valid Python identifier by + """Convert a long option name to a valid Python identifier by changing "-" to "_". """ class OptionDummy: - """ - Dummy class just used as a place to hold command-line option + """Dummy class just used as a place to hold command-line option values as instance attributes. """ def __init__(self, options: Iterable[str] = []) -> None: - """ - Create a new OptionDummy instance. The attributes listed in + """Create a new OptionDummy instance. The attributes listed in 'options' will be initialized to None. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/file_util.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/file_util.pyi index 39bddfaeb9..6631d7bade 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/file_util.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/file_util.pyi @@ -22,8 +22,7 @@ def copy_file( verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0, ) -> tuple[_StrPathT | str, bool]: - """ - Copy a file 'src' to 'dst'. If 'dst' is a directory, then 'src' is + """Copy a file 'src' to 'dst'. If 'dst' is a directory, then 'src' is copied there with the same name; otherwise, it must be a filename. (If the file exists, it will be ruthlessly clobbered.) If 'preserve_mode' is true (the default), the file's mode (type and permission bits, or @@ -63,8 +62,7 @@ def copy_file( def move_file( src: StrPath, dst: _StrPathT, verbose: bool | Literal[0, 1] = 0, dry_run: bool | Literal[0, 1] = 0 ) -> _StrPathT | str: - """ - Move a file 'src' to 'dst'. If 'dst' is a directory, the file will + """Move a file 'src' to 'dst'. If 'dst' is a directory, the file will be moved into it with the same name; otherwise, 'src' is just renamed to 'dst'. Return the new full name of the file. @@ -77,7 +75,6 @@ def move_file( src: BytesPath, dst: _BytesPathT, verbose: bool | Literal[0, 1] = 0, dry_run: bool | Literal[0, 1] = 0 ) -> _BytesPathT | bytes: ... def write_file(filename: StrOrBytesPath, contents: Iterable[str]) -> None: - """ - Create a file with the specified name and write 'contents' (a + """Create a file with the specified name and write 'contents' (a sequence of strings without line terminators) to it. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/filelist.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/filelist.pyi index bd63dfbeef..01412b5c18 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/filelist.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/filelist.pyi @@ -11,8 +11,7 @@ from typing import Literal, overload # class is entirely undocumented class FileList: - """ - A list of files built by on exploring the filesystem and filtered by + """A list of files built by on exploring the filesystem and filtered by applying various patterns to what we find there. Instance attributes: @@ -32,8 +31,7 @@ class FileList: def set_allfiles(self, allfiles: Iterable[str]) -> None: ... def findall(self, dir: str = ".") -> None: ... def debug_print(self, msg: str) -> None: - """ - Print 'msg' to stdout if the global DEBUG (taken from the + """Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true. """ @@ -46,8 +44,7 @@ class FileList: def include_pattern( self, pattern: str, anchor: bool | Literal[0, 1] = 1, prefix: str | None = None, is_regex: Literal[0, False] = 0 ) -> bool: - """ - Select strings (presumably filenames) from 'self.files' that + """Select strings (presumably filenames) from 'self.files' that match 'pattern', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the 'fnmatch' module: '*' and '?' match non-special characters, where "special" is platform- @@ -86,8 +83,7 @@ class FileList: def exclude_pattern( self, pattern: str, anchor: bool | Literal[0, 1] = 1, prefix: str | None = None, is_regex: Literal[0, False] = 0 ) -> bool: - """ - Remove strings (presumably filenames) from 'files' that match + """Remove strings (presumably filenames) from 'files' that match 'pattern'. Other parameters are the same as for 'include_pattern()', above. The list 'self.files' is modified in place. @@ -106,14 +102,12 @@ class FileList: ) -> bool: ... def findall(dir: str = ".") -> list[str]: - """ - Find all files under 'dir' and return the list of full filenames. + """Find all files under 'dir' and return the list of full filenames. Unless dir is '.', return full filenames with dir prepended. """ def glob_to_re(pattern: str) -> str: - """ - Translate a shell-like glob pattern to a regular expression; return + """Translate a shell-like glob pattern to a regular expression; return a string containing the regex. Differs from 'fnmatch.translate()' in that '*' does not match "special characters" (which are platform-specific). @@ -123,8 +117,7 @@ def glob_to_re(pattern: str) -> str: def translate_pattern( pattern: str, anchor: bool | Literal[0, 1] = 1, prefix: str | None = None, is_regex: Literal[False, 0] = 0 ) -> Pattern[str]: - """ - Translate a shell-like wildcard pattern to a compiled regular + """Translate a shell-like wildcard pattern to a compiled regular expression. Return the compiled regex. If 'is_regex' true, then 'pattern' is directly compiled to a regex (if it's a string) or just returned as-is (assumes it's a regex object). diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/msvccompiler.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/msvccompiler.pyi index e1907bb759..65ed9db167 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/msvccompiler.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/msvccompiler.pyi @@ -8,7 +8,6 @@ for the Microsoft Visual Studio. from distutils.ccompiler import CCompiler class MSVCCompiler(CCompiler): - """ - Concrete class that implements an interface to Microsoft Visual C++, + """Concrete class that implements an interface to Microsoft Visual C++, as defined by the CCompiler abstract class. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/spawn.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/spawn.pyi index b090901cf1..a1062e1955 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/spawn.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/spawn.pyi @@ -16,8 +16,7 @@ def spawn( verbose: bool | Literal[0, 1] = 0, dry_run: bool | Literal[0, 1] = 0, ) -> None: - """ - Run another program, specified as a command list 'cmd', in a new process. + """Run another program, specified as a command list 'cmd', in a new process. 'cmd' is just the argument list for the new process, ie. cmd[0] is the program to run and cmd[1:] are the rest of its arguments. @@ -34,8 +33,7 @@ def spawn( """ def find_executable(executable: str, path: str | None = None) -> str | None: - """ - Tries to find 'executable' in the directories listed in 'path'. + """Tries to find 'executable' in the directories listed in 'path'. A string listing directories separated by 'os.pathsep'; defaults to os.environ['PATH']. Returns the complete filename or None if not found. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/sysconfig.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/sysconfig.pyi index fefb6d94a2..8ac3ecaec6 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/sysconfig.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/sysconfig.pyi @@ -24,8 +24,7 @@ project_base: Final[str] python_build: Final[bool] def expand_makefile_vars(s: str, vars: Mapping[str, str]) -> str: - """ - Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in + """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in 'string' according to 'vars' (a dictionary mapping variable names to values). Variables not present in 'vars' are silently expanded to the empty string. The variable values in 'vars' should not contain further @@ -36,8 +35,7 @@ def expand_makefile_vars(s: str, vars: Mapping[str, str]) -> str: @overload @deprecated("SO is deprecated, use EXT_SUFFIX. Support is removed in Python 3.11") def get_config_var(name: Literal["SO"]) -> int | str | None: - """ - Return the value of a single variable using the dictionary returned by + """Return the value of a single variable using the dictionary returned by 'get_config_vars()'. Equivalent to get_config_vars().get(name) @@ -47,8 +45,7 @@ def get_config_var(name: Literal["SO"]) -> int | str | None: def get_config_var(name: str) -> int | str | None: ... @overload def get_config_vars() -> dict[str, str | int]: - """ - With no arguments, return a dictionary of all configuration + """With no arguments, return a dictionary of all configuration variables relevant for the current platform. On Unix, this means every variable defined in Python's installed Makefile; @@ -61,18 +58,13 @@ def get_config_vars() -> dict[str, str | int]: @overload def get_config_vars(arg: str, /, *args: str) -> list[str | int]: ... def get_config_h_filename() -> str: - """ - Return the path of pyconfig.h. - """ + """Return the path of pyconfig.h.""" def get_makefile_filename() -> str: - """ - Return the path of the Makefile. - """ + """Return the path of the Makefile.""" def get_python_inc(plat_specific: bool | Literal[0, 1] = 0, prefix: str | None = None) -> str: - """ - Return the directory containing installed Python header files. + """Return the directory containing installed Python header files. If 'plat_specific' is false (the default), this is the path to the non-platform-specific header files, i.e. Python.h and so on; @@ -86,8 +78,7 @@ def get_python_inc(plat_specific: bool | Literal[0, 1] = 0, prefix: str | None = def get_python_lib( plat_specific: bool | Literal[0, 1] = 0, standard_lib: bool | Literal[0, 1] = 0, prefix: str | None = None ) -> str: - """ - Return the directory containing the Python library (standard or + """Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing @@ -102,8 +93,7 @@ def get_python_lib( """ def customize_compiler(compiler: CCompiler) -> None: - """ - Do any platform-specific customization of a CCompiler instance. + """Do any platform-specific customization of a CCompiler instance. Mainly needed on Unix, so we can plug in the information that varies across Unices and is stored in Python's Makefile. @@ -111,8 +101,7 @@ def customize_compiler(compiler: CCompiler) -> None: if sys.version_info < (3, 10): def get_python_version() -> str: - """ - Return a string containing the major and minor Python version, + """Return a string containing the major and minor Python version, leaving off the patchlevel. Sample return values could be '1.5' or '2.2'. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/text_file.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/text_file.pyi index 7fdd1ff513..8e49a9f6ba 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/text_file.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/text_file.pyi @@ -9,8 +9,7 @@ lines, and joining lines with backslashes. from typing import IO, Literal class TextFile: - """ - Provides a file-like object that takes care of all the things you + """Provides a file-like object that takes care of all the things you commonly want to do when processing a text file that has some line-by-line syntax: strip comments (as long as "#" is your comment character), skip blank lines, join adjacent lines by @@ -81,28 +80,24 @@ class TextFile: join_lines: bool | Literal[0, 1] = ..., collapse_join: bool | Literal[0, 1] = ..., ) -> None: - """ - Construct a new TextFile object. At least one of 'filename' + """Construct a new TextFile object. At least one of 'filename' (a string) and 'file' (a file-like object) must be supplied. They keyword argument options are described above and affect the values returned by 'readline()'. """ def open(self, filename: str) -> None: - """ - Open a new file named 'filename'. This overrides both the + """Open a new file named 'filename'. This overrides both the 'filename' and 'file' arguments to the constructor. """ def close(self) -> None: - """ - Close the current file and forget everything we know about it + """Close the current file and forget everything we know about it (filename, current line number). """ def warn(self, msg: str, line: list[int] | tuple[int, int] | int | None = None) -> None: - """ - Print (to stderr) a warning message tied to the current logical + """Print (to stderr) a warning message tied to the current logical line in the current file. If the current logical line in the file spans multiple physical lines, the warning refers to the whole range, eg. "lines 3-5". If 'line' supplied, it overrides @@ -112,8 +107,7 @@ class TextFile: """ def readline(self) -> str | None: - """ - Read and return a single logical line from the current file (or + """Read and return a single logical line from the current file (or from an internal buffer if lines have previously been "unread" with 'unreadline()'). If the 'join_lines' option is true, this may involve reading multiple physical lines concatenated into a @@ -125,14 +119,12 @@ class TextFile: """ def readlines(self) -> list[str]: - """ - Read and return the list of all logical lines remaining in the + """Read and return the list of all logical lines remaining in the current file. """ def unreadline(self, line: str) -> str: - """ - Push 'line' (a string) onto an internal buffer that will be + """Push 'line' (a string) onto an internal buffer that will be checked by future 'readline()' calls. Handy for implementing a parser with line-at-a-time lookahead. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/util.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/util.pyi index e9942a7247..9f464257e7 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/util.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/util.pyi @@ -13,8 +13,7 @@ from typing_extensions import TypeVarTuple, Unpack _Ts = TypeVarTuple("_Ts") def get_host_platform() -> str: - """ - Return a string that identifies the current platform. This is used mainly to + """Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by 'os.uname()'), although the exact information @@ -35,8 +34,7 @@ def get_host_platform() -> str: def get_platform() -> str: ... def convert_path(pathname: str) -> str: - """ - Return 'pathname' as a name that will work on the native filesystem, + """Return 'pathname' as a name that will work on the native filesystem, i.e. split it on '/' and put it back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the local @@ -46,16 +44,14 @@ def convert_path(pathname: str) -> str: """ def change_root(new_root: StrPath, pathname: StrPath) -> str: - """ - Return 'pathname' with 'new_root' prepended. If 'pathname' is + """Return 'pathname' with 'new_root' prepended. If 'pathname' is relative, this is equivalent to "os.path.join(new_root,pathname)". Otherwise, it requires making 'pathname' relative and then joining the two, which is tricky on DOS/Windows and Mac OS. """ def check_environ() -> None: - """ - Ensure that 'os.environ' has all the environment variables we + """Ensure that 'os.environ' has all the environment variables we guarantee that users can use in config files, command-line options, etc. Currently this includes: HOME - user's home directory (Unix only) @@ -64,8 +60,7 @@ def check_environ() -> None: """ def subst_vars(s: str, local_vars: Mapping[str, str]) -> None: - """ - Perform shell/Perl-style variable substitution on 'string'. Every + """Perform shell/Perl-style variable substitution on 'string'. Every occurrence of '$' followed by a name is considered a variable, and variable is substituted by the value found in the 'local_vars' dictionary, or in 'os.environ' if it's not in 'local_vars'. @@ -75,8 +70,7 @@ def subst_vars(s: str, local_vars: Mapping[str, str]) -> None: """ def split_quoted(s: str) -> list[str]: - """ - Split a string up according to Unix shell-like rules for quotes and + """Split a string up according to Unix shell-like rules for quotes and backslashes. In short: words are delimited by spaces, as long as those spaces are not escaped by a backslash, or inside a quoted string. Single and double quotes are equivalent, and the quote characters can @@ -93,8 +87,7 @@ def execute( verbose: bool | Literal[0, 1] = 0, dry_run: bool | Literal[0, 1] = 0, ) -> None: - """ - Perform some action that affects the outside world (eg. by + """Perform some action that affects the outside world (eg. by writing to the filesystem). Such actions are special because they are disabled by the 'dry_run' flag. This method takes care of all that bureaucracy for you; all you have to do is supply the @@ -104,8 +97,7 @@ def execute( """ def strtobool(val: str) -> Literal[0, 1]: - """ - Convert a string representation of truth to true (1) or false (0). + """Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if @@ -122,8 +114,7 @@ def byte_compile( dry_run: bool | Literal[0, 1] = 0, direct: bool | None = None, ) -> None: - """ - Byte-compile a collection of Python source files to .pyc + """Byte-compile a collection of Python source files to .pyc files in a __pycache__ subdirectory. 'py_files' is a list of files to compile; any files that don't end in ".py" are silently skipped. 'optimize' must be one of the following: @@ -153,8 +144,7 @@ def byte_compile( """ def rfc822_escape(header: str) -> str: - """ - Return a version of the string escaped for inclusion in an + """Return a version of the string escaped for inclusion in an RFC-822 header, by ensuring there are 8 spaces space after each newline. """ @@ -164,8 +154,7 @@ def run_2to3( options: Mapping[str, Any] | None = None, explicit: Unused = None, ) -> None: - """ - Invoke 2to3 on a list of Python files. + """Invoke 2to3 on a list of Python files. The files should all come from the build area, as the modification is done in-place. To reduce the build time, only files modified since the last invocation of this @@ -180,16 +169,14 @@ def copydir_run_2to3( options: Mapping[str, Any] | None = None, explicit: Container[str] | None = None, ) -> list[str]: - """ - Recursively copy a directory, only copying new and changed files, + """Recursively copy a directory, only copying new and changed files, running run_2to3 over all newly copied Python modules afterward. If you give a template string, it's parsed like a MANIFEST.in. """ class Mixin2to3: - """ - Mixin class for commands that run 2to3. + """Mixin class for commands that run 2to3. To configure 2to3, setup scripts may either change the class variables, or inherit from individual commands to override how 2to3 is invoked. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/version.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/version.pyi index 41e91756a3..bbcca8c7a6 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/distutils/version.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/distutils/version.pyi @@ -23,8 +23,7 @@ from re import Pattern from typing_extensions import Self class Version: - """ - Abstract base class for version numbering classes. Just provides + """Abstract base class for version numbering classes. Just provides constructor (__init__) and reproducer (__repr__), because those seem to be the same for all version numbering classes; and route rich comparisons to _cmp. @@ -45,8 +44,7 @@ class Version: def _cmp(self, other: Self | str) -> bool: ... class StrictVersion(Version): - """ - Version numbering for anal retentives and software idealists. + """Version numbering for anal retentives and software idealists. Implements the standard interface for version number classes as described above. A version number consists of two or three dot-separated numeric components, with an optional "pre-release" tag @@ -90,8 +88,7 @@ class StrictVersion(Version): def _cmp(self, other: Self | str) -> bool: ... class LooseVersion(Version): - """ - Version numbering for anarchists and software realists. + """Version numbering for anarchists and software realists. Implements the standard interface for version number classes as described above. A version number consists of a series of numbers, separated by either periods or strings of letters. When comparing diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/doctest.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/doctest.pyi index 4dc2ec1da7..c542a9d2e8 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/doctest.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/doctest.pyi @@ -94,9 +94,7 @@ if sys.version_info >= (3, 13): else: class TestResults(NamedTuple): - """ - TestResults(failed, attempted) - """ + """TestResults(failed, attempted)""" failed: int attempted: int @@ -126,8 +124,7 @@ BLANKLINE_MARKER: str ELLIPSIS_MARKER: str class Example: - """ - A single doctest example, consisting of source code and expected + """A single doctest example, consisting of source code and expected output. `Example` defines the following attributes: - source: A single Python statement, always ending with a newline. @@ -180,8 +177,7 @@ class Example: def __eq__(self, other: object) -> bool: ... class DocTest: - """ - A collection of doctest examples that should be run in a single + """A collection of doctest examples that should be run in a single namespace. Each `DocTest` defines the following attributes: - examples: the list of examples. @@ -219,8 +215,7 @@ class DocTest: lineno: int | None, docstring: str | None, ) -> None: - """ - Create a new DocTest containing the given examples. The + """Create a new DocTest containing the given examples. The DocTest's globals are initialized with a copy of `globs`. """ @@ -229,13 +224,10 @@ class DocTest: def __eq__(self, other: object) -> bool: ... class DocTestParser: - """ - A class used to parse strings containing doctest examples. - """ + """A class used to parse strings containing doctest examples.""" def parse(self, string: str, name: str = "") -> list[str | Example]: - """ - Divide the given string into examples and intervening text, + """Divide the given string into examples and intervening text, and return them as a list of alternating Examples and strings. Line numbers for the Examples are 0-based. The optional argument `name` is a name identifying this string, and is only @@ -243,8 +235,7 @@ class DocTestParser: """ def get_doctest(self, string: str, globs: dict[str, Any], name: str, filename: str | None, lineno: int | None) -> DocTest: - """ - Extract all doctest examples from the given string, and + """Extract all doctest examples from the given string, and collect them into a `DocTest` object. `globs`, `name`, `filename`, and `lineno` are attributes for @@ -253,8 +244,7 @@ class DocTestParser: """ def get_examples(self, string: str, name: str = "") -> list[Example]: - """ - Extract all doctest examples from the given string, and return + """Extract all doctest examples from the given string, and return them as a list of `Example` objects. Line numbers are 0-based, because it's most common in doctests that nothing interesting appears on the same line as opening triple-quote, @@ -265,8 +255,7 @@ class DocTestParser: """ class DocTestFinder: - """ - A class used to extract the DocTests that are relevant to a given + """A class used to extract the DocTests that are relevant to a given object, from its docstring and the docstrings of its contained objects. Doctests can currently be extracted from the following object types: modules, functions, classes, methods, staticmethods, @@ -276,8 +265,7 @@ class DocTestFinder: def __init__( self, verbose: bool = False, parser: DocTestParser = ..., recurse: bool = True, exclude_empty: bool = True ) -> None: - """ - Create a new doctest finder. + """Create a new doctest finder. The optional argument `parser` specifies a class or function that should be used to create new DocTest objects (or @@ -300,8 +288,7 @@ class DocTestFinder: globs: dict[str, Any] | None = None, extraglobs: dict[str, Any] | None = None, ) -> list[DocTest]: - """ - Return a list of the DocTests that are defined by the given + """Return a list of the DocTests that are defined by the given object's docstring, or by any of its contained objects' docstrings. @@ -337,8 +324,7 @@ class DocTestFinder: _Out: TypeAlias = Callable[[str], object] class DocTestRunner: - """ - A class used to run DocTest test cases, and accumulate statistics. + """A class used to run DocTest test cases, and accumulate statistics. The `run` method is used to process a single DocTest case. It returns a TestResults instance. @@ -408,8 +394,7 @@ class DocTestRunner: skips: int test: DocTest def __init__(self, checker: OutputChecker | None = None, verbose: bool | None = None, optionflags: int = 0) -> None: - """ - Create a new test runner. + """Create a new test runner. Optional keyword arg `checker` is the `OutputChecker` that should be used to compare the expected outputs and actual @@ -426,32 +411,25 @@ class DocTestRunner: """ def report_start(self, out: _Out, test: DocTest, example: Example) -> None: - """ - Report that the test runner is about to process the given + """Report that the test runner is about to process the given example. (Only displays a message if verbose=True) """ def report_success(self, out: _Out, test: DocTest, example: Example, got: str) -> None: - """ - Report that the given example ran successfully. (Only + """Report that the given example ran successfully. (Only displays a message if verbose=True) """ def report_failure(self, out: _Out, test: DocTest, example: Example, got: str) -> None: - """ - Report that the given example failed. - """ + """Report that the given example failed.""" def report_unexpected_exception(self, out: _Out, test: DocTest, example: Example, exc_info: ExcInfo) -> None: - """ - Report that the given example raised an unexpected exception. - """ + """Report that the given example raised an unexpected exception.""" def run( self, test: DocTest, compileflags: int | None = None, out: _Out | None = None, clear_globs: bool = True ) -> TestResults: - """ - Run the examples in `test`, and display the results using the + """Run the examples in `test`, and display the results using the writer function `out`. The examples are run in the namespace `test.globs`. If @@ -471,8 +449,7 @@ class DocTestRunner: """ def summarize(self, verbose: bool | None = None) -> TestResults: - """ - Print a summary of all the test cases that have been run by + """Print a summary of all the test cases that have been run by this DocTestRunner, and return a TestResults instance. The optional `verbose` argument controls how detailed the @@ -483,8 +460,7 @@ class DocTestRunner: def merge(self, other: DocTestRunner) -> None: ... class OutputChecker: - """ - A class used to check whether the actual output from a doctest + """A class used to check whether the actual output from a doctest example matches the expected output. `OutputChecker` defines two methods: `check_output`, which compares a given pair of outputs, and returns true if they match; and `output_difference`, which @@ -492,8 +468,7 @@ class OutputChecker: """ def check_output(self, want: str, got: str, optionflags: int) -> bool: - """ - Return True iff the actual output from an example (`got`) + """Return True iff the actual output from an example (`got`) matches the expected output (`want`). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, @@ -503,16 +478,14 @@ class OutputChecker: """ def output_difference(self, example: Example, got: str, optionflags: int) -> str: - """ - Return a string describing the differences between the + """Return a string describing the differences between the expected output for a given example (`example`) and the actual output (`got`). `optionflags` is the set of option flags used to compare `want` and `got`. """ class DocTestFailure(Exception): - """ - A DocTest example has failed in debugging mode. + """A DocTest example has failed in debugging mode. The exception instance has variables: @@ -529,8 +502,7 @@ class DocTestFailure(Exception): def __init__(self, test: DocTest, example: Example, got: str) -> None: ... class UnexpectedException(Exception): - """ - A DocTest example has encountered an unexpected exception + """A DocTest example has encountered an unexpected exception The exception instance has variables: @@ -547,8 +519,7 @@ class UnexpectedException(Exception): def __init__(self, test: DocTest, example: Example, exc_info: ExcInfo) -> None: ... class DebugRunner(DocTestRunner): - """ - Run doc tests but raise an exception as soon as there is a failure. + """Run doc tests but raise an exception as soon as there is a failure. If an unexpected exception occurs, an UnexpectedException is raised. It contains the test, the example, and the original exception: @@ -650,8 +621,7 @@ def testmod( raise_on_error: bool = False, exclude_empty: bool = False, ) -> TestResults: - """ - m=None, name=None, globs=None, verbose=None, report=True, + """m=None, name=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False @@ -729,8 +699,7 @@ def testfile( parser: DocTestParser = ..., encoding: str | None = None, ) -> TestResults: - """ - Test examples in the given file. Return (#failures, #tests). + """Test examples in the given file. Return (#failures, #tests). Optional keyword arg "module_relative" specifies how filenames should be interpreted: @@ -814,8 +783,7 @@ def run_docstring_examples( compileflags: int | None = None, optionflags: int = 0, ) -> None: - """ - Test examples in the given object's docstring (`f`), using `globs` + """Test examples in the given object's docstring (`f`), using `globs` as globals. Optional argument `name` is used in failure messages. If the optional argument `verbose` is true, then generate output even if there are no failures. @@ -831,8 +799,7 @@ def run_docstring_examples( """ def set_unittest_reportflags(flags: int) -> int: - """ - Sets the unittest option flags. + """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: @@ -886,8 +853,7 @@ def DocTestSuite( test_finder: DocTestFinder | None = None, **options: Any, ) -> _DocTestSuite: - """ - Convert doctest tests for a module to a unittest test suite. + """Convert doctest tests for a module to a unittest test suite. This converts each documentation string in a module that contains doctest tests to a unittest test case. If any of the @@ -933,8 +899,7 @@ def DocFileTest( **options: Any, ) -> DocFileCase: ... def DocFileSuite(*paths: str, **kw: Any) -> _DocTestSuite: - """ - A unittest suite for one or more doctest files. + """A unittest suite for one or more doctest files. The path to each doctest file is given as a string; the interpretation of that string depends on the keyword argument @@ -991,8 +956,7 @@ def DocFileSuite(*paths: str, **kw: Any) -> _DocTestSuite: """ def script_from_examples(s: str) -> str: - """ - Extract script from text with examples. + """Extract script from text with examples. Converts text with examples to a Python script. Example input is converted to regular code. Example output and all other words @@ -1051,8 +1015,7 @@ def script_from_examples(s: str) -> str: """ def testsource(module: None | str | types.ModuleType, name: str) -> str: - """ - Extract the test sources from a doctest docstring as a script. + """Extract the test sources from a doctest docstring as a script. Provide the module (or dotted name of the module) containing the test to be debugged and the name (within the module) of the object @@ -1060,18 +1023,13 @@ def testsource(module: None | str | types.ModuleType, name: str) -> str: """ def debug_src(src: str, pm: bool = False, globs: dict[str, Any] | None = None) -> None: - """ - Debug a single doctest docstring, in argument `src` - """ + """Debug a single doctest docstring, in argument `src`""" def debug_script(src: str, pm: bool = False, globs: dict[str, Any] | None = None) -> None: - """ - Debug a test script. `src` is the script, as a string. - """ + """Debug a test script. `src` is the script, as a string.""" def debug(module: None | str | types.ModuleType, name: str, pm: bool = False) -> None: - """ - Debug a single doctest docstring. + """Debug a single doctest docstring. Provide the module (or dotted name of the module) containing the test to be debugged and the name (within the module) of the object diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/__init__.pyi index ffd48bc839..28009c67e6 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/__init__.pyi @@ -38,8 +38,7 @@ _ParamsType: TypeAlias = str | None | tuple[str, str | None, str] # noqa: Y047 @overload def message_from_string(s: str) -> Message: - """ - Parse a string into a Message object model. + """Parse a string into a Message object model. Optional _class and strict are passed to the Parser constructor. """ @@ -50,8 +49,7 @@ def message_from_string(s: str, _class: Callable[[], _MessageT]) -> _MessageT: . def message_from_string(s: str, _class: Callable[[], _MessageT] = ..., *, policy: Policy[_MessageT]) -> _MessageT: ... @overload def message_from_bytes(s: bytes | bytearray) -> Message: - """ - Parse a bytes string into a Message object model. + """Parse a bytes string into a Message object model. Optional _class and strict are passed to the Parser constructor. """ @@ -64,8 +62,7 @@ def message_from_bytes( ) -> _MessageT: ... @overload def message_from_file(fp: IO[str]) -> Message: - """ - Read a file and parse its contents into a Message object model. + """Read a file and parse its contents into a Message object model. Optional _class and strict are passed to the Parser constructor. """ @@ -76,8 +73,7 @@ def message_from_file(fp: IO[str], _class: Callable[[], _MessageT]) -> _MessageT def message_from_file(fp: IO[str], _class: Callable[[], _MessageT] = ..., *, policy: Policy[_MessageT]) -> _MessageT: ... @overload def message_from_binary_file(fp: IO[bytes]) -> Message: - """ - Read a binary file and parse its contents into a Message object model. + """Read a binary file and parse its contents into a Message object model. Optional _class and strict are passed to the Parser constructor. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/_header_value_parser.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/_header_value_parser.pyi index a73db420ad..64d45af8e1 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/_header_value_parser.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/_header_value_parser.pyi @@ -93,9 +93,7 @@ SPECIALSNL: Final[set[str]] # Added in Python 3.9.23, 3.10.17, 3.11.12, 3.12.9, 3.13.2 def make_quoted_pairs(value: Any) -> str: - """ - Escape dquote and backslash for use within a quoted-string. - """ + """Escape dquote and backslash for use within a quoted-string.""" def quote_string(value: Any) -> str: ... @@ -114,9 +112,7 @@ class TokenList(list[TokenList | Terminal]): def startswith_fws(self) -> bool: ... @property def as_ew_allowed(self) -> bool: - """ - True if all top level tokens of this part may be RFC2047 encoded. - """ + """True if all top level tokens of this part may be RFC2047 encoded.""" @property def comments(self) -> list[str]: ... @@ -420,17 +416,14 @@ class ValueTerminal(Terminal): class EWWhiteSpaceTerminal(WhiteSpaceTerminal): ... class _InvalidEwError(HeaderParseError): - """ - Invalid encoded word found while parsing headers. - """ + """Invalid encoded word found while parsing headers.""" DOT: Final[ValueTerminal] ListSeparator: Final[ValueTerminal] RouteComponentMarker: Final[ValueTerminal] def get_fws(value: str) -> tuple[WhiteSpaceTerminal, str]: - """ - FWS = 1*WSP + """FWS = 1*WSP This isn't the RFC definition. We're using fws to represent tokens where folding can be done, but when we are parsing the *un*folding has already @@ -438,13 +431,10 @@ def get_fws(value: str) -> tuple[WhiteSpaceTerminal, str]: """ def get_encoded_word(value: str, terminal_type: str = "vtext") -> tuple[EncodedWord, str]: - """ - encoded-word = "=?" charset "?" encoding "?" encoded-text "?=" - """ + """encoded-word = "=?" charset "?" encoding "?" encoded-text "?=" """ def get_unstructured(value: str) -> UnstructuredTokenList: - """ - unstructured = (*([FWS] vchar) *WSP) / obs-unstruct + """unstructured = (*([FWS] vchar) *WSP) / obs-unstruct obs-unstruct = *((*LF *CR *(obs-utext) *LF *CR)) / FWS) obs-utext = %d0 / obs-NO-WS-CTL / LF / CR @@ -463,8 +453,7 @@ def get_unstructured(value: str) -> UnstructuredTokenList: """ def get_qp_ctext(value: str) -> tuple[WhiteSpaceTerminal, str]: - """ - ctext = + """ctext = This is not the RFC ctext, since we are handling nested comments in comment and unquoting quoted-pairs here. We allow anything except the '()' @@ -476,8 +465,7 @@ def get_qp_ctext(value: str) -> tuple[WhiteSpaceTerminal, str]: """ def get_qcontent(value: str) -> tuple[ValueTerminal, str]: - """ - qcontent = qtext / quoted-pair + """qcontent = qtext / quoted-pair We allow anything except the DQUOTE character, but if we find any ASCII other than the RFC defined printable ASCII, a NonPrintableDefect is @@ -487,16 +475,14 @@ def get_qcontent(value: str) -> tuple[ValueTerminal, str]: """ def get_atext(value: str) -> tuple[ValueTerminal, str]: - """ - atext = + """atext = We allow any non-ATOM_ENDS in atext, but add an InvalidATextDefect to the token's defects list if we find non-atext characters. """ def get_bare_quoted_string(value: str) -> tuple[BareQuotedString, str]: - """ - bare-quoted-string = DQUOTE *([FWS] qcontent) [FWS] DQUOTE + """bare-quoted-string = DQUOTE *([FWS] qcontent) [FWS] DQUOTE A quoted-string without the leading or trailing white space. Its value is the text between the quote marks, with whitespace @@ -504,21 +490,17 @@ def get_bare_quoted_string(value: str) -> tuple[BareQuotedString, str]: """ def get_comment(value: str) -> tuple[Comment, str]: - """ - comment = "(" *([FWS] ccontent) [FWS] ")" + """comment = "(" *([FWS] ccontent) [FWS] ")" ccontent = ctext / quoted-pair / comment We handle nested comments here, and quoted-pair in our qp-ctext routine. """ def get_cfws(value: str) -> tuple[CFWSList, str]: - """ - CFWS = (1*([FWS] comment) [FWS]) / FWS - """ + """CFWS = (1*([FWS] comment) [FWS]) / FWS""" def get_quoted_string(value: str) -> tuple[QuotedString, str]: - """ - quoted-string = [CFWS] [CFWS] + """quoted-string = [CFWS] [CFWS] 'bare-quoted-string' is an intermediate class defined by this parser and not by the RFC grammar. It is the quoted string @@ -526,28 +508,23 @@ def get_quoted_string(value: str) -> tuple[QuotedString, str]: """ def get_atom(value: str) -> tuple[Atom, str]: - """ - atom = [CFWS] 1*atext [CFWS] + """atom = [CFWS] 1*atext [CFWS] An atom could be an rfc2047 encoded word. """ def get_dot_atom_text(value: str) -> tuple[DotAtomText, str]: - """ - dot-text = 1*atext *("." 1*atext) - """ + """dot-text = 1*atext *("." 1*atext)""" def get_dot_atom(value: str) -> tuple[DotAtom, str]: - """ - dot-atom = [CFWS] dot-atom-text [CFWS] + """dot-atom = [CFWS] dot-atom-text [CFWS] Any place we can have a dot atom, we could instead have an rfc2047 encoded word. """ def get_word(value: str) -> tuple[Any, str]: - """ - word = atom / quoted-string + """word = atom / quoted-string Either atom or quoted-string may start with CFWS. We have to peel off this CFWS first to determine which type of word to parse. Afterward we splice @@ -563,8 +540,7 @@ def get_word(value: str) -> tuple[Any, str]: """ def get_phrase(value: str) -> tuple[Phrase, str]: - """ - phrase = 1*word / obs-phrase + """phrase = 1*word / obs-phrase obs-phrase = word *(word / "." / CFWS) This means a phrase can be a sequence of words, periods, and CFWS in any @@ -576,18 +552,13 @@ def get_phrase(value: str) -> tuple[Phrase, str]: """ def get_local_part(value: str) -> tuple[LocalPart, str]: - """ - local-part = dot-atom / quoted-string / obs-local-part - """ + """local-part = dot-atom / quoted-string / obs-local-part""" def get_obs_local_part(value: str) -> tuple[ObsLocalPart, str]: - """ - obs-local-part = word *("." word) - """ + """obs-local-part = word *("." word)""" def get_dtext(value: str) -> tuple[ValueTerminal, str]: - """ - dtext = / obs-dtext + """dtext = / obs-dtext obs-dtext = obs-NO-WS-CTL / quoted-pair We allow anything except the excluded characters, but if we find any @@ -599,24 +570,18 @@ def get_dtext(value: str) -> tuple[ValueTerminal, str]: """ def get_domain_literal(value: str) -> tuple[DomainLiteral, str]: - """ - domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS] - """ + """domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]""" def get_domain(value: str) -> tuple[Domain, str]: - """ - domain = dot-atom / domain-literal / obs-domain + """domain = dot-atom / domain-literal / obs-domain obs-domain = atom *("." atom)) """ def get_addr_spec(value: str) -> tuple[AddrSpec, str]: - """ - addr-spec = local-part "@" domain - """ + """addr-spec = local-part "@" domain""" def get_obs_route(value: str) -> tuple[ObsRoute, str]: - """ - obs-route = obs-domain-list ":" + """obs-route = obs-domain-list ":" obs-domain-list = *(CFWS / ",") "@" domain *("," [CFWS] ["@" domain]) Returns an obs-route token with the appropriate sub-tokens (that is, @@ -624,14 +589,12 @@ def get_obs_route(value: str) -> tuple[ObsRoute, str]: """ def get_angle_addr(value: str) -> tuple[AngleAddr, str]: - """ - angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr + """angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS] """ def get_display_name(value: str) -> tuple[DisplayName, str]: - """ - display-name = phrase + """display-name = phrase Because this is simply a name-rule, we don't return a display-name token containing a phrase, but rather a display-name token with @@ -639,26 +602,20 @@ def get_display_name(value: str) -> tuple[DisplayName, str]: """ def get_name_addr(value: str) -> tuple[NameAddr, str]: - """ - name-addr = [display-name] angle-addr - """ + """name-addr = [display-name] angle-addr""" def get_mailbox(value: str) -> tuple[Mailbox, str]: - """ - mailbox = name-addr / addr-spec - """ + """mailbox = name-addr / addr-spec""" def get_invalid_mailbox(value: str, endchars: str) -> tuple[InvalidMailbox, str]: - """ - Read everything up to one of the chars in endchars. + """Read everything up to one of the chars in endchars. This is outside the formal grammar. The InvalidMailbox TokenList that is returned acts like a Mailbox, but the data attributes are None. """ def get_mailbox_list(value: str) -> tuple[MailboxList, str]: - """ - mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list + """mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS]) For this routine we go outside the formal grammar in order to improve error @@ -670,19 +627,15 @@ def get_mailbox_list(value: str) -> tuple[MailboxList, str]: """ def get_group_list(value: str) -> tuple[GroupList, str]: - """ - group-list = mailbox-list / CFWS / obs-group-list + """group-list = mailbox-list / CFWS / obs-group-list obs-group-list = 1*([CFWS] ",") [CFWS] """ def get_group(value: str) -> tuple[Group, str]: - """ - group = display-name ":" [group-list] ";" [CFWS] - """ + """group = display-name ":" [group-list] ";" [CFWS]""" def get_address(value: str) -> tuple[Address, str]: - """ - address = mailbox / group + """address = mailbox / group Note that counter-intuitively, an address can be either a single address or a list of addresses (a group). This is why the returned Address object has @@ -692,8 +645,7 @@ def get_address(value: str) -> tuple[Address, str]: """ def get_address_list(value: str) -> tuple[AddressList, str]: - """ - address_list = (address *("," address)) / obs-addr-list + """address_list = (address *("," address)) / obs-addr-list obs-addr-list = *([CFWS] ",") address *("," [address / CFWS]) We depart from the formal grammar here by continuing to parse until the end @@ -703,39 +655,30 @@ def get_address_list(value: str) -> tuple[AddressList, str]: """ def get_no_fold_literal(value: str) -> tuple[NoFoldLiteral, str]: - """ - no-fold-literal = "[" *dtext "]" - """ + """no-fold-literal = "[" *dtext "]" """ def get_msg_id(value: str) -> tuple[MsgID, str]: - """ - msg-id = [CFWS] "<" id-left '@' id-right ">" [CFWS] + """msg-id = [CFWS] "<" id-left '@' id-right ">" [CFWS] id-left = dot-atom-text / obs-id-left id-right = dot-atom-text / no-fold-literal / obs-id-right no-fold-literal = "[" *dtext "]" """ def parse_message_id(value: str) -> MessageID: - """ - message-id = "Message-ID:" msg-id CRLF - """ + """message-id = "Message-ID:" msg-id CRLF""" def parse_mime_version(value: str) -> MIMEVersion: - """ - mime-version = [CFWS] 1*digit [CFWS] "." [CFWS] 1*digit [CFWS] - """ + """mime-version = [CFWS] 1*digit [CFWS] "." [CFWS] 1*digit [CFWS]""" def get_invalid_parameter(value: str) -> tuple[InvalidParameter, str]: - """ - Read everything up to the next ';'. + """Read everything up to the next ';'. This is outside the formal grammar. The InvalidParameter TokenList that is returned acts like a Parameter, but the data attributes are None. """ def get_ttext(value: str) -> tuple[ValueTerminal, str]: - """ - ttext = + """ttext = We allow any non-TOKEN_ENDS in ttext, but add defects to the token's defects list if we find non-ttext characters. We also register defects for @@ -744,8 +687,7 @@ def get_ttext(value: str) -> tuple[ValueTerminal, str]: """ def get_token(value: str) -> tuple[Token, str]: - """ - token = [CFWS] 1*ttext [CFWS] + """token = [CFWS] 1*ttext [CFWS] The RFC equivalent of ttext is any US-ASCII chars except space, ctls, or tspecials. We also exclude tabs even though the RFC doesn't. @@ -754,8 +696,7 @@ def get_token(value: str) -> tuple[Token, str]: """ def get_attrtext(value: str) -> tuple[ValueTerminal, str]: - """ - attrtext = 1*(any non-ATTRIBUTE_ENDS character) + """attrtext = 1*(any non-ATTRIBUTE_ENDS character) We allow any non-ATTRIBUTE_ENDS in attrtext, but add defects to the token's defects list if we find non-attrtext characters. We also register @@ -764,8 +705,7 @@ def get_attrtext(value: str) -> tuple[ValueTerminal, str]: """ def get_attribute(value: str) -> tuple[Attribute, str]: - """ - [CFWS] 1*attrtext [CFWS] + """[CFWS] 1*attrtext [CFWS] This version of the BNF makes the CFWS explicit, and as usual we use a value terminal for the actual run of characters. The RFC equivalent of @@ -774,8 +714,7 @@ def get_attribute(value: str) -> tuple[Attribute, str]: """ def get_extended_attrtext(value: str) -> tuple[ValueTerminal, str]: - """ - attrtext = 1*(any non-ATTRIBUTE_ENDS character plus '%') + """attrtext = 1*(any non-ATTRIBUTE_ENDS character plus '%') This is a special parsing routine so that we get a value that includes % escapes as a single string (which we decode as a single @@ -783,16 +722,14 @@ def get_extended_attrtext(value: str) -> tuple[ValueTerminal, str]: """ def get_extended_attribute(value: str) -> tuple[Attribute, str]: - """ - [CFWS] 1*extended_attrtext [CFWS] + """[CFWS] 1*extended_attrtext [CFWS] This is like the non-extended version except we allow % characters, so that we can pick up an encoded value as a single string. """ def get_section(value: str) -> tuple[Section, str]: - """ - '*' digits + """'*' digits The formal BNF is more complicated because leading 0s are not allowed. We check for that and add a defect. We also assume no CFWS is allowed between @@ -801,13 +738,10 @@ def get_section(value: str) -> tuple[Section, str]: """ def get_value(value: str) -> tuple[Value, str]: - """ - quoted-string / attribute - """ + """quoted-string / attribute""" def get_parameter(value: str) -> tuple[Parameter, str]: - """ - attribute [section] ["*"] [CFWS] "=" value + """attribute [section] ["*"] [CFWS] "=" value The CFWS is implied by the RFC but not made explicit in the BNF. This simplified form of the BNF from the RFC is made to conform with the RFC BNF @@ -816,8 +750,7 @@ def get_parameter(value: str) -> tuple[Parameter, str]: """ def parse_mime_parameters(value: str) -> MimeParameters: - """ - parameter *( ";" parameter ) + """parameter *( ";" parameter ) That BNF is meant to indicate this routine should only be called after finding and handling the leading ';'. There is no corresponding rule in @@ -830,8 +763,7 @@ def parse_mime_parameters(value: str) -> MimeParameters: """ def parse_content_type_header(value: str) -> ContentType: - """ - maintype "/" subtype *( ";" parameter ) + """maintype "/" subtype *( ";" parameter ) The maintype and substype are tokens. Theoretically they could be checked against the official IANA list + x-token, but we @@ -839,11 +771,7 @@ def parse_content_type_header(value: str) -> ContentType: """ def parse_content_disposition_header(value: str) -> ContentDisposition: - """ - disposition-type *( ";" parameter ) - """ + """disposition-type *( ";" parameter )""" def parse_content_transfer_encoding_header(value: str) -> ContentTransferEncoding: - """ - mechanism - """ + """mechanism""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/_policybase.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/_policybase.pyi index 38d29d1ef9..72dbccd5db 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/_policybase.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/_policybase.pyi @@ -24,8 +24,7 @@ class _MessageFactory(Protocol[_MessageT]): # assume that the __init__ arguments and attributes of _PolicyBase are # the same as those of Policy. class _PolicyBase(Generic[_MessageT_co]): - """ - Policy Object basic framework. + """Policy Object basic framework. This class is useless unless subclassed. A subclass should define class attributes with defaults for any values that are to be @@ -66,8 +65,7 @@ class _PolicyBase(Generic[_MessageT_co]): # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 verify_generated_headers: bool = True, ) -> None: - """ - Create new Policy, possibly overriding some defaults. + """Create new Policy, possibly overriding some defaults. See class docstring for a list of overridable attributes. """ @@ -84,23 +82,20 @@ class _PolicyBase(Generic[_MessageT_co]): # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 verify_generated_headers: bool = ..., ) -> Self: - """ - Return a new instance with specified attributes changed. + """Return a new instance with specified attributes changed. The new instance has the same attribute values as the current object, except for the changes passed in as keyword arguments. """ def __add__(self, other: Policy) -> Self: - """ - Non-default values from right operand override those from left. + """Non-default values from right operand override those from left. The object returned is a new instance of the subclass. """ class Policy(_PolicyBase[_MessageT_co], metaclass=ABCMeta): - """ - Controls for how messages are interpreted and formatted. + """Controls for how messages are interpreted and formatted. Most of the classes and many of the methods in the email package accept Policy objects as parameters. A Policy object contains a set of values and @@ -158,8 +153,7 @@ class Policy(_PolicyBase[_MessageT_co], metaclass=ABCMeta): # Every Message object has a `defects` attribute, so the following # methods will work for any Message object. def handle_defect(self, obj: Message[Any, Any], defect: MessageDefect) -> None: - """ - Based on policy, either raise defect or call register_defect. + """Based on policy, either raise defect or call register_defect. handle_defect(obj, defect) @@ -174,8 +168,7 @@ class Policy(_PolicyBase[_MessageT_co], metaclass=ABCMeta): """ def register_defect(self, obj: Message[Any, Any], defect: MessageDefect) -> None: - """ - Record 'defect' on 'obj'. + """Record 'defect' on 'obj'. Called by handle_defect if raise_on_defect is False. This method is part of the Policy API so that Policy subclasses can implement custom @@ -186,8 +179,7 @@ class Policy(_PolicyBase[_MessageT_co], metaclass=ABCMeta): """ def header_max_count(self, name: str) -> int | None: - """ - Return the maximum allowed number of headers named 'name'. + """Return the maximum allowed number of headers named 'name'. Called when a header is added to a Message object. If the returned value is not 0 or None, and there are already a number of headers with @@ -206,8 +198,7 @@ class Policy(_PolicyBase[_MessageT_co], metaclass=ABCMeta): @abstractmethod def header_source_parse(self, sourcelines: list[str]) -> tuple[str, str]: - """ - Given a list of linesep terminated strings constituting the lines of + """Given a list of linesep terminated strings constituting the lines of a single header, return the (name, value) tuple that should be stored in the model. The input lines should retain their terminating linesep characters. The lines passed in by the email package may contain @@ -216,15 +207,13 @@ class Policy(_PolicyBase[_MessageT_co], metaclass=ABCMeta): @abstractmethod def header_store_parse(self, name: str, value: str) -> tuple[str, str]: - """ - Given the header name and the value provided by the application + """Given the header name and the value provided by the application program, return the (name, value) that should be stored in the model. """ @abstractmethod def header_fetch_parse(self, name: str, value: str) -> str: - """ - Given the header name and the value from the model, return the value + """Given the header name and the value from the model, return the value to be returned to the application program that is requesting that header. The value passed in by the email package may contain surrogateescaped binary data if the lines were parsed by a BytesParser. @@ -233,8 +222,7 @@ class Policy(_PolicyBase[_MessageT_co], metaclass=ABCMeta): @abstractmethod def fold(self, name: str, value: str) -> str: - """ - Given the header name and the value from the model, return a string + """Given the header name and the value from the model, return a string containing linesep characters that implement the folding of the header according to the policy controls. The value passed in by the email package may contain surrogateescaped binary data if the lines were @@ -244,16 +232,14 @@ class Policy(_PolicyBase[_MessageT_co], metaclass=ABCMeta): @abstractmethod def fold_binary(self, name: str, value: str) -> bytes: - """ - Given the header name and the value from the model, return binary + """Given the header name and the value from the model, return binary data containing linesep characters that implement the folding of the header according to the policy controls. The value passed in by the email package may contain surrogateescaped binary data. """ class Compat32(Policy[_MessageT_co]): - """ - Controls for how messages are interpreted and formatted. + """Controls for how messages are interpreted and formatted. Most of the classes and many of the methods in the email package accept Policy objects as parameters. A Policy object contains a set of values and @@ -311,8 +297,7 @@ class Compat32(Policy[_MessageT_co]): """ def header_source_parse(self, sourcelines: list[str]) -> tuple[str, str]: - """ - Given a list of linesep terminated strings constituting the lines of + """Given a list of linesep terminated strings constituting the lines of a single header, return the (name, value) tuple that should be stored in the model. The input lines should retain their terminating linesep characters. The lines passed in by the email package may contain @@ -324,15 +309,13 @@ class Compat32(Policy[_MessageT_co]): """ def header_store_parse(self, name: str, value: str) -> tuple[str, str]: - """ - Given the header name and the value provided by the application + """Given the header name and the value provided by the application program, return the (name, value) that should be stored in the model. The name and value are returned unmodified. """ def header_fetch_parse(self, name: str, value: str) -> str | Header: # type: ignore[override] - """ - Given the header name and the value from the model, return the value + """Given the header name and the value from the model, return the value to be returned to the application program that is requesting that header. The value passed in by the email package may contain surrogateescaped binary data if the lines were parsed by a BytesParser. @@ -343,8 +326,7 @@ class Compat32(Policy[_MessageT_co]): """ def fold(self, name: str, value: str) -> str: - """ - Given the header name and the value from the model, return a string + """Given the header name and the value from the model, return a string containing linesep characters that implement the folding of the header according to the policy controls. The value passed in by the email package may contain surrogateescaped binary data if the lines were @@ -358,8 +340,7 @@ class Compat32(Policy[_MessageT_co]): """ def fold_binary(self, name: str, value: str) -> bytes: - """ - Given the header name and the value from the model, return binary + """Given the header name and the value from the model, return binary data containing linesep characters that implement the folding of the header according to the policy controls. The value passed in by the email package may contain surrogateescaped binary data. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/base64mime.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/base64mime.pyi index 83f34f4bb7..6bdc1bf504 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/base64mime.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/base64mime.pyi @@ -26,13 +26,10 @@ __all__ = ["body_decode", "body_encode", "decode", "decodestring", "header_encod from _typeshed import ReadableBuffer def header_length(bytearray: str | bytes | bytearray) -> int: - """ - Return the length of s when it is encoded with base64. - """ + """Return the length of s when it is encoded with base64.""" def header_encode(header_bytes: str | ReadableBuffer, charset: str = "iso-8859-1") -> str: - """ - Encode a single header line with Base64 encoding in a given charset. + """Encode a single header line with Base64 encoding in a given charset. charset names the character set to use to encode the header. It defaults to iso-8859-1. Base64 encoding is defined in RFC 2045. @@ -40,8 +37,7 @@ def header_encode(header_bytes: str | ReadableBuffer, charset: str = "iso-8859-1 # First argument should be a buffer that supports slicing and len(). def body_encode(s: bytes | bytearray, maxlinelen: int = 76, eol: str = "\n") -> str: - """ - Encode a string with base64. + """Encode a string with base64. Each line will be wrapped at, at most, maxlinelen characters (defaults to 76 characters). @@ -52,8 +48,7 @@ def body_encode(s: bytes | bytearray, maxlinelen: int = 76, eol: str = "\n") -> """ def decode(string: str | ReadableBuffer) -> bytes: - """ - Decode a raw base64 string, returning a bytes object. + """Decode a raw base64 string, returning a bytes object. This function does not parse a full MIME header value encoded with base64 (like =?iso-8859-1?b?bmloISBuaWgh?=) -- please use the high diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/charset.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/charset.pyi index 18a0e7fa76..a1b44e899c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/charset.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/charset.pyi @@ -9,8 +9,7 @@ BASE64: Final[int] # undocumented SHORTEST: Final[int] # undocumented class Charset: - """ - Map character sets to their email properties. + """Map character sets to their email properties. This class provides information about the requirements imposed on email for a specific character set. It also provides convenience routines for @@ -62,8 +61,7 @@ class Charset: output_codec: str | None def __init__(self, input_charset: str = "us-ascii") -> None: ... def get_body_encoding(self) -> str | Callable[[Message], None]: - """ - Return the content-transfer-encoding used for body encoding. + """Return the content-transfer-encoding used for body encoding. This is either the string 'quoted-printable' or 'base64' depending on the encoding used, or it is a function in which case you should call @@ -77,16 +75,14 @@ class Charset: """ def get_output_charset(self) -> str | None: - """ - Return the output character set. + """Return the output character set. This is self.output_charset if that is not None, otherwise it is self.input_charset. """ def header_encode(self, string: str) -> str: - """ - Header-encode a string by converting it first to bytes. + """Header-encode a string by converting it first to bytes. The type of encoding (base64 or quoted-printable) will be based on this charset's `header_encoding`. @@ -98,8 +94,7 @@ class Charset: """ def header_encode_lines(self, string: str, maxlengths: Iterator[int]) -> list[str | None]: - """ - Header-encode a string by converting it first to bytes. + """Header-encode a string by converting it first to bytes. This is similar to `header_encode()` except that the string is fit into maximum line lengths as given by the argument. @@ -118,8 +113,7 @@ class Charset: @overload def body_encode(self, string: None) -> None: - """ - Body-encode a string by converting it first to bytes. + """Body-encode a string by converting it first to bytes. The type of encoding (base64 or quoted-printable) will be based on self.body_encoding. If body_encoding is None, we assume the @@ -137,8 +131,7 @@ class Charset: def add_charset( charset: str, header_enc: int | None = None, body_enc: int | None = None, output_charset: str | None = None ) -> None: - """ - Add character set properties to the global registry. + """Add character set properties to the global registry. charset is the input character set, and must be the canonical name of a character set. @@ -162,16 +155,14 @@ def add_charset( """ def add_alias(alias: str, canonical: str) -> None: - """ - Add a character set alias. + """Add a character set alias. alias is the alias name, e.g. latin-1 canonical is the character set's canonical name, e.g. iso-8859-1 """ def add_codec(charset: str, codecname: str) -> None: - """ - Add a codec that map characters in the given charset to/from Unicode. + """Add a codec that map characters in the given charset to/from Unicode. charset is the canonical name of a character set. codecname is the name of a Python codec, as appropriate for the second argument to the unicode() diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/encoders.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/encoders.pyi index afcd8497fe..dfb716293a 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/encoders.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/encoders.pyi @@ -7,25 +7,19 @@ from email.message import Message __all__ = ["encode_7or8bit", "encode_base64", "encode_noop", "encode_quopri"] def encode_base64(msg: Message) -> None: - """ - Encode the message's payload in Base64. + """Encode the message's payload in Base64. Also, add an appropriate Content-Transfer-Encoding header. """ def encode_quopri(msg: Message) -> None: - """ - Encode the message's payload in quoted-printable. + """Encode the message's payload in quoted-printable. Also, add an appropriate Content-Transfer-Encoding header. """ def encode_7or8bit(msg: Message) -> None: - """ - Set the Content-Transfer-Encoding header to 7bit or 8bit. - """ + """Set the Content-Transfer-Encoding header to 7bit or 8bit.""" def encode_noop(msg: Message) -> None: - """ - Do nothing. - """ + """Do nothing.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/errors.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/errors.pyi index 79a0b69371..17b3f21088 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/errors.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/errors.pyi @@ -5,144 +5,90 @@ email package exception classes. import sys class MessageError(Exception): - """ - Base class for errors in the email package. - """ + """Base class for errors in the email package.""" class MessageParseError(MessageError): - """ - Base class for message parsing errors. - """ + """Base class for message parsing errors.""" class HeaderParseError(MessageParseError): - """ - Error while parsing headers. - """ + """Error while parsing headers.""" class BoundaryError(MessageParseError): - """ - Couldn't find terminating boundary. - """ + """Couldn't find terminating boundary.""" class MultipartConversionError(MessageError, TypeError): - """ - Conversion to a multipart is prohibited. - """ + """Conversion to a multipart is prohibited.""" class CharsetError(MessageError): - """ - An illegal charset was given. - """ + """An illegal charset was given.""" # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 class HeaderWriteError(MessageError): - """ - Error while writing headers. - """ + """Error while writing headers.""" class MessageDefect(ValueError): - """ - Base class for a message defect. - """ + """Base class for a message defect.""" def __init__(self, line: str | None = None) -> None: ... class NoBoundaryInMultipartDefect(MessageDefect): - """ - A message claimed to be a multipart but had no boundary parameter. - """ + """A message claimed to be a multipart but had no boundary parameter.""" class StartBoundaryNotFoundDefect(MessageDefect): - """ - The claimed start boundary was never found. - """ + """The claimed start boundary was never found.""" class FirstHeaderLineIsContinuationDefect(MessageDefect): - """ - A message had a continuation line as its first header line. - """ + """A message had a continuation line as its first header line.""" class MisplacedEnvelopeHeaderDefect(MessageDefect): - """ - A 'Unix-from' header was found in the middle of a header block. - """ + """A 'Unix-from' header was found in the middle of a header block.""" class MultipartInvariantViolationDefect(MessageDefect): - """ - A message claimed to be a multipart but no subparts were found. - """ + """A message claimed to be a multipart but no subparts were found.""" class InvalidMultipartContentTransferEncodingDefect(MessageDefect): - """ - An invalid content transfer encoding was set on the multipart itself. - """ + """An invalid content transfer encoding was set on the multipart itself.""" class UndecodableBytesDefect(MessageDefect): - """ - Header contained bytes that could not be decoded - """ + """Header contained bytes that could not be decoded""" class InvalidBase64PaddingDefect(MessageDefect): - """ - base64 encoded sequence had an incorrect length - """ + """base64 encoded sequence had an incorrect length""" class InvalidBase64CharactersDefect(MessageDefect): - """ - base64 encoded sequence had characters not in base64 alphabet - """ + """base64 encoded sequence had characters not in base64 alphabet""" class InvalidBase64LengthDefect(MessageDefect): - """ - base64 encoded sequence had invalid length (1 mod 4) - """ + """base64 encoded sequence had invalid length (1 mod 4)""" class CloseBoundaryNotFoundDefect(MessageDefect): - """ - A start boundary was found, but not the corresponding close boundary. - """ + """A start boundary was found, but not the corresponding close boundary.""" class MissingHeaderBodySeparatorDefect(MessageDefect): - """ - Found line with no leading whitespace and no colon before blank line. - """ + """Found line with no leading whitespace and no colon before blank line.""" MalformedHeaderDefect = MissingHeaderBodySeparatorDefect class HeaderDefect(MessageDefect): - """ - Base class for a header defect. - """ + """Base class for a header defect.""" class InvalidHeaderDefect(HeaderDefect): - """ - Header is not valid, message gives details. - """ + """Header is not valid, message gives details.""" class HeaderMissingRequiredValue(HeaderDefect): - """ - A header that must have a value had none - """ + """A header that must have a value had none""" class NonPrintableDefect(HeaderDefect): - """ - ASCII characters outside the ascii-printable range found - """ + """ASCII characters outside the ascii-printable range found""" def __init__(self, non_printables: str | None) -> None: ... class ObsoleteHeaderDefect(HeaderDefect): - """ - Header uses syntax declared obsolete by RFC 5322 - """ + """Header uses syntax declared obsolete by RFC 5322""" class NonASCIILocalPartDefect(HeaderDefect): - """ - local_part contains non-ASCII characters - """ + """local_part contains non-ASCII characters""" if sys.version_info >= (3, 10): class InvalidDateDefect(HeaderDefect): - """ - Header has unparsable or invalid date - """ + """Header has unparsable or invalid date""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/feedparser.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/feedparser.pyi index 8c65126ca6..2556caa90c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/feedparser.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/feedparser.pyi @@ -25,14 +25,11 @@ from typing import Generic, overload __all__ = ["FeedParser", "BytesFeedParser"] class FeedParser(Generic[_MessageT]): - """ - A feed-style parser of email. - """ + """A feed-style parser of email.""" @overload def __init__(self: FeedParser[Message], _factory: None = None, *, policy: Policy[Message] = ...) -> None: - """ - _factory is called with no arguments to create a new message obj + """_factory is called with no arguments to create a new message obj The policy keyword specifies a policy object that controls a number of aspects of the parser's operation. The default policy maintains @@ -42,24 +39,17 @@ class FeedParser(Generic[_MessageT]): @overload def __init__(self, _factory: Callable[[], _MessageT], *, policy: Policy[_MessageT] = ...) -> None: ... def feed(self, data: str) -> None: - """ - Push more data into the parser. - """ + """Push more data into the parser.""" def close(self) -> _MessageT: - """ - Parse all remaining data and return the root message object. - """ + """Parse all remaining data and return the root message object.""" class BytesFeedParser(FeedParser[_MessageT]): - """ - Like FeedParser, but feed accepts bytes. - """ + """Like FeedParser, but feed accepts bytes.""" @overload def __init__(self: BytesFeedParser[Message], _factory: None = None, *, policy: Policy[Message] = ...) -> None: - """ - _factory is called with no arguments to create a new message obj + """_factory is called with no arguments to create a new message obj The policy keyword specifies a policy object that controls a number of aspects of the parser's operation. The default policy maintains diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/generator.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/generator.pyi index d1cad5e3f6..b01da84149 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/generator.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/generator.pyi @@ -14,8 +14,7 @@ __all__ = ["Generator", "DecodedGenerator", "BytesGenerator"] _MessageT = TypeVar("_MessageT", bound=Message[Any, Any], default=Any) class Generator(Generic[_MessageT]): - """ - Generates output from a Message object tree. + """Generates output from a Message object tree. This basic generator writes the message to the given file object as plain text. @@ -32,8 +31,7 @@ class Generator(Generic[_MessageT]): *, policy: None = None, ) -> None: - """ - Create the generator for message flattening. + """Create the generator for message flattening. outfp is the output file-like object for writing the message to. It must have a write() method. @@ -66,8 +64,7 @@ class Generator(Generic[_MessageT]): ) -> None: ... def write(self, s: str) -> None: ... def flatten(self, msg: _MessageT, unixfrom: bool = False, linesep: str | None = None) -> None: - """ - Print the message object tree rooted at msg to the output file + """Print the message object tree rooted at msg to the output file specified when the Generator instance was created. unixfrom is a flag that forces the printing of a Unix From_ delimiter @@ -84,13 +81,10 @@ class Generator(Generic[_MessageT]): """ def clone(self, fp: SupportsWrite[str]) -> Self: - """ - Clone this generator with the exact same options. - """ + """Clone this generator with the exact same options.""" class BytesGenerator(Generator[_MessageT]): - """ - Generates a bytes version of a Message object tree. + """Generates a bytes version of a Message object tree. Functionally identical to the base Generator except that the output is bytes and not string. When surrogates were used in the input to encode @@ -111,8 +105,7 @@ class BytesGenerator(Generator[_MessageT]): *, policy: None = None, ) -> None: - """ - Create the generator for message flattening. + """Create the generator for message flattening. outfp is the output file-like object for writing the message to. It must have a write() method. @@ -145,8 +138,7 @@ class BytesGenerator(Generator[_MessageT]): ) -> None: ... class DecodedGenerator(Generator[_MessageT]): - """ - Generates a text representation of a message. + """Generates a text representation of a message. Like the Generator base class, except that non-text parts are substituted with a format string representing the part. @@ -162,8 +154,7 @@ class DecodedGenerator(Generator[_MessageT]): *, policy: None = None, ) -> None: - """ - Like Generator.__init__() except that an additional optional + """Like Generator.__init__() except that an additional optional argument is allowed. Walks through all subparts of a message. If the subpart is of main diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/header.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/header.pyi index 6cee7fb6b6..9132b62267 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/header.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/header.pyi @@ -18,8 +18,7 @@ class Header: continuation_ws: str = " ", errors: str = "strict", ) -> None: - """ - Create a MIME-compliant header that can contain many character sets. + """Create a MIME-compliant header that can contain many character sets. Optional s is the initial header value. If None, the initial header value is not set. You can later append to the header with .append() @@ -47,8 +46,7 @@ class Header: """ def append(self, s: bytes | bytearray | str, charset: Charset | str | None = None, errors: str = "strict") -> None: - """ - Append a string to the MIME header. + """Append a string to the MIME header. Optional charset, if given, should be a Charset instance or the name of a character set (which will be converted to a Charset instance). A @@ -70,8 +68,7 @@ class Header: """ def encode(self, splitchars: str = ";, \t", maxlinelen: int | None = None, linesep: str = "\n") -> str: - """ - Encode a message header into an RFC-compliant format. + """Encode a message header into an RFC-compliant format. There are many issues involved in converting a given string for use in an email header. Only certain character sets are readable in most @@ -111,8 +108,7 @@ class Header: # contains no encoded parts, or list[tuple[bytes, str | None]] if the header # contains at least one encoded part. def decode_header(header: Header | str) -> list[tuple[Any, Any | None]]: - """ - Decode a message header value without converting charset. + """Decode a message header value without converting charset. For historical reasons, this function may return either: @@ -138,8 +134,7 @@ def make_header( header_name: str | None = None, continuation_ws: str = " ", ) -> Header: - """ - Create a Header from a sequence of pairs as returned by decode_header() + """Create a Header from a sequence of pairs as returned by decode_header() decode_header() takes a header value string and returns a sequence of pairs of the format (decoded_string, charset) where charset is the string diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/headerregistry.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/headerregistry.pyi index 903530d295..c5d49cfb0c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/headerregistry.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/headerregistry.pyi @@ -24,8 +24,7 @@ from typing import Any, ClassVar, Literal, Protocol from typing_extensions import Self class BaseHeader(str): - """ - Base class for message headers. + """Base class for message headers. Implements generic behavior and provides tools for subclasses. @@ -65,8 +64,7 @@ class BaseHeader(str): def __new__(cls, name: str, value: Any) -> Self: ... def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect]) -> None: ... def fold(self, *, policy: Policy) -> str: - """ - Fold header according to policy. + """Fold header according to policy. The parsed representation of the header is folded according to RFC5322 rules, as modified by the policy. If the parse tree @@ -85,8 +83,7 @@ class UnstructuredHeader: max_count: ClassVar[Literal[1] | None] @staticmethod def value_parser(value: str) -> UnstructuredTokenList: - """ - unstructured = (*([FWS] vchar) *WSP) / obs-unstruct + """unstructured = (*([FWS] vchar) *WSP) / obs-unstruct obs-unstruct = *((*LF *CR *(obs-utext) *LF *CR)) / FWS) obs-utext = %d0 / obs-NO-WS-CTL / LF / CR @@ -111,8 +108,7 @@ class UniqueUnstructuredHeader(UnstructuredHeader): max_count: ClassVar[Literal[1]] class DateHeader: - """ - Header whose value consists of a single timestamp. + """Header whose value consists of a single timestamp. Provides an additional attribute, datetime, which is either an aware datetime using a timezone, or a naive datetime if the timezone @@ -127,8 +123,7 @@ class DateHeader: def datetime(self) -> _datetime: ... @staticmethod def value_parser(value: str) -> UnstructuredTokenList: - """ - unstructured = (*([FWS] vchar) *WSP) / obs-unstruct + """unstructured = (*([FWS] vchar) *WSP) / obs-unstruct obs-unstruct = *((*LF *CR *(obs-utext) *LF *CR)) / FWS) obs-utext = %d0 / obs-NO-WS-CTL / LF / CR @@ -194,9 +189,7 @@ class MIMEVersionHeader: def minor(self) -> int | None: ... @staticmethod def value_parser(value: str) -> MIMEVersion: - """ - mime-version = [CFWS] 1*digit [CFWS] "." [CFWS] 1*digit [CFWS] - """ + """mime-version = [CFWS] 1*digit [CFWS] "." [CFWS] 1*digit [CFWS]""" @classmethod def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... @@ -218,8 +211,7 @@ class ContentTypeHeader(ParameterizedMIMEHeader): def subtype(self) -> str: ... @staticmethod def value_parser(value: str) -> ContentType: - """ - maintype "/" subtype *( ";" parameter ) + """maintype "/" subtype *( ";" parameter ) The maintype and substype are tokens. Theoretically they could be checked against the official IANA list + x-token, but we @@ -232,9 +224,7 @@ class ContentDispositionHeader(ParameterizedMIMEHeader): def content_disposition(self) -> str | None: ... @staticmethod def value_parser(value: str) -> ContentDisposition: - """ - disposition-type *( ";" parameter ) - """ + """disposition-type *( ";" parameter )""" class ContentTransferEncodingHeader: max_count: ClassVar[Literal[1]] @@ -245,9 +235,7 @@ class ContentTransferEncodingHeader: def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... @staticmethod def value_parser(value: str) -> ContentTransferEncoding: - """ - mechanism - """ + """mechanism""" class MessageIDHeader: max_count: ClassVar[Literal[1]] @@ -255,9 +243,7 @@ class MessageIDHeader: def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... @staticmethod def value_parser(value: str) -> MessageID: - """ - message-id = "Message-ID:" msg-id CRLF - """ + """message-id = "Message-ID:" msg-id CRLF""" class _HeaderParser(Protocol): max_count: ClassVar[Literal[1] | None] @@ -267,9 +253,7 @@ class _HeaderParser(Protocol): def parse(cls, value: str, kwds: dict[str, Any], /) -> None: ... class HeaderRegistry: - """ - A header_factory and header registry. - """ + """A header_factory and header registry.""" registry: dict[str, type[_HeaderParser]] base_class: type[BaseHeader] @@ -277,8 +261,7 @@ class HeaderRegistry: def __init__( self, base_class: type[BaseHeader] = ..., default_class: type[_HeaderParser] = ..., use_default_map: bool = True ) -> None: - """ - Create a header_factory that works with the Policy API. + """Create a header_factory that works with the Policy API. base_class is the class that will be the last class in the created header class's __bases__ list. default_class is the class that will be @@ -289,14 +272,11 @@ class HeaderRegistry: """ def map_to_type(self, name: str, cls: type[BaseHeader]) -> None: - """ - Register cls as the specialized class for handling "name" headers. - """ + """Register cls as the specialized class for handling "name" headers.""" def __getitem__(self, name: str) -> type[BaseHeader]: ... def __call__(self, name: str, value: Any) -> BaseHeader: - """ - Create a header instance for header 'name' from 'value'. + """Create a header instance for header 'name' from 'value'. Creates a header instance by creating a specialized class for parsing and representing the specified header by combining the factory @@ -314,16 +294,14 @@ class Address: def domain(self) -> str: ... @property def addr_spec(self) -> str: - """ - The addr_spec (username@domain) portion of the address, quoted + """The addr_spec (username@domain) portion of the address, quoted according to RFC 5322 rules, but with no Content Transfer Encoding. """ def __init__( self, display_name: str = "", username: str | None = "", domain: str | None = "", addr_spec: str | None = None ) -> None: - """ - Create an object representing a full email address. + """Create an object representing a full email address. An address can have a 'display_name', a 'username', and a 'domain'. In addition to specifying the username and domain separately, they may be @@ -346,8 +324,7 @@ class Group: @property def addresses(self) -> tuple[Address, ...]: ... def __init__(self, display_name: str | None = None, addresses: Iterable[Address] | None = None) -> None: - """ - Create an object representing an address group. + """Create an object representing an address group. An address group consists of a display_name followed by colon and a list of addresses (see Address) terminated by a semi-colon. The Group diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/iterators.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/iterators.pyi index a7b839a2d4..cc9e2b97f9 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/iterators.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/iterators.pyi @@ -9,15 +9,13 @@ from email.message import Message __all__ = ["body_line_iterator", "typed_subpart_iterator", "walk"] def body_line_iterator(msg: Message, decode: bool = False) -> Iterator[str]: - """ - Iterate over the parts, returning string payloads line-by-line. + """Iterate over the parts, returning string payloads line-by-line. Optional decode (default False) is passed through to .get_payload(). """ def typed_subpart_iterator(msg: Message, maintype: str = "text", subtype: str | None = None) -> Iterator[str]: - """ - Iterate over the subparts with a given MIME type. + """Iterate over the subparts with a given MIME type. Use 'maintype' as the main MIME type to match against; this defaults to "text". Optional 'subtype' is the MIME subtype to match against; if @@ -25,8 +23,7 @@ def typed_subpart_iterator(msg: Message, maintype: str = "text", subtype: str | """ def walk(self: Message) -> Iterator[Message]: - """ - Walk over the message tree, yielding each subpart. + """Walk over the message tree, yielding each subpart. The walk is performed in depth-first order. This method is a generator. @@ -34,6 +31,4 @@ def walk(self: Message) -> Iterator[Message]: # We include the seemingly private function because it is documented in the stdlib documentation. def _structure(msg: Message, fp: SupportsWrite[str] | None = None, level: int = 0, include_default: bool = False) -> None: - """ - A handy debugging aid - """ + """A handy debugging aid""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/message.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/message.pyi index 53e884c65f..5e10c6d431 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/message.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/message.pyi @@ -35,8 +35,7 @@ class _SupportsDecodeToPayload(Protocol): def decode(self, encoding: str, errors: str, /) -> _PayloadType | _MultipartPayloadType: ... class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): - """ - Basic message object. + """Basic message object. A message object is defined as something that has a bunch of RFC 2822 headers and a payload. It may optionally have an envelope header @@ -59,15 +58,12 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): defects: list[MessageDefect] def __init__(self, policy: Policy[Any] = ...) -> None: ... def is_multipart(self) -> bool: - """ - Return True if the message consists of multiple parts. - """ + """Return True if the message consists of multiple parts.""" def set_unixfrom(self, unixfrom: str) -> None: ... def get_unixfrom(self) -> str | None: ... def attach(self, payload: _PayloadType) -> None: - """ - Add the given payload to the current payload. + """Add the given payload to the current payload. The current payload will always be a list of objects after this method is called. If you want to set the payload to a scalar object, use @@ -77,8 +73,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): # `| MaybeNone` acts like `| Any`: can be None for cleared or unset payload, but annoying to check @overload # multipart def get_payload(self, i: int, decode: Literal[True]) -> None: - """ - Return a reference to the payload. + """Return a reference to the payload. The payload will either be a list object or a string. If you mutate the list object, you modify the message's payload in place. Optional @@ -111,8 +106,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): # Not[_SupportsEncodeToPayload] @overload def set_payload(self, payload: _SupportsDecodeToPayload | _PayloadType | _MultipartPayloadType, charset: None = None) -> None: - """ - Set the payload to the given value. + """Set the payload to the given value. Optional charset sets the message's default character set. See set_charset() for details. @@ -125,8 +119,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): charset: Charset | str, ) -> None: ... def set_charset(self, charset: _CharsetType) -> None: - """ - Set the charset of the payload to a given character set. + """Set the charset of the payload to a given character set. charset can be a Charset instance, a string naming a character set, or None. If it is a string it will be converted to a Charset instance. @@ -141,14 +134,10 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): """ def get_charset(self) -> _CharsetType: - """ - Return the Charset instance associated with the message's payload. - """ + """Return the Charset instance associated with the message's payload.""" def __len__(self) -> int: - """ - Return the total number of headers, including duplicates. - """ + """Return the total number of headers, including duplicates.""" def __contains__(self, name: str) -> bool: ... def __iter__(self) -> Iterator[str]: ... @@ -157,8 +146,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): # Morally, the return type should be `AnyOf[_HeaderType, None]`, # so using "the Any trick" instead. def __getitem__(self, name: str) -> _HeaderT_co | MaybeNone: - """ - Get a header value. + """Get a header value. Return None if the header is missing instead of raising an exception. @@ -168,23 +156,20 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): """ def __setitem__(self, name: str, val: _HeaderParamT_contra) -> None: - """ - Set the value of a header. + """Set the value of a header. Note: this does not overwrite an existing header with the same field name. Use __delitem__() first to delete any existing headers. """ def __delitem__(self, name: str) -> None: - """ - Delete all occurrences of a header, if present. + """Delete all occurrences of a header, if present. Does not raise an exception if the header is missing. """ def keys(self) -> list[str]: - """ - Return a list of all the message's header field names. + """Return a list of all the message's header field names. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. @@ -193,8 +178,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): """ def values(self) -> list[_HeaderT_co]: - """ - Return a list of all the message's header values. + """Return a list of all the message's header values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. @@ -203,8 +187,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): """ def items(self) -> list[tuple[str, _HeaderT_co]]: - """ - Get all the message's header fields and values. + """Get all the message's header fields and values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. @@ -214,8 +197,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): @overload def get(self, name: str, failobj: None = None) -> _HeaderT_co | None: - """ - Get a header value. + """Get a header value. Like __getitem__() but return failobj instead of None when the field is missing. @@ -225,8 +207,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): def get(self, name: str, failobj: _T) -> _HeaderT_co | _T: ... @overload def get_all(self, name: str, failobj: None = None) -> list[_HeaderT_co] | None: - """ - Return a list of all the values for the named field. + """Return a list of all the values for the named field. These will be sorted in the order they appeared in the original message, and may contain duplicates. Any fields deleted and @@ -238,8 +219,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): @overload def get_all(self, name: str, failobj: _T) -> list[_HeaderT_co] | _T: ... def add_header(self, _name: str, _value: str, **_params: _ParamsType) -> None: - """ - Extended header setting. + """Extended header setting. name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted @@ -260,8 +240,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): """ def replace_header(self, _name: str, _value: _HeaderParamT_contra) -> None: - """ - Replace a header. + """Replace a header. Replace the first matching header found in the message, retaining header order and case. If no matching header was found, a KeyError is @@ -269,8 +248,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): """ def get_content_type(self) -> str: - """ - Return the message's content type. + """Return the message's content type. The returned string is coerced to lower case of the form 'maintype/subtype'. If there was no Content-Type header in the @@ -284,24 +262,21 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): """ def get_content_maintype(self) -> str: - """ - Return the message's main content type. + """Return the message's main content type. This is the 'maintype' part of the string returned by get_content_type(). """ def get_content_subtype(self) -> str: - """ - Returns the message's sub-content type. + """Returns the message's sub-content type. This is the 'subtype' part of the string returned by get_content_type(). """ def get_default_type(self) -> str: - """ - Return the 'default' content type. + """Return the 'default' content type. Most messages have a default content type of text/plain, except for messages that are subparts of multipart/digest containers. Such @@ -309,8 +284,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): """ def set_default_type(self, ctype: str) -> None: - """ - Set the 'default' content type. + """Set the 'default' content type. ctype should be either "text/plain" or "message/rfc822", although this is not enforced. The default content type is not stored in the @@ -321,8 +295,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): def get_params( self, failobj: None = None, header: str = "content-type", unquote: bool = True ) -> list[tuple[str, str]] | None: - """ - Return the message's Content-Type parameters, as a list. + """Return the message's Content-Type parameters, as a list. The elements of the returned list are 2-tuples of key/value pairs, as split on the '=' sign. The left hand side of the '=' is the key, @@ -341,8 +314,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): def get_param( self, param: str, failobj: None = None, header: str = "content-type", unquote: bool = True ) -> _ParamType | None: - """ - Return the parameter value if found in the Content-Type header. + """Return the parameter value if found in the Content-Type header. Optional failobj is the object to return if there is no Content-Type header, or the Content-Type header has no such parameter. Optional @@ -367,8 +339,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): @overload def get_param(self, param: str, failobj: _T, header: str = "content-type", unquote: bool = True) -> _ParamType | _T: ... def del_param(self, param: str, header: str = "content-type", requote: bool = True) -> None: - """ - Remove the given parameter completely from the Content-Type header. + """Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. All values will be quoted as necessary unless requote is @@ -377,8 +348,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): """ def set_type(self, type: str, header: str = "Content-Type", requote: bool = True) -> None: - """ - Set the main type and subtype for the Content-Type header. + """Set the main type and subtype for the Content-Type header. type must be a string in the form "maintype/subtype", otherwise a ValueError is raised. @@ -395,8 +365,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): @overload def get_filename(self, failobj: None = None) -> str | None: - """ - Return the filename associated with the payload if present. + """Return the filename associated with the payload if present. The filename is extracted from the Content-Disposition header's 'filename' parameter, and it is unquoted. If that header is missing @@ -408,8 +377,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): def get_filename(self, failobj: _T) -> str | _T: ... @overload def get_boundary(self, failobj: None = None) -> str | None: - """ - Return the boundary associated with the payload if present. + """Return the boundary associated with the payload if present. The boundary is extracted from the Content-Type header's 'boundary' parameter, and it is unquoted. @@ -418,8 +386,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): @overload def get_boundary(self, failobj: _T) -> str | _T: ... def set_boundary(self, boundary: str) -> None: - """ - Set the boundary parameter in Content-Type to 'boundary'. + """Set the boundary parameter in Content-Type to 'boundary'. This is subtly different than deleting the Content-Type header and adding a new one with a new boundary parameter via add_header(). The @@ -431,8 +398,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): @overload def get_content_charset(self) -> str | None: - """ - Return the charset parameter of the Content-Type header. + """Return the charset parameter of the Content-Type header. The returned string is always coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, @@ -443,8 +409,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): def get_content_charset(self, failobj: _T) -> str | _T: ... @overload def get_charsets(self, failobj: None = None) -> list[str | None]: - """ - Return a list containing the charset(s) used in this message. + """Return a list containing the charset(s) used in this message. The returned list of items describes the Content-Type headers' charset parameter for this message and all the subparts in its @@ -463,24 +428,21 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): @overload def get_charsets(self, failobj: _T) -> list[str | _T]: ... def walk(self) -> Generator[Self, None, None]: - """ - Walk over the message tree, yielding each subpart. + """Walk over the message tree, yielding each subpart. The walk is performed in depth-first order. This method is a generator. """ def get_content_disposition(self) -> str | None: - """ - Return the message's content-disposition if it exists, or None. + """Return the message's content-disposition if it exists, or None. The return values can be either 'inline', 'attachment' or None according to the rfc2183. """ def as_string(self, unixfrom: bool = False, maxheaderlen: int = 0, policy: Policy[Any] | None = None) -> str: - """ - Return the entire formatted message as a string. + """Return the entire formatted message as a string. Optional 'unixfrom', when true, means include the Unix From_ envelope header. For backward compatibility reasons, if maxheaderlen is @@ -495,8 +457,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): """ def as_bytes(self, unixfrom: bool = False, policy: Policy[Any] | None = None) -> bytes: - """ - Return the entire formatted message as a bytes object. + """Return the entire formatted message as a bytes object. Optional 'unixfrom', when true, means include the Unix From_ envelope header. 'policy' is passed to the BytesGenerator instance used to @@ -505,9 +466,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): """ def __bytes__(self) -> bytes: - """ - Return the entire formatted message as a bytes object. - """ + """Return the entire formatted message as a bytes object.""" def set_param( self, @@ -519,8 +478,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): language: str = "", replace: bool = False, ) -> None: - """ - Set a parameter in the Content-Type header. + """Set a parameter in the Content-Type header. If the parameter already exists in the header, its value will be replaced with the new value. @@ -538,15 +496,13 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): """ # The following two methods are undocumented, but a source code comment states that they are public API def set_raw(self, name: str, value: _HeaderParamT_contra) -> None: - """ - Store name and value in the model without modification. + """Store name and value in the model without modification. This is an "internal" API, intended only for use by a parser. """ def raw_items(self) -> Iterator[tuple[str, _HeaderT_co]]: - """ - Return the (name, value) header pairs without modification. + """Return the (name, value) header pairs without modification. This is an "internal" API, intended only for use by a generator. """ @@ -554,8 +510,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): class MIMEPart(Message[_HeaderRegistryT_co, _HeaderRegistryParamT_contra]): def __init__(self, policy: Policy[Any] | None = None) -> None: ... def get_body(self, preferencelist: Sequence[str] = ("related", "html", "plain")) -> MIMEPart[_HeaderRegistryT_co] | None: - """ - Return best candidate mime part for display as 'body' of message. + """Return best candidate mime part for display as 'body' of message. Do a depth first search, starting with self, looking for the first part matching each of the items in preferencelist, and return the part @@ -566,8 +521,7 @@ class MIMEPart(Message[_HeaderRegistryT_co, _HeaderRegistryParamT_contra]): """ def attach(self, payload: Self) -> None: # type: ignore[override] - """ - Add the given payload to the current payload. + """Add the given payload to the current payload. The current payload will always be a list of objects after this method is called. If you want to set the payload to a scalar object, use @@ -577,8 +531,7 @@ class MIMEPart(Message[_HeaderRegistryT_co, _HeaderRegistryParamT_contra]): # possible to sneak other attachment types into a MIMEPart instance, but could cause # cause unforseen consequences. def iter_attachments(self) -> Iterator[Self]: - """ - Return an iterator over the non-main parts of a multipart. + """Return an iterator over the non-main parts of a multipart. Skip the first of each occurrence of text/plain, text/html, multipart/related, or multipart/alternative in the multipart (unless @@ -590,8 +543,7 @@ class MIMEPart(Message[_HeaderRegistryT_co, _HeaderRegistryParamT_contra]): """ def iter_parts(self) -> Iterator[MIMEPart[_HeaderRegistryT_co]]: - """ - Return an iterator over all immediate subparts of a multipart. + """Return an iterator over all immediate subparts of a multipart. Return an empty iterator for a non-multipart. """ @@ -607,8 +559,7 @@ class MIMEPart(Message[_HeaderRegistryT_co, _HeaderRegistryParamT_contra]): def clear(self) -> None: ... def clear_content(self) -> None: ... def as_string(self, unixfrom: bool = False, maxheaderlen: int | None = None, policy: Policy[Any] | None = None) -> str: - """ - Return the entire formatted message as a string. + """Return the entire formatted message as a string. Optional 'unixfrom', when true, means include the Unix From_ envelope header. maxheaderlen is retained for backward compatibility with the diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/application.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/application.pyi index 8608f046b5..db1a5c93cc 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/application.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/application.pyi @@ -10,9 +10,7 @@ from email.policy import Policy __all__ = ["MIMEApplication"] class MIMEApplication(MIMENonMultipart): - """ - Class for generating application/* MIME documents. - """ + """Class for generating application/* MIME documents.""" def __init__( self, @@ -23,8 +21,7 @@ class MIMEApplication(MIMENonMultipart): policy: Policy | None = None, **_params: _ParamsType, ) -> None: - """ - Create an application/* type MIME document. + """Create an application/* type MIME document. _data contains the bytes for the raw application data. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/audio.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/audio.pyi index e8e661d31b..634c6e4aba 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/audio.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/audio.pyi @@ -10,9 +10,7 @@ from email.policy import Policy __all__ = ["MIMEAudio"] class MIMEAudio(MIMENonMultipart): - """ - Class for generating audio/* MIME documents. - """ + """Class for generating audio/* MIME documents.""" def __init__( self, @@ -23,8 +21,7 @@ class MIMEAudio(MIMENonMultipart): policy: Policy | None = None, **_params: _ParamsType, ) -> None: - """ - Create an audio/* type MIME document. + """Create an audio/* type MIME document. _audiodata contains the bytes for the raw audio data. If this data can be decoded as au, wav, aiff, or aifc, then the diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/base.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/base.pyi index ae096f7095..bda2856f38 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/base.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/base.pyi @@ -9,13 +9,10 @@ from email.policy import Policy __all__ = ["MIMEBase"] class MIMEBase(email.message.Message): - """ - Base class for MIME specializations. - """ + """Base class for MIME specializations.""" def __init__(self, _maintype: str, _subtype: str, *, policy: Policy | None = None, **_params: _ParamsType) -> None: - """ - This constructor adds a Content-Type: and a MIME-Version: header. + """This constructor adds a Content-Type: and a MIME-Version: header. The Content-Type: header is taken from the _maintype and _subtype arguments. Additional parameters for this header are taken from the diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/image.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/image.pyi index 1a47bb35eb..b81fd35a04 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/image.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/image.pyi @@ -10,9 +10,7 @@ from email.policy import Policy __all__ = ["MIMEImage"] class MIMEImage(MIMENonMultipart): - """ - Class for generating image/* type MIME documents. - """ + """Class for generating image/* type MIME documents.""" def __init__( self, @@ -23,8 +21,7 @@ class MIMEImage(MIMENonMultipart): policy: Policy | None = None, **_params: _ParamsType, ) -> None: - """ - Create an image/* type MIME document. + """Create an image/* type MIME document. _imagedata contains the bytes for the raw image data. If the data type can be detected (jpeg, png, gif, tiff, rgb, pbm, pgm, ppm, diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/message.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/message.pyi index fb3c4e8246..41881c8ef8 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/message.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/message.pyi @@ -9,13 +9,10 @@ from email.policy import Policy __all__ = ["MIMEMessage"] class MIMEMessage(MIMENonMultipart): - """ - Class representing message/* MIME documents. - """ + """Class representing message/* MIME documents.""" def __init__(self, _msg: _MessageT, _subtype: str = "rfc822", *, policy: Policy[_MessageT] | None = None) -> None: - """ - Create a message/* type MIME document. + """Create a message/* type MIME document. _msg is a message object and must be an instance of Message, or a derived class of Message, otherwise a TypeError is raised. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/multipart.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/multipart.pyi index a24b302a96..39c8806e81 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/multipart.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/multipart.pyi @@ -11,9 +11,7 @@ from email.policy import Policy __all__ = ["MIMEMultipart"] class MIMEMultipart(MIMEBase): - """ - Base class for MIME multipart/* type messages. - """ + """Base class for MIME multipart/* type messages.""" def __init__( self, @@ -24,8 +22,7 @@ class MIMEMultipart(MIMEBase): policy: Policy[_MessageT] | None = None, **_params: _ParamsType, ) -> None: - """ - Creates a multipart/* type message. + """Creates a multipart/* type message. By default, creates a multipart/mixed message, with proper Content-Type and MIME-Version headers. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/nonmultipart.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/nonmultipart.pyi index 1f5f929aed..288c9ba13f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/nonmultipart.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/nonmultipart.pyi @@ -7,6 +7,4 @@ from email.mime.base import MIMEBase __all__ = ["MIMENonMultipart"] class MIMENonMultipart(MIMEBase): - """ - Base class for MIME non-multipart type messages. - """ + """Base class for MIME non-multipart type messages.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/text.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/text.pyi index 785526b19a..5dcb283a6f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/text.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/mime/text.pyi @@ -8,13 +8,10 @@ from email.mime.nonmultipart import MIMENonMultipart __all__ = ["MIMEText"] class MIMEText(MIMENonMultipart): - """ - Class for generating text/* type MIME documents. - """ + """Class for generating text/* type MIME documents.""" def __init__(self, _text: str, _subtype: str = "plain", _charset: str | None = None, *, policy: Policy | None = None) -> None: - """ - Create a text/* type MIME document. + """Create a text/* type MIME document. _text is the string for this message object. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/parser.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/parser.pyi index 75a5ac737f..669565c822 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/parser.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/parser.pyi @@ -16,8 +16,7 @@ __all__ = ["Parser", "HeaderParser", "BytesParser", "BytesHeaderParser", "FeedPa class Parser(Generic[_MessageT]): @overload def __init__(self: Parser[Message[str, str]], _class: None = None) -> None: - """ - Parser of RFC 2822 and MIME email messages. + """Parser of RFC 2822 and MIME email messages. Creates an in-memory object tree representing the email message, which can then be manipulated and turned over to a Generator to return the @@ -42,8 +41,7 @@ class Parser(Generic[_MessageT]): @overload def __init__(self, _class: Callable[[], _MessageT] | None, *, policy: Policy[_MessageT] = ...) -> None: ... def parse(self, fp: SupportsRead[str], headersonly: bool = False) -> _MessageT: - """ - Create a message structure from the data in a file. + """Create a message structure from the data in a file. Reads all the data from the file and returns the root of the message structure. Optional headersonly is a flag specifying whether to stop @@ -52,8 +50,7 @@ class Parser(Generic[_MessageT]): """ def parsestr(self, text: str, headersonly: bool = False) -> _MessageT: - """ - Create a message structure from a string. + """Create a message structure from a string. Returns the root of the message structure. Optional headersonly is a flag specifying whether to stop parsing after reading the headers or @@ -69,8 +66,7 @@ class BytesParser(Generic[_MessageT]): parser: Parser[_MessageT] @overload def __init__(self: BytesParser[Message[str, str]], _class: None = None) -> None: - """ - Parser of binary RFC 2822 and MIME email messages. + """Parser of binary RFC 2822 and MIME email messages. Creates an in-memory object tree representing the email message, which can then be manipulated and turned over to a Generator to return the @@ -91,8 +87,7 @@ class BytesParser(Generic[_MessageT]): @overload def __init__(self, _class: Callable[[], _MessageT], *, policy: Policy[_MessageT] = ...) -> None: ... def parse(self, fp: _WrappedBuffer, headersonly: bool = False) -> _MessageT: - """ - Create a message structure from the data in a binary file. + """Create a message structure from the data in a binary file. Reads all the data from the file and returns the root of the message structure. Optional headersonly is a flag specifying whether to stop @@ -101,8 +96,7 @@ class BytesParser(Generic[_MessageT]): """ def parsebytes(self, text: bytes | bytearray, headersonly: bool = False) -> _MessageT: - """ - Create a message structure from a byte string. + """Create a message structure from a byte string. Returns the root of the message structure. Optional headersonly is a flag specifying whether to stop parsing after reading the headers or diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/policy.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/policy.pyi index 8d33ca7e27..72dae2ec4c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/policy.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/policy.pyi @@ -13,8 +13,7 @@ from typing_extensions import Self __all__ = ["Compat32", "compat32", "Policy", "EmailPolicy", "default", "strict", "SMTP", "HTTP"] class EmailPolicy(Policy[_MessageT]): - """ - Controls for how messages are interpreted and formatted. + """Controls for how messages are interpreted and formatted. Most of the classes and many of the methods in the email package accept Policy objects as parameters. A Policy object contains a set of values and @@ -162,8 +161,7 @@ class EmailPolicy(Policy[_MessageT]): content_manager: ContentManager = ..., ) -> None: ... def header_source_parse(self, sourcelines: list[str]) -> tuple[str, str]: - """ - Given a list of linesep terminated strings constituting the lines of + """Given a list of linesep terminated strings constituting the lines of a single header, return the (name, value) tuple that should be stored in the model. The input lines should retain their terminating linesep characters. The lines passed in by the email package may contain @@ -176,8 +174,7 @@ class EmailPolicy(Policy[_MessageT]): """ def header_store_parse(self, name: str, value: Any) -> tuple[str, Any]: - """ - Given the header name and the value provided by the application + """Given the header name and the value provided by the application program, return the (name, value) that should be stored in the model. The name is returned unchanged. If the input value has a 'name' attribute and it matches the name ignoring case, the value is returned @@ -188,8 +185,7 @@ class EmailPolicy(Policy[_MessageT]): """ def header_fetch_parse(self, name: str, value: str) -> Any: - """ - Given the header name and the value from the model, return the value + """Given the header name and the value from the model, return the value to be returned to the application program that is requesting that header. The value passed in by the email package may contain surrogateescaped binary data if the lines were parsed by a BytesParser. @@ -203,8 +199,7 @@ class EmailPolicy(Policy[_MessageT]): """ def fold(self, name: str, value: str) -> Any: - """ - Given the header name and the value from the model, return a string + """Given the header name and the value from the model, return a string containing linesep characters that implement the folding of the header according to the policy controls. The value passed in by the email package may contain surrogateescaped binary data if the lines were @@ -229,8 +224,7 @@ class EmailPolicy(Policy[_MessageT]): """ def fold_binary(self, name: str, value: str) -> bytes: - """ - Given the header name and the value from the model, return binary + """Given the header name and the value from the model, return binary data containing linesep characters that implement the folding of the header according to the policy controls. The value passed in by the email package may contain surrogateescaped binary data. @@ -263,8 +257,7 @@ class EmailPolicy(Policy[_MessageT]): header_factory: Callable[[str, str], str] = ..., content_manager: ContentManager = ..., ) -> Self: - """ - Return a new instance with specified attributes changed. + """Return a new instance with specified attributes changed. The new instance has the same attribute values as the current object, except for the changes passed in as keyword arguments. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/quoprimime.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/quoprimime.pyi index b900823537..572b9f52a2 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/quoprimime.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/quoprimime.pyi @@ -39,18 +39,13 @@ __all__ = [ ] def header_check(octet: int) -> bool: - """ - Return True if the octet should be escaped with header quopri. - """ + """Return True if the octet should be escaped with header quopri.""" def body_check(octet: int) -> bool: - """ - Return True if the octet should be escaped with body quopri. - """ + """Return True if the octet should be escaped with body quopri.""" def header_length(bytearray: Iterable[int]) -> int: - """ - Return a header quoted-printable encoding length. + """Return a header quoted-printable encoding length. Note that this does not include any RFC 2047 chrome added by `header_encode()`. @@ -61,8 +56,7 @@ def header_length(bytearray: Iterable[int]) -> int: """ def body_length(bytearray: Iterable[int]) -> int: - """ - Return a body quoted-printable encoding length. + """Return a body quoted-printable encoding length. :param bytearray: An array of bytes (a.k.a. octets). :return: The length in bytes of the byte array when it is encoded with @@ -70,14 +64,11 @@ def body_length(bytearray: Iterable[int]) -> int: """ def unquote(s: str | bytes | bytearray) -> str: - """ - Turn a string in the form =AB to the ASCII character with value 0xab - """ + """Turn a string in the form =AB to the ASCII character with value 0xab""" def quote(c: str | bytes | bytearray) -> str: ... def header_encode(header_bytes: bytes | bytearray, charset: str = "iso-8859-1") -> str: - """ - Encode a single header line with quoted-printable (like) encoding. + """Encode a single header line with quoted-printable (like) encoding. Defined in RFC 2045, this 'Q' encoding is similar to quoted-printable, but used specifically for email header fields to allow charsets with mostly 7 @@ -89,8 +80,7 @@ def header_encode(header_bytes: bytes | bytearray, charset: str = "iso-8859-1") """ def body_encode(body: str, maxlinelen: int = 76, eol: str = "\n") -> str: - """ - Encode with quoted-printable, wrapping at maxlinelen characters. + """Encode with quoted-printable, wrapping at maxlinelen characters. Each line of encoded text will end with eol, which defaults to "\\n". Set this to "\\r\\n" if you will be using the result of this function directly @@ -108,15 +98,13 @@ def body_encode(body: str, maxlinelen: int = 76, eol: str = "\n") -> str: """ def decode(encoded: str, eol: str = "\n") -> str: - """ - Decode a quoted-printable string. + """Decode a quoted-printable string. Lines are separated with eol, which defaults to \\n. """ def header_decode(s: str) -> str: - """ - Decode a string encoded with RFC 2045 MIME header 'Q' encoding. + """Decode a string encoded with RFC 2045 MIME header 'Q' encoding. This function does not parse a full MIME header value encoded with quoted-printable (like =?iso-8859-1?q?Hello_World?=) -- please use diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/email/utils.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/email/utils.pyi index aecf1e312c..707b1d8c6f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/email/utils.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/email/utils.pyi @@ -32,8 +32,7 @@ __all__ = [ _PDTZ: TypeAlias = tuple[int, int, int, int, int, int, int, int, int, int | None] def quote(str: str) -> str: - """ - Prepare string to be used in a quoted string. + """Prepare string to be used in a quoted string. Turns backslash and double quote characters into quoted pairs. These are the only characters that need to be quoted inside a quoted string. @@ -41,14 +40,11 @@ def quote(str: str) -> str: """ def unquote(str: str) -> str: - """ - Remove quotes from a string. - """ + """Remove quotes from a string.""" # `strict` parameter added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 def parseaddr(addr: str | list[str], *, strict: bool = True) -> tuple[str, str]: - """ - Parse addr into its constituent realname and email address parts. + """Parse addr into its constituent realname and email address parts. Return a tuple of realname and email address, unless the parse fails, in which case return a 2-tuple of ('', ''). @@ -57,8 +53,7 @@ def parseaddr(addr: str | list[str], *, strict: bool = True) -> tuple[str, str]: """ def formataddr(pair: tuple[str | None, str], charset: str | Charset = "utf-8") -> str: - """ - The inverse of parseaddr(), this takes a 2-tuple of the form + """The inverse of parseaddr(), this takes a 2-tuple of the form (realname, email_address) and returns the string value suitable for an RFC 2822 From, To or Cc header. @@ -73,8 +68,7 @@ def formataddr(pair: tuple[str | None, str], charset: str | Charset = "utf-8") - # `strict` parameter added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 def getaddresses(fieldvalues: Iterable[str], *, strict: bool = True) -> list[tuple[str, str]]: - """ - Return a list of (REALNAME, EMAIL) or ('','') for each fieldvalue. + """Return a list of (REALNAME, EMAIL) or ('','') for each fieldvalue. When parsing fails for a fieldvalue, a 2-tuple of ('', '') is returned in its place. @@ -84,16 +78,13 @@ def getaddresses(fieldvalues: Iterable[str], *, strict: bool = True) -> list[tup @overload def parsedate(data: None) -> None: - """ - Convert a time string to a time tuple. - """ + """Convert a time string to a time tuple.""" @overload def parsedate(data: str) -> tuple[int, int, int, int, int, int, int, int, int] | None: ... @overload def parsedate_tz(data: None) -> None: - """ - Convert a date string to a time tuple. + """Convert a date string to a time tuple. Accounts for military timezones. """ @@ -111,13 +102,10 @@ else: def parsedate_to_datetime(data: str) -> datetime.datetime: ... def mktime_tz(data: _PDTZ) -> int: - """ - Turn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp. - """ + """Turn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp.""" def formatdate(timeval: float | None = None, localtime: bool = False, usegmt: bool = False) -> str: - """ - Returns a date string as specified by RFC 2822, e.g.: + """Returns a date string as specified by RFC 2822, e.g.: Fri, 09 Nov 2001 01:08:47 -0000 @@ -134,8 +122,7 @@ def formatdate(timeval: float | None = None, localtime: bool = False, usegmt: bo """ def format_datetime(dt: datetime.datetime, usegmt: bool = False) -> str: - """ - Turn a datetime into a date string as specified in RFC 2822. + """Turn a datetime into a date string as specified in RFC 2822. If usegmt is True, dt must be an aware datetime with an offset of zero. In this case 'GMT' will be rendered instead of the normal +0000 required by @@ -144,8 +131,7 @@ def format_datetime(dt: datetime.datetime, usegmt: bool = False) -> str: if sys.version_info >= (3, 14): def localtime(dt: datetime.datetime | None = None) -> datetime.datetime: - """ - Return local time as an aware datetime object. + """Return local time as an aware datetime object. If called without arguments, return current time. Otherwise *dt* argument should be a datetime instance, and it is converted to the @@ -156,8 +142,7 @@ if sys.version_info >= (3, 14): elif sys.version_info >= (3, 12): @overload def localtime(dt: datetime.datetime | None = None) -> datetime.datetime: - """ - Return local time as an aware datetime object. + """Return local time as an aware datetime object. If called without arguments, return current time. Otherwise *dt* argument should be a datetime instance, and it is converted to the @@ -172,8 +157,7 @@ elif sys.version_info >= (3, 12): else: def localtime(dt: datetime.datetime | None = None, isdst: int = -1) -> datetime.datetime: - """ - Return local time as an aware datetime object. + """Return local time as an aware datetime object. If called without arguments, return current time. Otherwise *dt* argument should be a datetime instance, and it is converted to the @@ -187,8 +171,7 @@ else: """ def make_msgid(idstring: str | None = None, domain: str | None = None) -> str: - """ - Returns a string suitable for RFC 2822 compliant Message-ID, e.g: + """Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <142480216486.20800.16526388040877946887@nightshade.la.mastaler.com> @@ -199,13 +182,10 @@ def make_msgid(idstring: str | None = None, domain: str | None = None) -> str: """ def decode_rfc2231(s: str) -> tuple[str | None, str | None, str]: # May return list[str]. See issue #10431 for details. - """ - Decode string according to RFC 2231 - """ + """Decode string according to RFC 2231""" def encode_rfc2231(s: str, charset: str | None = None, language: str | None = None) -> str: - """ - Encode string according to RFC 2231. + """Encode string according to RFC 2231. If neither charset nor language is given, then s is returned as-is. If charset is given but not language, the string is encoded using the empty @@ -214,8 +194,7 @@ def encode_rfc2231(s: str, charset: str | None = None, language: str | None = No def collapse_rfc2231_value(value: _ParamType, errors: str = "replace", fallback_charset: str = "us-ascii") -> str: ... def decode_params(params: list[tuple[str, str]]) -> list[tuple[str, _ParamType]]: - """ - Decode parameters list according to RFC 2231. + """Decode parameters list according to RFC 2231. params is a sequence of 2-tuples containing (param name, string value). """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/encodings/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/encodings/__init__.pyi index d3065c44c6..1f91774416 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/encodings/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/encodings/__init__.pyi @@ -33,8 +33,7 @@ from codecs import CodecInfo class CodecRegistryError(LookupError, SystemError): ... def normalize_encoding(encoding: str | bytes) -> str: - """ - Normalize an encoding name. + """Normalize an encoding name. Normalization works as follows: all non-alphanumeric characters except the dot used for Python package names are diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/encodings/mbcs.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/encodings/mbcs.pyi index 2c2917d63f..3c1fd63c8c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/encodings/mbcs.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/encodings/mbcs.pyi @@ -1,3 +1,13 @@ +""" +Python 'mbcs' Codec for Windows + + +Cloned by Mark Hammond (mhammond@skippinet.com.au) from ascii.py, +which was written by Marc-Andre Lemburg (mal@lemburg.com). + +(c) Copyright CNRI, All Rights Reserved. NO WARRANTY. +""" + import codecs import sys from _typeshed import ReadableBuffer diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/encodings/oem.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/encodings/oem.pyi index 376c12c445..28697d1806 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/encodings/oem.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/encodings/oem.pyi @@ -1,3 +1,7 @@ +""" +Python 'oem' Codec for Windows +""" + import codecs import sys from _typeshed import ReadableBuffer diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/encodings/punycode.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/encodings/punycode.pyi index 7d2c0bc995..ef9bedd19d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/encodings/punycode.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/encodings/punycode.pyi @@ -8,18 +8,13 @@ import codecs from typing import Literal def segregate(str: str) -> tuple[bytes, list[int]]: - """ - 3.1 Basic code point segregation - """ + """3.1 Basic code point segregation""" def selective_len(str: str, max: int) -> int: - """ - Return the length of str, considering only characters below max. - """ + """Return the length of str, considering only characters below max.""" def selective_find(str: str, char: str, index: int, pos: int) -> tuple[int, int]: - """ - Return a pair (index, pos), indicating the next occurrence of + """Return a pair (index, pos), indicating the next occurrence of char in str. index is the position of the character considering only ordinals up to and including char, and pos is the position in the full string. index/pos is the starting position in the full @@ -27,35 +22,25 @@ def selective_find(str: str, char: str, index: int, pos: int) -> tuple[int, int] """ def insertion_unsort(str: str, extended: list[int]) -> list[int]: - """ - 3.2 Insertion unsort coding - """ + """3.2 Insertion unsort coding""" def T(j: int, bias: int) -> int: ... digits: Literal[b"abcdefghijklmnopqrstuvwxyz0123456789"] def generate_generalized_integer(N: int, bias: int) -> bytes: - """ - 3.3 Generalized variable-length integers - """ + """3.3 Generalized variable-length integers""" def adapt(delta: int, first: bool, numchars: int) -> int: ... def generate_integers(baselen: int, deltas: list[int]) -> bytes: - """ - 3.4 Bias adaptation - """ + """3.4 Bias adaptation""" def punycode_encode(text: str) -> bytes: ... def decode_generalized_number(extended: bytes, extpos: int, bias: int, errors: str) -> tuple[int, int | None]: - """ - 3.3 Generalized variable-length integers - """ + """3.3 Generalized variable-length integers""" def insertion_sort(base: str, extended: bytes, errors: str) -> str: - """ - 3.2 Insertion sort coding - """ + """3.2 Insertion sort coding""" def punycode_decode(text: memoryview | bytes | bytearray | str, errors: str) -> str: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/encodings/utf_32.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/encodings/utf_32.pyi index f294f44802..9b4533a2af 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/encodings/utf_32.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/encodings/utf_32.pyi @@ -1,4 +1,5 @@ """ + Python 'utf-32' Codec """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/encodings/utf_32_be.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/encodings/utf_32_be.pyi index 360d0f69fe..053c4ec060 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/encodings/utf_32_be.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/encodings/utf_32_be.pyi @@ -1,4 +1,5 @@ """ + Python 'utf-32-be' Codec """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/encodings/utf_32_le.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/encodings/utf_32_le.pyi index 40149d98d2..03fe8c9854 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/encodings/utf_32_le.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/encodings/utf_32_le.pyi @@ -1,4 +1,5 @@ """ + Python 'utf-32-le' Codec """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/ensurepip/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/ensurepip/__init__.pyi index c203a2e65b..84910ee849 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/ensurepip/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/ensurepip/__init__.pyi @@ -1,9 +1,7 @@ __all__ = ["version", "bootstrap"] def version() -> str: - """ - Returns a string specifying the bundled version of pip. - """ + """Returns a string specifying the bundled version of pip.""" def bootstrap( *, @@ -14,8 +12,7 @@ def bootstrap( default_pip: bool = False, verbosity: int = 0, ) -> None: - """ - Bootstrap pip into the current Python installation (or the given root + """Bootstrap pip into the current Python installation (or the given root directory). Note that calling this function will alter both sys.path and os.environ. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/enum.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/enum.pyi index 241fcda289..63a785ce26 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/enum.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/enum.pyi @@ -57,24 +57,19 @@ _Signature: TypeAlias = Any # TODO: Unable to import Signature from inspect mod if sys.version_info >= (3, 11): class nonmember(Generic[_EnumMemberT]): - """ - Protects item from becoming an Enum member during class creation. - """ + """Protects item from becoming an Enum member during class creation.""" value: _EnumMemberT def __init__(self, value: _EnumMemberT) -> None: ... class member(Generic[_EnumMemberT]): - """ - Forces item to become an Enum member during class creation. - """ + """Forces item to become an Enum member during class creation.""" value: _EnumMemberT def __init__(self, value: _EnumMemberT) -> None: ... class _EnumDict(dict[str, Any]): - """ - Track enum member order and ensure member names are not reused. + """Track enum member order and ensure member names are not reused. EnumType will use the names found in self._member_names as the enumeration member names. @@ -86,8 +81,7 @@ class _EnumDict(dict[str, Any]): def __init__(self) -> None: ... def __setitem__(self, key: str, value: Any) -> None: - """ - Changes anything not dundered or not a descriptor. + """Changes anything not dundered or not a descriptor. If an enum member name is used twice, an error is raised; duplicate values are not checked for. @@ -113,9 +107,7 @@ if sys.version_info >= (3, 13): # Structurally: Iterable[T], Reversible[T], Container[T] where T is the enum itself class EnumMeta(type): - """ - Metaclass for Enum - """ + """Metaclass for Enum""" if sys.version_info >= (3, 11): def __new__( @@ -136,18 +128,13 @@ class EnumMeta(type): @classmethod def __prepare__(metacls, cls: str, bases: tuple[type, ...], **kwds: Any) -> _EnumDict: ... # type: ignore[override] def __iter__(self: type[_EnumMemberT]) -> Iterator[_EnumMemberT]: - """ - Return members in definition order. - """ + """Return members in definition order.""" def __reversed__(self: type[_EnumMemberT]) -> Iterator[_EnumMemberT]: - """ - Return members in reverse definition order. - """ + """Return members in reverse definition order.""" if sys.version_info >= (3, 12): def __contains__(self: type[Any], value: object) -> bool: - """ - Return True if `value` is in `cls`. + """Return True if `value` is in `cls`. `value` is in `cls` if: 1) `value` is a member of `cls`, or @@ -156,8 +143,7 @@ class EnumMeta(type): """ elif sys.version_info >= (3, 11): def __contains__(self: type[Any], member: object) -> bool: - """ - Return True if `value` is in `cls`. + """Return True if `value` is in `cls`. `value` is in `cls` if: 1) `value` is a member of `cls`, or @@ -166,8 +152,7 @@ class EnumMeta(type): """ elif sys.version_info >= (3, 10): def __contains__(self: type[Any], obj: object) -> bool: - """ - Return True if `value` is in `cls`. + """Return True if `value` is in `cls`. `value` is in `cls` if: 1) `value` is a member of `cls`, or @@ -176,8 +161,7 @@ class EnumMeta(type): """ else: def __contains__(self: type[Any], member: object) -> bool: - """ - Return True if `value` is in `cls`. + """Return True if `value` is in `cls`. `value` is in `cls` if: 1) `value` is a member of `cls`, or @@ -186,36 +170,28 @@ class EnumMeta(type): """ def __getitem__(self: type[_EnumMemberT], name: str) -> _EnumMemberT: - """ - Return the member matching `name`. - """ + """Return the member matching `name`.""" @_builtins_property def __members__(self: type[_EnumMemberT]) -> types.MappingProxyType[str, _EnumMemberT]: - """ - Returns a mapping of member name->value. + """Returns a mapping of member name->value. This mapping lists all enum members, including aliases. Note that this is a read-only view of the internal mapping. """ def __len__(self) -> int: - """ - Return the number of members (no aliases) - """ + """Return the number of members (no aliases)""" def __bool__(self) -> Literal[True]: - """ - classes/types should always be True. - """ + """classes/types should always be True.""" def __dir__(self) -> list[str]: ... # Overload 1: Value lookup on an already existing enum class (simple case) @overload def __call__(cls: type[_EnumMemberT], value: Any, names: None = None) -> _EnumMemberT: - """ - Either returns an existing member, or creates a new enum class. + """Either returns an existing member, or creates a new enum class. This method is used both when an enum class is given a value to match to an enumeration member (i.e. Color(3)) and for the functional API @@ -254,8 +230,7 @@ class EnumMeta(type): start: int = 1, boundary: FlagBoundary | None = None, ) -> type[Enum]: - """ - Either returns an existing member, or creates a new enum class. + """Either returns an existing member, or creates a new enum class. This method is used both when an enum class is given a value to match to an enumeration member (i.e. Color(3)) and for the functional API @@ -292,8 +267,7 @@ class EnumMeta(type): type: type | None = None, start: int = 1, ) -> type[Enum]: - """ - Either returns an existing member, or creates a new enum class. + """Either returns an existing member, or creates a new enum class. This method is used both when an enum class is given a value to match to an enumeration member (i.e. Color(3)) and for the functional API @@ -328,8 +302,7 @@ class EnumMeta(type): if sys.version_info >= (3, 12): @overload def __call__(cls: type[_EnumMemberT], value: Any, *values: Any) -> _EnumMemberT: - """ - Either returns an existing member, or creates a new enum class. + """Either returns an existing member, or creates a new enum class. This method is used both when an enum class is given a value to match to an enumeration member (i.e. Color(3)) and for the functional API @@ -367,8 +340,7 @@ if sys.version_info >= (3, 11): EnumType = EnumMeta class property(types.DynamicClassAttribute): - """ - This is a descriptor, used to define attributes that act differently + """This is a descriptor, used to define attributes that act differently when accessed through an enum member and through an enum class. Instance access is the same as property(), but access to an attribute through the enum class will instead look in the class' _member_map_ for @@ -385,8 +357,7 @@ else: _magic_enum_attr = types.DynamicClassAttribute class Enum(metaclass=EnumMeta): - """ - Create a collection of name/value pairs. + """Create a collection of name/value pairs. Example enumeration: @@ -426,15 +397,11 @@ class Enum(metaclass=EnumMeta): @_magic_enum_attr def name(self) -> str: - """ - The name of the Enum member. - """ + """The name of the Enum member.""" @_magic_enum_attr def value(self) -> Any: - """ - The value of the Enum member. - """ + """The value of the Enum member.""" _name_: str _value_: Any _ignore_: str | list[str] @@ -444,8 +411,7 @@ class Enum(metaclass=EnumMeta): def _missing_(cls, value: object) -> Any: ... @staticmethod def _generate_next_value_(name: str, start: int, count: int, last_values: list[Any]) -> Any: - """ - Generate the next value when not given. + """Generate the next value when not given. name: the name of the member start: the initial start value or None @@ -459,9 +425,7 @@ class Enum(metaclass=EnumMeta): # and in practice using `object` here has the same effect as using `Any`. def __new__(cls, value: object) -> Self: ... def __dir__(self) -> list[str]: - """ - Returns public methods and other interesting attributes. - """ + """Returns public methods and other interesting attributes.""" def __hash__(self) -> int: ... def __format__(self, format_spec: str) -> str: ... @@ -475,9 +439,7 @@ class Enum(metaclass=EnumMeta): if sys.version_info >= (3, 11): class ReprEnum(Enum): - """ - Only changes the repr(), leaving str() and format() to the mixed-in type. - """ + """Only changes the repr(), leaving str() and format() to the mixed-in type.""" if sys.version_info >= (3, 11): _IntEnumBase = ReprEnum @@ -485,49 +447,35 @@ else: _IntEnumBase = Enum class IntEnum(int, _IntEnumBase): - """ - Enum where members are also (and must be) ints - """ + """Enum where members are also (and must be) ints""" _value_: int @_magic_enum_attr def value(self) -> int: - """ - The value of the Enum member. - """ + """The value of the Enum member.""" def __new__(cls, value: int) -> Self: ... def unique(enumeration: _EnumerationT) -> _EnumerationT: - """ - Class decorator for enumerations ensuring unique member values. - """ + """Class decorator for enumerations ensuring unique member values.""" _auto_null: Any class Flag(Enum): - """ - Support for flags - """ + """Support for flags""" _name_: str | None # type: ignore[assignment] _value_: int @_magic_enum_attr def name(self) -> str | None: # type: ignore[override] - """ - The name of the Enum member. - """ + """The name of the Enum member.""" @_magic_enum_attr def value(self) -> int: - """ - The value of the Enum member. - """ + """The value of the Enum member.""" def __contains__(self, other: Self) -> bool: - """ - Returns True if self has at least the same flags set as other. - """ + """Returns True if self has at least the same flags set as other.""" def __bool__(self) -> bool: ... def __or__(self, other: Self) -> Self: ... @@ -536,9 +484,7 @@ class Flag(Enum): def __invert__(self) -> Self: ... if sys.version_info >= (3, 11): def __iter__(self) -> Iterator[Self]: - """ - Returns flags in definition order. - """ + """Returns flags in definition order.""" def __len__(self) -> int: ... __ror__ = __or__ @@ -547,28 +493,20 @@ class Flag(Enum): if sys.version_info >= (3, 11): class StrEnum(str, ReprEnum): - """ - Enum where members are also (and must be) strings - """ + """Enum where members are also (and must be) strings""" def __new__(cls, value: str) -> Self: ... _value_: str @_magic_enum_attr def value(self) -> str: - """ - The value of the Enum member. - """ + """The value of the Enum member.""" @staticmethod def _generate_next_value_(name: str, start: int, count: int, last_values: list[str]) -> str: - """ - Return the lower-cased version of the member name. - """ + """Return the lower-cased version of the member name.""" class EnumCheck(StrEnum): - """ - various conditions to check an enumeration for - """ + """various conditions to check an enumeration for""" CONTINUOUS = "no skipped integer values" NAMED_FLAGS = "multi-flag aliases may not contain unnamed flags" @@ -579,16 +517,13 @@ if sys.version_info >= (3, 11): UNIQUE = EnumCheck.UNIQUE class verify: - """ - Check an enumeration for various constraints. (see EnumCheck) - """ + """Check an enumeration for various constraints. (see EnumCheck)""" def __init__(self, *checks: EnumCheck) -> None: ... def __call__(self, enumeration: _EnumerationT) -> _EnumerationT: ... class FlagBoundary(StrEnum): - """ - control how out of range values are handled + """control how out of range values are handled "strict" -> error is raised [default for Flag] "conform" -> extra bits are discarded "eject" -> lose flag status @@ -606,27 +541,22 @@ if sys.version_info >= (3, 11): KEEP = FlagBoundary.KEEP def global_str(self: Enum) -> str: - """ - use enum_name instead of class.enum_name - """ + """use enum_name instead of class.enum_name""" def global_enum(cls: _EnumerationT, update_str: bool = False) -> _EnumerationT: - """ - decorator that makes the repr() of an enum member reference its module + """decorator that makes the repr() of an enum member reference its module instead of its class; also exports all members to the enum's module's global namespace """ def global_enum_repr(self: Enum) -> str: - """ - use module.enum_name instead of class.enum_name + """use module.enum_name instead of class.enum_name the module is the last module in case of a multi-module name """ def global_flag_repr(self: Flag) -> str: - """ - use module.flag_name instead of class.flag_name + """use module.flag_name instead of class.flag_name the module is the last module in case of a multi-module name """ @@ -634,9 +564,7 @@ if sys.version_info >= (3, 11): if sys.version_info >= (3, 11): # The body of the class is the same, but the base classes are different. class IntFlag(int, ReprEnum, Flag, boundary=KEEP): # type: ignore[misc] # complaints about incompatible bases - """ - Support for integer-based Flags - """ + """Support for integer-based Flags""" def __new__(cls, value: int) -> Self: ... def __or__(self, other: int) -> Self: ... @@ -649,9 +577,7 @@ if sys.version_info >= (3, 11): else: class IntFlag(int, Flag): # type: ignore[misc] # complaints about incompatible bases - """ - Support for integer-based Flags - """ + """Support for integer-based Flags""" def __new__(cls, value: int) -> Self: ... def __or__(self, other: int) -> Self: ... @@ -663,9 +589,7 @@ else: __rxor__ = __xor__ class auto: - """ - Instances are replaced with an appropriate value in Enum class suites. - """ + """Instances are replaced with an appropriate value in Enum class suites.""" _value_: Any @_magic_enum_attr @@ -678,9 +602,7 @@ class auto: # Ideally type checkers would special case auto enough to handle this, # but until then this is a slightly inaccurate helping hand. def __or__(self, other: int | Self) -> Self: - """ - Return self|value. - """ + """Return self|value.""" def __and__(self, other: int | Self) -> Self: ... def __xor__(self, other: int | Self) -> Self: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/faulthandler.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/faulthandler.pyi index cb465cd0a3..2049374456 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/faulthandler.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/faulthandler.pyi @@ -6,49 +6,32 @@ import sys from _typeshed import FileDescriptorLike def cancel_dump_traceback_later() -> None: - """ - Cancel the previous call to dump_traceback_later(). - """ + """Cancel the previous call to dump_traceback_later().""" def disable() -> None: - """ - Disable the fault handler. - """ + """Disable the fault handler.""" def dump_traceback(file: FileDescriptorLike = ..., all_threads: bool = ...) -> None: - """ - Dump the traceback of the current thread, or of all threads if all_threads is True, into file. - """ + """Dump the traceback of the current thread, or of all threads if all_threads is True, into file.""" if sys.version_info >= (3, 14): def dump_c_stack(file: FileDescriptorLike = ...) -> None: - """ - Dump the C stack of the current thread. - """ + """Dump the C stack of the current thread.""" def dump_traceback_later(timeout: float, repeat: bool = ..., file: FileDescriptorLike = ..., exit: bool = ...) -> None: - """ - Dump the traceback of all threads in timeout seconds, + """Dump the traceback of all threads in timeout seconds, or each timeout seconds if repeat is True. If exit is True, call _exit(1) which is not safe. """ def enable(file: FileDescriptorLike = ..., all_threads: bool = ...) -> None: - """ - Enable the fault handler. - """ + """Enable the fault handler.""" def is_enabled() -> bool: - """ - Check if the handler is enabled. - """ + """Check if the handler is enabled.""" if sys.platform != "win32": def register(signum: int, file: FileDescriptorLike = ..., all_threads: bool = ..., chain: bool = ...) -> None: - """ - Register a handler for the signal 'signum': dump the traceback of the current thread, or of all threads if all_threads is True, into file. - """ + """Register a handler for the signal 'signum': dump the traceback of the current thread, or of all threads if all_threads is True, into file.""" def unregister(signum: int, /) -> None: - """ - Unregister the handler of the signal 'signum' registered by register(). - """ + """Unregister the handler of the signal 'signum' registered by register().""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/fcntl.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/fcntl.pyi index 5e766cd560..43182de9ea 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/fcntl.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/fcntl.pyi @@ -145,8 +145,7 @@ if sys.platform != "win32": @overload def fcntl(fd: FileDescriptorLike, cmd: int, arg: int = 0, /) -> int: - """ - Perform the operation `cmd` on file descriptor fd. + """Perform the operation `cmd` on file descriptor fd. The values used for `cmd` are operating system dependent, and are available as constants in the fcntl module, using the same names as used in @@ -164,8 +163,7 @@ if sys.platform != "win32": # If arg is an int, return int @overload def ioctl(fd: FileDescriptorLike, request: int, arg: int = 0, mutate_flag: bool = True, /) -> int: - """ - Perform the operation `request` on file descriptor `fd`. + """Perform the operation `request` on file descriptor `fd`. The values used for `request` are operating system dependent, and are available as constants in the fcntl or termios library modules, using the same names as @@ -206,16 +204,14 @@ if sys.platform != "win32": @overload def ioctl(fd: FileDescriptorLike, request: int, arg: Buffer, mutate_flag: bool = True, /) -> Any: ... def flock(fd: FileDescriptorLike, operation: int, /) -> None: - """ - Perform the lock operation `operation` on file descriptor `fd`. + """Perform the lock operation `operation` on file descriptor `fd`. See the Unix manual page for flock(2) for details (On some systems, this function is emulated using fcntl()). """ def lockf(fd: FileDescriptorLike, cmd: int, len: int = 0, start: int = 0, whence: int = 0, /) -> Any: - """ - A wrapper around the fcntl() locking calls. + """A wrapper around the fcntl() locking calls. `fd` is the file descriptor of the file to lock or unlock, and operation is one of the following values: diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/filecmp.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/filecmp.pyi index a5ed7d6e17..83194e2f11 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/filecmp.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/filecmp.pyi @@ -22,8 +22,7 @@ DEFAULT_IGNORES: list[str] BUFSIZE: Final = 8192 def cmp(f1: StrOrBytesPath, f2: StrOrBytesPath, shallow: bool | Literal[0, 1] = True) -> bool: - """ - Compare two files. + """Compare two files. Arguments: @@ -47,8 +46,7 @@ def cmp(f1: StrOrBytesPath, f2: StrOrBytesPath, shallow: bool | Literal[0, 1] = def cmpfiles( a: GenericPath[AnyStr], b: GenericPath[AnyStr], common: Iterable[GenericPath[AnyStr]], shallow: bool | Literal[0, 1] = True ) -> tuple[list[AnyStr], list[AnyStr], list[AnyStr]]: - """ - Compare common files in two directories. + """Compare common files in two directories. a, b -- directory names common -- list of file names found in both directories @@ -61,8 +59,7 @@ def cmpfiles( """ class dircmp(Generic[AnyStr]): - """ - A class that manages the comparison of 2 directories. + """A class that manages the comparison of 2 directories. dircmp(a, b, ignore=None, hide=None, *, shallow=True) A and B are directories. @@ -146,13 +143,10 @@ class dircmp(Generic[AnyStr]): def phase4(self) -> None: ... def phase4_closure(self) -> None: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ def clear_cache() -> None: - """ - Clear the filecmp cache. - """ + """Clear the filecmp cache.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/fileinput.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/fileinput.pyi index b8cc5bb6ea..3c603a7537 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/fileinput.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/fileinput.pyi @@ -110,8 +110,7 @@ if sys.version_info >= (3, 10): encoding: str | None = None, errors: str | None = None, ) -> FileInput[str]: - """ - Return an instance of the FileInput class, which can be iterated. + """Return an instance of the FileInput class, which can be iterated. The parameters are passed to the constructor of the FileInput class. The returned instance, in addition to being an iterator, @@ -152,8 +151,7 @@ else: mode: _TextMode = "r", openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = None, ) -> FileInput[str]: - """ - Return an instance of the FileInput class, which can be iterated. + """Return an instance of the FileInput class, which can be iterated. The parameters are passed to the constructor of the FileInput class. The returned instance, in addition to being an iterator, @@ -180,13 +178,10 @@ else: ) -> FileInput[Any]: ... def close() -> None: - """ - Close the sequence. - """ + """Close the sequence.""" def nextfile() -> None: - """ - Close the current file so that the next iteration will read the first + """Close the current file so that the next iteration will read the first line from the next file (if any); lines not read from the file will not count towards the cumulative line count. The filename is not changed until after the first line of the next file has been read. @@ -196,46 +191,39 @@ def nextfile() -> None: """ def filename() -> str: - """ - Return the name of the file currently being read. + """Return the name of the file currently being read. Before the first line has been read, returns None. """ def lineno() -> int: - """ - Return the cumulative line number of the line that has just been read. + """Return the cumulative line number of the line that has just been read. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line. """ def filelineno() -> int: - """ - Return the line number in the current file. Before the first line + """Return the line number in the current file. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line within the file. """ def fileno() -> int: - """ - Return the file number of the current file. When no file is currently + """Return the file number of the current file. When no file is currently opened, returns -1. """ def isfirstline() -> bool: - """ - Returns true the line just read is the first line of its file, + """Returns true the line just read is the first line of its file, otherwise returns false. """ def isstdin() -> bool: - """ - Returns true if the last line was read from sys.stdin, + """Returns true if the last line was read from sys.stdin, otherwise returns false. """ class FileInput(Generic[AnyStr]): - """ - FileInput([files[, inplace[, backup]]], *, mode=None, openhook=None) + """FileInput([files[, inplace[, backup]]], *, mode=None, openhook=None) Class FileInput is the implementation of the module; its methods filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(), @@ -339,8 +327,7 @@ class FileInput(Generic[AnyStr]): def isfirstline(self) -> bool: ... def isstdin(self) -> bool: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/fnmatch.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/fnmatch.pyi index b170cf789d..f5a7a31a60 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/fnmatch.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/fnmatch.pyi @@ -20,8 +20,7 @@ if sys.version_info >= (3, 14): __all__ += ["filterfalse"] def fnmatch(name: AnyStr, pat: AnyStr) -> bool: - """ - Test whether FILENAME matches PATTERN. + """Test whether FILENAME matches PATTERN. Patterns are Unix shell style: @@ -37,27 +36,21 @@ def fnmatch(name: AnyStr, pat: AnyStr) -> bool: """ def fnmatchcase(name: AnyStr, pat: AnyStr) -> bool: - """ - Test whether FILENAME matches PATTERN, including case. + """Test whether FILENAME matches PATTERN, including case. This is a version of fnmatch() which doesn't case-normalize its arguments. """ def filter(names: Iterable[AnyStr], pat: AnyStr) -> list[AnyStr]: - """ - Construct a list from those elements of the iterable NAMES that match PAT. - """ + """Construct a list from those elements of the iterable NAMES that match PAT.""" def translate(pat: str) -> str: - """ - Translate a shell PATTERN to a regular expression. + """Translate a shell PATTERN to a regular expression. There is no way to quote meta-characters. """ if sys.version_info >= (3, 14): def filterfalse(names: Iterable[AnyStr], pat: AnyStr) -> list[AnyStr]: - """ - Construct a list from those elements of the iterable NAMES that do not match PAT. - """ + """Construct a list from those elements of the iterable NAMES that do not match PAT.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/formatter.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/formatter.pyi index 7af1819e4f..63e0b0afae 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/formatter.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/formatter.pyi @@ -28,8 +28,7 @@ _FontType: TypeAlias = tuple[str, bool, bool, bool] _StylesType: TypeAlias = tuple[Any, ...] class NullFormatter: - """ - A formatter which does nothing. + """A formatter which does nothing. If the writer parameter is omitted, a NullWriter instance is created. No methods of the writer are called by NullFormatter instances. @@ -59,8 +58,7 @@ class NullFormatter: def assert_line_data(self, flag: int = 1) -> None: ... class AbstractFormatter: - """ - The standard formatter. + """The standard formatter. This implementation has demonstrated wide applicability to many writers, and may be used directly in most circumstances. It has been used to @@ -103,8 +101,7 @@ class AbstractFormatter: def assert_line_data(self, flag: int = 1) -> None: ... class NullWriter: - """ - Minimal writer interface to use in testing & inheritance. + """Minimal writer interface to use in testing & inheritance. A writer which only provides the interface definition; no actions are taken on any methods. This should be the base class for all writers @@ -125,16 +122,14 @@ class NullWriter: def send_literal_data(self, data: str) -> None: ... class AbstractWriter(NullWriter): - """ - A writer which can be used in debugging formatters, but not much else. + """A writer which can be used in debugging formatters, but not much else. Each method simply announces itself by printing its name and arguments on standard output. """ class DumbWriter(NullWriter): - """ - Simple writer class which writes output on the file object passed in + """Simple writer class which writes output on the file object passed in as the file parameter or, if file is omitted, on standard output. The output is simply word-wrapped to the number of columns specified by the maxcol parameter. This class is suitable for reflowing a sequence diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/fractions.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/fractions.pyi index 40cc5fe604..c7a071680a 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/fractions.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/fractions.pyi @@ -17,8 +17,7 @@ class _ConvertibleToIntegerRatio(Protocol): def as_integer_ratio(self) -> tuple[int | Rational, int | Rational]: ... class Fraction(Rational): - """ - This class implements rational numbers. + """This class implements rational numbers. In the two-argument form of the constructor, Fraction(8, 6) will produce a rational number equivalent to 4/3. Both arguments must @@ -39,8 +38,7 @@ class Fraction(Rational): @overload def __new__(cls, numerator: int | Rational = 0, denominator: int | Rational | None = None) -> Self: - """ - Constructs a Rational. + """Constructs a Rational. Takes a string like '3/2' or '1.5', another Rational instance, a numerator/denominator pair, or a float. @@ -76,8 +74,7 @@ class Fraction(Rational): if sys.version_info >= (3, 14): @overload def __new__(cls, numerator: _ConvertibleToIntegerRatio) -> Self: - """ - Constructs a Rational. + """Constructs a Rational. Takes a string like '3/2' or '1.5', another Rational instance, a numerator/denominator pair, or a float. @@ -109,21 +106,17 @@ class Fraction(Rational): @classmethod def from_float(cls, f: float) -> Self: - """ - Converts a finite float to a rational number, exactly. + """Converts a finite float to a rational number, exactly. Beware that Fraction.from_float(0.3) != Fraction(3, 10). """ @classmethod def from_decimal(cls, dec: Decimal) -> Self: - """ - Converts a finite Decimal instance to a rational number, exactly. - """ + """Converts a finite Decimal instance to a rational number, exactly.""" def limit_denominator(self, max_denominator: int = 1000000) -> Fraction: - """ - Closest Fraction to self with denominator at most max_denominator. + """Closest Fraction to self with denominator at most max_denominator. >>> Fraction('3.141592653589793').limit_denominator(10) Fraction(22, 7) @@ -134,16 +127,13 @@ class Fraction(Rational): """ def as_integer_ratio(self) -> tuple[int, int]: - """ - Return a pair of integers, whose ratio is equal to the original Fraction. + """Return a pair of integers, whose ratio is equal to the original Fraction. The ratio is in lowest terms and has a positive denominator. """ if sys.version_info >= (3, 12): def is_integer(self) -> bool: - """ - Return True if the Fraction is an integer. - """ + """Return True if the Fraction is an integer.""" @property def numerator(a) -> int: ... @@ -151,9 +141,7 @@ class Fraction(Rational): def denominator(a) -> int: ... @overload def __add__(a, b: int | Fraction) -> Fraction: - """ - a + b - """ + """a + b""" @overload def __add__(a, b: float) -> float: ... @@ -161,9 +149,7 @@ class Fraction(Rational): def __add__(a, b: complex) -> complex: ... @overload def __radd__(b, a: int | Fraction) -> Fraction: - """ - a + b - """ + """a + b""" @overload def __radd__(b, a: float) -> float: ... @@ -171,9 +157,7 @@ class Fraction(Rational): def __radd__(b, a: complex) -> complex: ... @overload def __sub__(a, b: int | Fraction) -> Fraction: - """ - a - b - """ + """a - b""" @overload def __sub__(a, b: float) -> float: ... @@ -181,9 +165,7 @@ class Fraction(Rational): def __sub__(a, b: complex) -> complex: ... @overload def __rsub__(b, a: int | Fraction) -> Fraction: - """ - a - b - """ + """a - b""" @overload def __rsub__(b, a: float) -> float: ... @@ -191,9 +173,7 @@ class Fraction(Rational): def __rsub__(b, a: complex) -> complex: ... @overload def __mul__(a, b: int | Fraction) -> Fraction: - """ - a * b - """ + """a * b""" @overload def __mul__(a, b: float) -> float: ... @@ -201,9 +181,7 @@ class Fraction(Rational): def __mul__(a, b: complex) -> complex: ... @overload def __rmul__(b, a: int | Fraction) -> Fraction: - """ - a * b - """ + """a * b""" @overload def __rmul__(b, a: float) -> float: ... @@ -211,9 +189,7 @@ class Fraction(Rational): def __rmul__(b, a: complex) -> complex: ... @overload def __truediv__(a, b: int | Fraction) -> Fraction: - """ - a / b - """ + """a / b""" @overload def __truediv__(a, b: float) -> float: ... @@ -221,9 +197,7 @@ class Fraction(Rational): def __truediv__(a, b: complex) -> complex: ... @overload def __rtruediv__(b, a: int | Fraction) -> Fraction: - """ - a / b - """ + """a / b""" @overload def __rtruediv__(b, a: float) -> float: ... @@ -231,57 +205,44 @@ class Fraction(Rational): def __rtruediv__(b, a: complex) -> complex: ... @overload def __floordiv__(a, b: int | Fraction) -> int: - """ - a // b - """ + """a // b""" @overload def __floordiv__(a, b: float) -> float: ... @overload def __rfloordiv__(b, a: int | Fraction) -> int: - """ - a // b - """ + """a // b""" @overload def __rfloordiv__(b, a: float) -> float: ... @overload def __mod__(a, b: int | Fraction) -> Fraction: - """ - a % b - """ + """a % b""" @overload def __mod__(a, b: float) -> float: ... @overload def __rmod__(b, a: int | Fraction) -> Fraction: - """ - a % b - """ + """a % b""" @overload def __rmod__(b, a: float) -> float: ... @overload def __divmod__(a, b: int | Fraction) -> tuple[int, Fraction]: - """ - (a // b, a % b) - """ + """(a // b, a % b)""" @overload def __divmod__(a, b: float) -> tuple[float, Fraction]: ... @overload def __rdivmod__(a, b: int | Fraction) -> tuple[int, Fraction]: - """ - (a // b, a % b) - """ + """(a // b, a % b)""" @overload def __rdivmod__(a, b: float) -> tuple[float, Fraction]: ... if sys.version_info >= (3, 14): @overload def __pow__(a, b: int, modulo: None = None) -> Fraction: - """ - a ** b + """a ** b If b is not an integer, the result will be a float or complex since roots are generally irrational. If b is an integer, the @@ -295,8 +256,7 @@ class Fraction(Rational): else: @overload def __pow__(a, b: int) -> Fraction: - """ - a ** b + """a ** b If b is not an integer, the result will be a float or complex since roots are generally irrational. If b is an integer, the @@ -310,56 +270,39 @@ class Fraction(Rational): if sys.version_info >= (3, 14): @overload def __rpow__(b, a: float | Fraction, modulo: None = None) -> float: - """ - a ** b - """ + """a ** b""" @overload def __rpow__(b, a: complex, modulo: None = None) -> complex: ... else: @overload def __rpow__(b, a: float | Fraction) -> float: - """ - a ** b - """ + """a ** b""" @overload def __rpow__(b, a: complex) -> complex: ... def __pos__(a) -> Fraction: - """ - +a: Coerces a subclass instance to Fraction - """ + """+a: Coerces a subclass instance to Fraction""" def __neg__(a) -> Fraction: - """ - -a - """ + """-a""" def __abs__(a) -> Fraction: - """ - abs(a) - """ + """abs(a)""" def __trunc__(a) -> int: - """ - math.trunc(a) - """ + """math.trunc(a)""" def __floor__(a) -> int: - """ - math.floor(a) - """ + """math.floor(a)""" def __ceil__(a) -> int: - """ - math.ceil(a) - """ + """math.ceil(a)""" @overload def __round__(self, ndigits: None = None) -> int: - """ - round(self, ndigits) + """round(self, ndigits) Rounds half toward even. """ @@ -367,70 +310,47 @@ class Fraction(Rational): @overload def __round__(self, ndigits: int) -> Fraction: ... def __hash__(self) -> int: # type: ignore[override] - """ - hash(self) - """ + """hash(self)""" def __eq__(a, b: object) -> bool: - """ - a == b - """ + """a == b""" def __lt__(a, b: _ComparableNum) -> bool: - """ - a < b - """ + """a < b""" def __gt__(a, b: _ComparableNum) -> bool: - """ - a > b - """ + """a > b""" def __le__(a, b: _ComparableNum) -> bool: - """ - a <= b - """ + """a <= b""" def __ge__(a, b: _ComparableNum) -> bool: - """ - a >= b - """ + """a >= b""" def __bool__(a) -> bool: - """ - a != 0 - """ + """a != 0""" def __copy__(self) -> Self: ... def __deepcopy__(self, memo: Any) -> Self: ... if sys.version_info >= (3, 11): def __int__(a, _index: Callable[[SupportsIndex], int] = ...) -> int: - """ - int(a) - """ + """int(a)""" # Not actually defined within fractions.py, but provides more useful # overrides @property def real(self) -> Fraction: - """ - Real numbers are their real component. - """ + """Real numbers are their real component.""" @property def imag(self) -> Literal[0]: - """ - Real numbers have no imaginary component. - """ + """Real numbers have no imaginary component.""" def conjugate(self) -> Fraction: - """ - Conjugate is a no-op for Reals. - """ + """Conjugate is a no-op for Reals.""" if sys.version_info >= (3, 14): @classmethod def from_number(cls, number: float | Rational | _ConvertibleToIntegerRatio) -> Self: - """ - Converts a finite real number to a rational number, exactly. + """Converts a finite real number to a rational number, exactly. Beware that Fraction.from_number(0.3) != Fraction(3, 10). """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/ftplib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/ftplib.pyi index 562b19a30e..baf709684b 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/ftplib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/ftplib.pyi @@ -55,8 +55,7 @@ class error_proto(Error): ... all_errors: tuple[type[Exception], ...] class FTP: - """ - An FTP client class. + """An FTP client class. To create a connection, call the class using these arguments: host, user, passwd, acct, timeout, source_address, encoding @@ -107,16 +106,14 @@ class FTP: *, encoding: str = "utf-8", ) -> None: - """ - Initialization method (called by class instantiation). + """Initialization method (called by class instantiation). Initialize host to localhost, port to standard ftp port. Optional arguments are host (for connect()), and user, passwd, acct (for login()). """ def connect(self, host: str = "", port: int = 0, timeout: float = -999, source_address: tuple[str, int] | None = None) -> str: - """ - Connect to host. Arguments are: + """Connect to host. Arguments are: - host: hostname to connect to (string, default previous host) - port: port to connect to (integer, default previous port) - timeout: the timeout to set against the ftp socket(s) @@ -125,14 +122,12 @@ class FTP: """ def getwelcome(self) -> str: - """ - Get the welcome message from the server. + """Get the welcome message from the server. (this is read and squirreled away by connect()) """ def set_debuglevel(self, level: int) -> None: - """ - Set the debugging level. + """Set the debugging level. The required argument level means: 0: no debugging output (default) 1: print commands and responses but not body text etc. @@ -140,8 +135,7 @@ class FTP: """ def debug(self, level: int) -> None: - """ - Set the debugging level. + """Set the debugging level. The required argument level means: 0: no debugging output (default) 1: print commands and responses but not body text etc. @@ -149,8 +143,7 @@ class FTP: """ def set_pasv(self, val: bool | Literal[0, 1]) -> None: - """ - Use passive or active mode for data transfers. + """Use passive or active mode for data transfers. With a false argument, use the normal PORT mode, With a true argument, use the PASV command. """ @@ -162,57 +155,40 @@ class FTP: def getmultiline(self) -> str: ... def getresp(self) -> str: ... def voidresp(self) -> str: - """ - Expect a response beginning with '2'. - """ + """Expect a response beginning with '2'.""" def abort(self) -> str: - """ - Abort a file transfer. Uses out-of-band data. + """Abort a file transfer. Uses out-of-band data. This does not follow the procedure from the RFC to send Telnet IP and Synch; that doesn't seem to work with the servers I've tried. Instead, just send the ABOR command as OOB data. """ def sendcmd(self, cmd: str) -> str: - """ - Send a command and return the response. - """ + """Send a command and return the response.""" def voidcmd(self, cmd: str) -> str: - """ - Send a command and expect a response beginning with '2'. - """ + """Send a command and expect a response beginning with '2'.""" def sendport(self, host: str, port: int) -> str: - """ - Send a PORT command with the current host and the given + """Send a PORT command with the current host and the given port number. """ def sendeprt(self, host: str, port: int) -> str: - """ - Send an EPRT command with the current host and the given port number. - """ + """Send an EPRT command with the current host and the given port number.""" def makeport(self) -> socket: - """ - Create a new socket and send a PORT command for it. - """ + """Create a new socket and send a PORT command for it.""" def makepasv(self) -> tuple[str, int]: - """ - Internal: Does the PASV or EPSV handshake -> (address, port) - """ + """Internal: Does the PASV or EPSV handshake -> (address, port)""" def login(self, user: str = "", passwd: str = "", acct: str = "") -> str: - """ - Login, default anonymous. - """ + """Login, default anonymous.""" # In practice, `rest` can actually be anything whose str() is an integer sequence, so to make it simple we allow integers def ntransfercmd(self, cmd: str, rest: int | str | None = None) -> tuple[socket, int | None]: - """ - Initiate a transfer over the data connection. + """Initiate a transfer over the data connection. If the transfer is active, send a port command and the transfer command, and accept the connection. If the server is @@ -228,15 +204,12 @@ class FTP: """ def transfercmd(self, cmd: str, rest: int | str | None = None) -> socket: - """ - Like ntransfercmd() but returns only the socket. - """ + """Like ntransfercmd() but returns only the socket.""" def retrbinary( self, cmd: str, callback: Callable[[bytes], object], blocksize: int = 8192, rest: int | str | None = None ) -> str: - """ - Retrieve data in binary mode. A new port is created for you. + """Retrieve data in binary mode. A new port is created for you. Args: cmd: A RETR command. @@ -258,8 +231,7 @@ class FTP: callback: Callable[[bytes], object] | None = None, rest: int | str | None = None, ) -> str: - """ - Store a file in binary mode. A new port is created for you. + """Store a file in binary mode. A new port is created for you. Args: cmd: A STOR command. @@ -275,8 +247,7 @@ class FTP: """ def retrlines(self, cmd: str, callback: Callable[[str], object] | None = None) -> str: - """ - Retrieve data in line mode. A new port is created for you. + """Retrieve data in line mode. A new port is created for you. Args: cmd: A RETR, LIST, or NLST command. @@ -289,8 +260,7 @@ class FTP: """ def storlines(self, cmd: str, fp: SupportsReadline[bytes], callback: Callable[[bytes], object] | None = None) -> str: - """ - Store a file in line mode. A new port is created for you. + """Store a file in line mode. A new port is created for you. Args: cmd: A STOR command. @@ -303,18 +273,13 @@ class FTP: """ def acct(self, password: str) -> str: - """ - Send new account name. - """ + """Send new account name.""" def nlst(self, *args: str) -> list[str]: - """ - Return a list of files in a given directory (default the current). - """ + """Return a list of files in a given directory (default the current).""" # Technically only the last arg can be a Callable but ... def dir(self, *args: str | Callable[[str], object]) -> None: - """ - List a directory in long form. + """List a directory in long form. By default list current directory to stdout. Optional last argument is callback function; all non-empty arguments before it are concatenated to the @@ -322,8 +287,7 @@ class FTP: """ def mlsd(self, path: str = "", facts: Iterable[str] = []) -> Iterator[tuple[str, dict[str, str]]]: - """ - List a directory in a standardized format by using MLSD + """List a directory in a standardized format by using MLSD command (RFC-3659). If path is omitted the current directory is assumed. "facts" is a list of strings representing the type of information desired (e.g. ["type", "size", "perm"]). @@ -336,53 +300,34 @@ class FTP: """ def rename(self, fromname: str, toname: str) -> str: - """ - Rename a file. - """ + """Rename a file.""" def delete(self, filename: str) -> str: - """ - Delete a file. - """ + """Delete a file.""" def cwd(self, dirname: str) -> str: - """ - Change to a directory. - """ + """Change to a directory.""" def size(self, filename: str) -> int | None: - """ - Retrieve the size of a file. - """ + """Retrieve the size of a file.""" def mkd(self, dirname: str) -> str: - """ - Make a directory, return its full pathname. - """ + """Make a directory, return its full pathname.""" def rmd(self, dirname: str) -> str: - """ - Remove a directory. - """ + """Remove a directory.""" def pwd(self) -> str: - """ - Return current working directory. - """ + """Return current working directory.""" def quit(self) -> str: - """ - Quit, and close the connection. - """ + """Quit, and close the connection.""" def close(self) -> None: - """ - Close the connection without assuming anything about it. - """ + """Close the connection without assuming anything about it.""" class FTP_TLS(FTP): - """ - A FTP subclass which adds TLS support to FTP as described + """A FTP subclass which adds TLS support to FTP as described in RFC-4217. Connect as usual to port 21 implicitly securing the FTP control @@ -449,54 +394,40 @@ class FTP_TLS(FTP): context: SSLContext def login(self, user: str = "", passwd: str = "", acct: str = "", secure: bool = True) -> str: ... def auth(self) -> str: - """ - Set up secure control connection by using TLS/SSL. - """ + """Set up secure control connection by using TLS/SSL.""" def prot_p(self) -> str: - """ - Set up secure data connection. - """ + """Set up secure data connection.""" def prot_c(self) -> str: - """ - Set up clear text data connection. - """ + """Set up clear text data connection.""" def ccc(self) -> str: - """ - Switch back to a clear-text control connection. - """ + """Switch back to a clear-text control connection.""" def parse150(resp: str) -> int | None: # undocumented - """ - Parse the '150' response for a RETR request. + """Parse the '150' response for a RETR request. Returns the expected transfer size or None; size is not guaranteed to be present in the 150 message. """ def parse227(resp: str) -> tuple[str, int]: # undocumented - """ - Parse the '227' response for a PASV request. + """Parse the '227' response for a PASV request. Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)' Return ('host.addr.as.numbers', port#) tuple. """ def parse229(resp: str, peer: Any) -> tuple[str, int]: # undocumented - """ - Parse the '229' response for an EPSV request. + """Parse the '229' response for an EPSV request. Raises error_proto if it does not contain '(|||port|)' Return ('host.addr.as.numbers', port#) tuple. """ def parse257(resp: str) -> str: # undocumented - """ - Parse the '257' response for a MKD or PWD request. + """Parse the '257' response for a MKD or PWD request. This is a response to a MKD or PWD request: a directory name. Returns the directoryname in the 257 reply. """ def ftpcp(source: FTP, sourcename: str, target: FTP, targetname: str = "", type: Literal["A", "I"] = "I") -> None: # undocumented - """ - Copy file from one FTP-instance to another. - """ + """Copy file from one FTP-instance to another.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/functools.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/functools.pyi index 5f723badcb..0bac0d4b3d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/functools.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/functools.pyi @@ -38,8 +38,7 @@ _RWrapper = TypeVar("_RWrapper") if sys.version_info >= (3, 14): @overload def reduce(function: Callable[[_T, _S], _T], iterable: Iterable[_S], /, initial: _T) -> _T: - """ - Apply a function of two arguments cumulatively to the items of an iterable, from left to right. + """Apply a function of two arguments cumulatively to the items of an iterable, from left to right. This effectively reduces the iterable to a single value. If initial is present, it is placed before the items of the iterable in the calculation, and serves as @@ -52,8 +51,7 @@ if sys.version_info >= (3, 14): else: @overload def reduce(function: Callable[[_T, _S], _T], iterable: Iterable[_S], initial: _T, /) -> _T: - """ - reduce(function, iterable[, initial], /) -> value + """reduce(function, iterable[, initial], /) -> value Apply a function of two arguments cumulatively to the items of an iterable, from left to right. @@ -69,9 +67,7 @@ else: def reduce(function: Callable[[_T, _T], _T], iterable: Iterable[_T], /) -> _T: ... class _CacheInfo(NamedTuple): - """ - CacheInfo(hits, misses, maxsize, currsize) - """ + """CacheInfo(hits, misses, maxsize, currsize)""" hits: int misses: int @@ -84,8 +80,7 @@ class _CacheParameters(TypedDict): @final class _lru_cache_wrapper(Generic[_T]): - """ - Create a cached callable that wraps another function. + """Create a cached callable that wraps another function. user_function: the function being cached @@ -102,19 +97,13 @@ class _lru_cache_wrapper(Generic[_T]): __wrapped__: Callable[..., _T] def __call__(self, *args: Hashable, **kwargs: Hashable) -> _T: - """ - Call self as a function. - """ + """Call self as a function.""" def cache_info(self) -> _CacheInfo: - """ - Report cache statistics - """ + """Report cache statistics""" def cache_clear(self) -> None: - """ - Clear the cache and cache statistics - """ + """Clear the cache and cache statistics""" def cache_parameters(self) -> _CacheParameters: ... def __copy__(self) -> _lru_cache_wrapper[_T]: ... @@ -122,8 +111,7 @@ class _lru_cache_wrapper(Generic[_T]): @overload def lru_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: - """ - Least-recently-used cache decorator. + """Least-recently-used cache decorator. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. @@ -191,8 +179,7 @@ if sys.version_info >= (3, 14): assigned: Iterable[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotate__", "__type_params__"), updated: Iterable[str] = ("__dict__",), ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: - """ - Update a wrapper function to look like the wrapped function + """Update a wrapper function to look like the wrapped function wrapper is the function to be updated wrapped is the original function @@ -209,8 +196,7 @@ if sys.version_info >= (3, 14): assigned: Iterable[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotate__", "__type_params__"), updated: Iterable[str] = ("__dict__",), ) -> _Wrapper[_PWrapped, _RWrapped]: - """ - Decorator factory to apply update_wrapper() to a wrapper function + """Decorator factory to apply update_wrapper() to a wrapper function Returns a decorator that invokes update_wrapper() with the decorated function as the wrapper argument and the arguments to wraps() as the @@ -226,8 +212,7 @@ elif sys.version_info >= (3, 12): assigned: Iterable[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__", "__type_params__"), updated: Iterable[str] = ("__dict__",), ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: - """ - Update a wrapper function to look like the wrapped function + """Update a wrapper function to look like the wrapped function wrapper is the function to be updated wrapped is the original function @@ -244,8 +229,7 @@ elif sys.version_info >= (3, 12): assigned: Iterable[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__", "__type_params__"), updated: Iterable[str] = ("__dict__",), ) -> _Wrapper[_PWrapped, _RWrapped]: - """ - Decorator factory to apply update_wrapper() to a wrapper function + """Decorator factory to apply update_wrapper() to a wrapper function Returns a decorator that invokes update_wrapper() with the decorated function as the wrapper argument and the arguments to wraps() as the @@ -261,8 +245,7 @@ else: assigned: Iterable[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__"), updated: Iterable[str] = ("__dict__",), ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: - """ - Update a wrapper function to look like the wrapped function + """Update a wrapper function to look like the wrapped function wrapper is the function to be updated wrapped is the original function @@ -279,8 +262,7 @@ else: assigned: Iterable[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__"), updated: Iterable[str] = ("__dict__",), ) -> _Wrapper[_PWrapped, _RWrapped]: - """ - Decorator factory to apply update_wrapper() to a wrapper function + """Decorator factory to apply update_wrapper() to a wrapper function Returns a decorator that invokes update_wrapper() with the decorated function as the wrapper argument and the arguments to wraps() as the @@ -290,59 +272,44 @@ else: """ def total_ordering(cls: type[_T]) -> type[_T]: - """ - Class decorator that fills in missing ordering methods - """ + """Class decorator that fills in missing ordering methods""" def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], SupportsAllComparisons]: - """ - Convert a cmp= function into a key= function. + """Convert a cmp= function into a key= function. mycmp Function that compares two objects. """ class partial(Generic[_T]): - """ - Create a new function with partial application of the given arguments + """Create a new function with partial application of the given arguments and keywords. """ @property def func(self) -> Callable[..., _T]: - """ - function object to use in future partial calls - """ + """function object to use in future partial calls""" @property def args(self) -> tuple[Any, ...]: - """ - tuple of arguments to future partial calls - """ + """tuple of arguments to future partial calls""" @property def keywords(self) -> dict[str, Any]: - """ - dictionary of keyword arguments to future partial calls - """ + """dictionary of keyword arguments to future partial calls""" def __new__(cls, func: Callable[..., _T], /, *args: Any, **kwargs: Any) -> Self: ... def __call__(self, /, *args: Any, **kwargs: Any) -> _T: - """ - Call self as a function. - """ + """Call self as a function.""" def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" # With protocols, this could change into a generic protocol that defines __get__ and returns _T _Descriptor: TypeAlias = Any class partialmethod(Generic[_T]): - """ - Method descriptor with partial application of the given arguments + """Method descriptor with partial application of the given arguments and keywords. Supports wrapping existing descriptors and handles non-descriptor @@ -360,8 +327,7 @@ class partialmethod(Generic[_T]): @property def __isabstractmethod__(self) -> bool: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ @@ -389,8 +355,7 @@ class _SingleDispatchCallable(Generic[_T]): def __call__(self, /, *args: Any, **kwargs: Any) -> _T: ... def singledispatch(func: Callable[..., _T]) -> _SingleDispatchCallable[_T]: - """ - Single-dispatch generic function decorator. + """Single-dispatch generic function decorator. Transforms a function into a generic function, which can have different behaviours depending upon the type of its first argument. The decorated @@ -400,8 +365,7 @@ def singledispatch(func: Callable[..., _T]) -> _SingleDispatchCallable[_T]: """ class singledispatchmethod(Generic[_T]): - """ - Single-dispatch generic method descriptor. + """Single-dispatch generic method descriptor. Supports wrapping existing descriptors and handles non-descriptor callables as instance methods. @@ -414,8 +378,7 @@ class singledispatchmethod(Generic[_T]): def __isabstractmethod__(self) -> bool: ... @overload def register(self, cls: _RegType, method: None = None) -> Callable[[Callable[..., _T]], Callable[..., _T]]: - """ - generic_method.register(cls, func) -> func + """generic_method.register(cls, func) -> func Registers a new implementation for the given *cls* on a *generic_method*. """ @@ -438,16 +401,13 @@ class cached_property(Generic[_T_co]): # __set__ is not defined at runtime, but @cached_property is designed to be settable def __set__(self, instance: object, value: _T_co) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ def cache(user_function: Callable[..., _T], /) -> _lru_cache_wrapper[_T]: - """ - Simple lightweight unbounded cache. Sometimes called "memoize". - """ + """Simple lightweight unbounded cache. Sometimes called "memoize".""" def _make_key( args: tuple[Hashable, ...], @@ -459,8 +419,7 @@ def _make_key( type: Any = ..., len: Callable[[Sized], int] = ..., ) -> Hashable: - """ - Make a cache key from optionally typed positional and keyword arguments + """Make a cache key from optionally typed positional and keyword arguments The key is constructed in a way that is flat as possible rather than as a nested structure that would take more memory. @@ -473,8 +432,7 @@ def _make_key( if sys.version_info >= (3, 14): @final class _PlaceholderType: - """ - The type of the Placeholder singleton. + """The type of the Placeholder singleton. Used as a placeholder for partial arguments. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/gc.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/gc.pyi index 5fe0b46552..4c81b6e47a 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/gc.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/gc.pyi @@ -37,8 +37,7 @@ callbacks: list[_CallbackType] garbage: list[Any] def collect(generation: int = 2) -> int: - """ - Run the garbage collector. + """Run the garbage collector. With no arguments, run a full collection. The optional argument may be an integer specifying which generation to collect. A ValueError @@ -48,28 +47,19 @@ def collect(generation: int = 2) -> int: """ def disable() -> None: - """ - Disable automatic garbage collection. - """ + """Disable automatic garbage collection.""" def enable() -> None: - """ - Enable automatic garbage collection. - """ + """Enable automatic garbage collection.""" def get_count() -> tuple[int, int, int]: - """ - Return a three-tuple of the current collection counts. - """ + """Return a three-tuple of the current collection counts.""" def get_debug() -> int: - """ - Get the garbage collection debugging flags. - """ + """Get the garbage collection debugging flags.""" def get_objects(generation: int | None = None) -> list[Any]: - """ - Return a list of objects tracked by the collector (excluding the list returned). + """Return a list of objects tracked by the collector (excluding the list returned). generation Generation to extract the objects from. @@ -79,8 +69,7 @@ def get_objects(generation: int | None = None) -> list[Any]: """ def freeze() -> None: - """ - Freeze all current tracked objects and ignore them for future collections. + """Freeze all current tracked objects and ignore them for future collections. This can be used before a POSIX fork() call to make the gc copy-on-write friendly. Note: collection before a POSIX fork() call may free pages for future allocation @@ -88,57 +77,40 @@ def freeze() -> None: """ def unfreeze() -> None: - """ - Unfreeze all objects in the permanent generation. + """Unfreeze all objects in the permanent generation. Put all objects in the permanent generation back into oldest generation. """ def get_freeze_count() -> int: - """ - Return the number of objects in the permanent generation. - """ + """Return the number of objects in the permanent generation.""" def get_referents(*objs: Any) -> list[Any]: - """ - Return the list of objects that are directly referred to by 'objs'. - """ + """Return the list of objects that are directly referred to by 'objs'.""" def get_referrers(*objs: Any) -> list[Any]: - """ - Return the list of objects that directly refer to any of 'objs'. - """ + """Return the list of objects that directly refer to any of 'objs'.""" def get_stats() -> list[dict[str, Any]]: - """ - Return a list of dictionaries containing per-generation statistics. - """ + """Return a list of dictionaries containing per-generation statistics.""" def get_threshold() -> tuple[int, int, int]: - """ - Return the current collection thresholds. - """ + """Return the current collection thresholds.""" def is_tracked(obj: Any, /) -> bool: - """ - Returns true if the object is tracked by the garbage collector. + """Returns true if the object is tracked by the garbage collector. Simple atomic objects will return false. """ def is_finalized(obj: Any, /) -> bool: - """ - Returns true if the object has been already finalized by the GC. - """ + """Returns true if the object has been already finalized by the GC.""" def isenabled() -> bool: - """ - Returns true if automatic garbage collection is enabled. - """ + """Returns true if automatic garbage collection is enabled.""" def set_debug(flags: int, /) -> None: - """ - Set the garbage collection debugging flags. + """Set the garbage collection debugging flags. flags An integer that can have the following bits turned on: @@ -153,8 +125,7 @@ def set_debug(flags: int, /) -> None: """ def set_threshold(threshold0: int, threshold1: int = ..., threshold2: int = ..., /) -> None: - """ - set_threshold(threshold0, [threshold1, [threshold2]]) + """set_threshold(threshold0, [threshold1, [threshold2]]) Set the collection thresholds (the collection frequency). Setting 'threshold0' to zero disables collection. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/genericpath.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/genericpath.pyi index 744e47caba..a43beedb37 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/genericpath.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/genericpath.pyi @@ -1,4 +1,5 @@ """ + Path operations common to more than one OS Do not use directly. The OS specific modules import the appropriate functions from this module themselves. @@ -35,9 +36,7 @@ if sys.version_info >= (3, 13): # type. But because this only works when T is str, we need Sequence[T] instead. @overload def commonprefix(m: Sequence[LiteralString]) -> LiteralString: - """ - Given a list of pathnames, returns the longest common leading component - """ + """Given a list of pathnames, returns the longest common leading component""" @overload def commonprefix(m: Sequence[StrPath]) -> str: ... @@ -48,83 +47,58 @@ def commonprefix(m: Sequence[list[SupportsRichComparisonT]]) -> Sequence[Support @overload def commonprefix(m: Sequence[tuple[SupportsRichComparisonT, ...]]) -> Sequence[SupportsRichComparisonT]: ... def exists(path: FileDescriptorOrPath) -> bool: - """ - Test whether a path exists. Returns False for broken symbolic links - """ + """Test whether a path exists. Returns False for broken symbolic links""" def getsize(filename: FileDescriptorOrPath) -> int: - """ - Return the size of a file, reported by os.stat(). - """ + """Return the size of a file, reported by os.stat().""" def isfile(path: FileDescriptorOrPath) -> bool: - """ - Test whether a path is a regular file - """ + """Test whether a path is a regular file""" def isdir(s: FileDescriptorOrPath) -> bool: - """ - Return true if the pathname refers to an existing directory. - """ + """Return true if the pathname refers to an existing directory.""" if sys.version_info >= (3, 12): def islink(path: StrOrBytesPath) -> bool: - """ - Test whether a path is a symbolic link - """ + """Test whether a path is a symbolic link""" # These return float if os.stat_float_times() == True, # but int is a subclass of float. def getatime(filename: FileDescriptorOrPath) -> float: - """ - Return the last access time of a file, reported by os.stat(). - """ + """Return the last access time of a file, reported by os.stat().""" def getmtime(filename: FileDescriptorOrPath) -> float: - """ - Return the last modification time of a file, reported by os.stat(). - """ + """Return the last modification time of a file, reported by os.stat().""" def getctime(filename: FileDescriptorOrPath) -> float: - """ - Return the metadata change time of a file, reported by os.stat(). - """ + """Return the metadata change time of a file, reported by os.stat().""" def samefile(f1: FileDescriptorOrPath, f2: FileDescriptorOrPath) -> bool: - """ - Test whether two pathnames reference the same actual file or directory + """Test whether two pathnames reference the same actual file or directory This is determined by the device number and i-node number and raises an exception if an os.stat() call on either pathname fails. """ def sameopenfile(fp1: int, fp2: int) -> bool: - """ - Test whether two open file objects reference the same file - """ + """Test whether two open file objects reference the same file""" def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: - """ - Test whether two stat buffers reference the same file - """ + """Test whether two stat buffers reference the same file""" if sys.version_info >= (3, 13): def isjunction(path: StrOrBytesPath) -> bool: - """ - Test whether a path is a junction + """Test whether a path is a junction Junctions are not supported on the current platform """ def isdevdrive(path: StrOrBytesPath) -> bool: - """ - Determines whether the specified path is on a Windows Dev Drive. + """Determines whether the specified path is on a Windows Dev Drive. Dev Drives are not supported on the current platform """ def lexists(path: StrOrBytesPath) -> bool: - """ - Test whether a path exists. Returns True for broken symbolic links - """ + """Test whether a path exists. Returns True for broken symbolic links""" # Added in Python 3.9.23, 3.10.18, 3.11.13, 3.12.11, 3.13.4 _AllowMissingType = NewType("_AllowMissingType", object) diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/getopt.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/getopt.pyi index 42b45f26c2..85eb6d694e 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/getopt.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/getopt.pyi @@ -32,8 +32,7 @@ __all__ = ["GetoptError", "error", "getopt", "gnu_getopt"] def getopt( args: _SliceableT[_StrSequenceT_co], shortopts: str, longopts: Iterable[str] | str = [] ) -> tuple[list[tuple[str, str]], _StrSequenceT_co]: - """ - getopt(args, options[, long_options]) -> opts, args + """getopt(args, options[, long_options]) -> opts, args Parses command line options and parameter list. args is the argument list to be parsed, without the leading reference to the @@ -63,8 +62,7 @@ def getopt( def gnu_getopt( args: Sequence[str], shortopts: str, longopts: Iterable[str] | str = [] ) -> tuple[list[tuple[str, str]], list[str]]: - """ - getopt(args, options[, long_options]) -> opts, args + """getopt(args, options[, long_options]) -> opts, args This function works like getopt(), except that GNU style scanning mode is used by default. This means that option and non-option diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/getpass.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/getpass.pyi index abf2547614..8b31291227 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/getpass.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/getpass.pyi @@ -18,8 +18,7 @@ __all__ = ["getpass", "getuser", "GetPassWarning"] if sys.version_info >= (3, 14): def getpass(prompt: str = "Password: ", stream: TextIO | None = None, *, echo_char: str | None = None) -> str: - """ - Prompt for a password, with echo turned off. + """Prompt for a password, with echo turned off. Args: prompt: Written on stream to ask for the input. Default: 'Password: ' @@ -38,8 +37,7 @@ if sys.version_info >= (3, 14): else: def getpass(prompt: str = "Password: ", stream: TextIO | None = None) -> str: - """ - Prompt for a password, with echo turned off. + """Prompt for a password, with echo turned off. Args: prompt: Written on stream to ask for the input. Default: 'Password: ' @@ -55,8 +53,7 @@ else: """ def getuser() -> str: - """ - Get the username from the environment or password database. + """Get the username from the environment or password database. First try various environment variables, then the password database. This works on Windows as long as USERNAME is set. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/gettext.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/gettext.pyi index 324c8e5eee..e0296695fe 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/gettext.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/gettext.pyi @@ -181,7 +181,6 @@ if sys.version_info < (3, 11): Catalog = translation def c2py(plural: str) -> Callable[[int], int]: - """ - Gets a C expression as used in PO files for plural forms and returns a + """Gets a C expression as used in PO files for plural forms and returns a Python function that implements an equivalent expression. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/glob.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/glob.pyi index 85bbed03b6..8470e755bf 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/glob.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/glob.pyi @@ -24,8 +24,7 @@ if sys.version_info >= (3, 11): recursive: bool = False, include_hidden: bool = False, ) -> list[AnyStr]: - """ - Return a list of paths matching a pathname pattern. + """Return a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. Unlike fnmatch, filenames starting with a @@ -47,8 +46,7 @@ if sys.version_info >= (3, 11): recursive: bool = False, include_hidden: bool = False, ) -> Iterator[AnyStr]: - """ - Return an iterator which yields the paths matching a pathname pattern. + """Return an iterator which yields the paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a @@ -63,8 +61,7 @@ elif sys.version_info >= (3, 10): def glob( pathname: AnyStr, *, root_dir: StrOrBytesPath | None = None, dir_fd: int | None = None, recursive: bool = False ) -> list[AnyStr]: - """ - Return a list of paths matching a pathname pattern. + """Return a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a @@ -78,8 +75,7 @@ elif sys.version_info >= (3, 10): def iglob( pathname: AnyStr, *, root_dir: StrOrBytesPath | None = None, dir_fd: int | None = None, recursive: bool = False ) -> Iterator[AnyStr]: - """ - Return an iterator which yields the paths matching a pathname pattern. + """Return an iterator which yields the paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a @@ -92,8 +88,7 @@ elif sys.version_info >= (3, 10): else: def glob(pathname: AnyStr, *, recursive: bool = False) -> list[AnyStr]: - """ - Return a list of paths matching a pathname pattern. + """Return a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a @@ -105,8 +100,7 @@ else: """ def iglob(pathname: AnyStr, *, recursive: bool = False) -> Iterator[AnyStr]: - """ - Return an iterator which yields the paths matching a pathname pattern. + """Return an iterator which yields the paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a @@ -118,16 +112,13 @@ else: """ def escape(pathname: AnyStr) -> AnyStr: - """ - Escape all special characters. - """ + """Escape all special characters.""" def has_magic(s: str | bytes) -> bool: ... # undocumented if sys.version_info >= (3, 13): def translate(pat: str, *, recursive: bool = False, include_hidden: bool = False, seps: Sequence[str] | None = None) -> str: - """ - Translate a pathname with shell wildcards to a regular expression. + """Translate a pathname with shell wildcards to a regular expression. If `recursive` is true, the pattern segment '**' will match any number of path segments. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/graphlib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/graphlib.pyi index e82943c1f5..21b07b3aa7 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/graphlib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/graphlib.pyi @@ -11,17 +11,14 @@ if sys.version_info >= (3, 11): from types import GenericAlias class TopologicalSorter(Generic[_T]): - """ - Provides functionality to topologically sort a graph of hashable nodes - """ + """Provides functionality to topologically sort a graph of hashable nodes""" @overload def __init__(self, graph: None = None) -> None: ... @overload def __init__(self, graph: SupportsItems[_T, Iterable[_T]]) -> None: ... def add(self, node: _T, *predecessors: _T) -> None: - """ - Add a new node and its predecessors to the graph. + """Add a new node and its predecessors to the graph. Both the *node* and all elements in *predecessors* must be hashable. @@ -37,8 +34,7 @@ class TopologicalSorter(Generic[_T]): """ def prepare(self) -> None: - """ - Mark the graph as finished and check for cycles in the graph. + """Mark the graph as finished and check for cycles in the graph. If any cycle is detected, "CycleError" will be raised, but "get_ready" can still be used to obtain as many nodes as possible until cycles block more @@ -49,8 +45,7 @@ class TopologicalSorter(Generic[_T]): """ def is_active(self) -> bool: - """ - Return ``True`` if more progress can be made and ``False`` otherwise. + """Return ``True`` if more progress can be made and ``False`` otherwise. Progress can be made if cycles do not block the resolution and either there are still nodes ready that haven't yet been returned by "get_ready" or the @@ -62,8 +57,7 @@ class TopologicalSorter(Generic[_T]): def __bool__(self) -> bool: ... def done(self, *nodes: _T) -> None: - """ - Marks a set of nodes returned by "get_ready" as processed. + """Marks a set of nodes returned by "get_ready" as processed. This method unblocks any successor of each node in *nodes* for being returned in the future by a call to "get_ready". @@ -75,8 +69,7 @@ class TopologicalSorter(Generic[_T]): """ def get_ready(self) -> tuple[_T, ...]: - """ - Return a tuple of all the nodes that are ready. + """Return a tuple of all the nodes that are ready. Initially it returns all nodes with no predecessors; once those are marked as processed by calling "done", further calls will return all new nodes that @@ -87,8 +80,7 @@ class TopologicalSorter(Generic[_T]): """ def static_order(self) -> Iterable[_T]: - """ - Returns an iterable of nodes in a topological order. + """Returns an iterable of nodes in a topological order. The particular order that is returned may depend on the specific order in which the items were inserted in the graph. @@ -98,15 +90,13 @@ class TopologicalSorter(Generic[_T]): """ if sys.version_info >= (3, 11): def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ class CycleError(ValueError): - """ - Subclass of ValueError raised by TopologicalSorter.prepare if cycles + """Subclass of ValueError raised by TopologicalSorter.prepare if cycles exist in the working graph. If multiple cycles exist, only one undefined choice among them will be reported diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/grp.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/grp.pyi index 13c0436e31..f8e3f82e1c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/grp.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/grp.pyi @@ -22,8 +22,7 @@ from typing import Any, Final, final if sys.platform != "win32": @final class struct_group(structseq[Any], tuple[str, str | None, int, list[str]]): - """ - grp.struct_group: Results from getgr*() routines. + """grp.struct_group: Results from getgr*() routines. This object may be accessed either as a tuple of (gr_name,gr_passwd,gr_gid,gr_mem) @@ -35,46 +34,35 @@ if sys.platform != "win32": @property def gr_name(self) -> str: - """ - group name - """ + """group name""" @property def gr_passwd(self) -> str | None: - """ - password - """ + """password""" @property def gr_gid(self) -> int: - """ - group id - """ + """group id""" @property def gr_mem(self) -> list[str]: - """ - group members - """ + """group members""" def getgrall() -> list[struct_group]: - """ - Return a list of all available group entries, in arbitrary order. + """Return a list of all available group entries, in arbitrary order. An entry whose name starts with '+' or '-' represents an instruction to use YP/NIS and may not be accessible via getgrnam or getgrgid. """ def getgrgid(id: int) -> struct_group: - """ - Return the group database entry for the given numeric group ID. + """Return the group database entry for the given numeric group ID. If id is not valid, raise KeyError. """ def getgrnam(name: str) -> struct_group: - """ - Return the group database entry for the given group name. + """Return the group database entry for the given group name. If name is not valid, raise KeyError. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/gzip.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/gzip.pyi index a8bd57e4f4..0d93995b97 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/gzip.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/gzip.pyi @@ -57,8 +57,7 @@ def open( errors: None = None, newline: None = None, ) -> GzipFile: - """ - Open a gzip-compressed file in binary or text mode. + """Open a gzip-compressed file in binary or text mode. The filename argument can be an actual filename (a str or bytes object), or an existing file object to read from or write to. @@ -105,8 +104,7 @@ def open( ) -> GzipFile | TextIOWrapper: ... class _PaddedFile: - """ - Minimal read-only file object that prepends a string to the contents + """Minimal read-only file object that prepends a string to the contents of an actual file. Shouldn't be used outside of gzip.py, as it lacks essential functionality. """ @@ -119,13 +117,10 @@ class _PaddedFile: def seekable(self) -> bool: ... class BadGzipFile(OSError): - """ - Exception raised in some cases for invalid gzip files. - """ + """Exception raised in some cases for invalid gzip files.""" class GzipFile(BaseStream): - """ - The GzipFile class simulates most of the methods of a file object with + """The GzipFile class simulates most of the methods of a file object with the exception of the truncate() method. This class only supports opening files in binary mode. If you need to open a @@ -146,8 +141,7 @@ class GzipFile(BaseStream): fileobj: _ReadableFileobj | None = None, mtime: float | None = None, ) -> None: - """ - Constructor for the GzipFile class. + """Constructor for the GzipFile class. At least one of fileobj and filename must be given a non-trivial value. @@ -222,15 +216,12 @@ class GzipFile(BaseStream): @property def mtime(self) -> int | None: - """ - Last modification time read from stream, or None - """ + """Last modification time read from stream, or None""" crc: int def write(self, data: ReadableBuffer) -> int: ... def read(self, size: int | None = -1) -> bytes: ... def read1(self, size: int = -1) -> bytes: - """ - Implements BufferedIOBase.read1() + """Implements BufferedIOBase.read1() Reads up to a buffer's worth of data if size is negative. """ @@ -239,16 +230,14 @@ class GzipFile(BaseStream): def close(self) -> None: ... def flush(self, zlib_mode: int = 2) -> None: ... def fileno(self) -> int: - """ - Invoke the underlying file object's fileno() method. + """Invoke the underlying file object's fileno() method. This will raise AttributeError if the underlying file object doesn't support fileno(). """ def rewind(self) -> None: - """ - Return the uncompressed stream file position indicator to the + """Return the uncompressed stream file position indicator to the beginning of the file """ @@ -264,8 +253,7 @@ class _GzipReader(DecompressReader): if sys.version_info >= (3, 14): def compress(data: SizedBuffer, compresslevel: int = 9, *, mtime: float = 0) -> bytes: - """ - Compress data in one shot and return the compressed string. + """Compress data in one shot and return the compressed string. compresslevel sets the compression level in range of 0-9. mtime can be used to set the modification time. @@ -274,8 +262,7 @@ if sys.version_info >= (3, 14): else: def compress(data: SizedBuffer, compresslevel: int = 9, *, mtime: float | None = None) -> bytes: - """ - Compress data in one shot and return the compressed string. + """Compress data in one shot and return the compressed string. compresslevel sets the compression level in range of 0-9. mtime can be used to set the modification time. The modification time is @@ -283,7 +270,6 @@ else: """ def decompress(data: ReadableBuffer) -> bytes: - """ - Decompress a gzip compressed string in one shot. + """Decompress a gzip compressed string in one shot. Return the decompressed string. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/hashlib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/hashlib.pyi index d4e1d4f49f..b34bc088c3 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/hashlib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/hashlib.pyi @@ -118,8 +118,7 @@ else: ) def new(name: str, data: ReadableBuffer = b"", *, usedforsecurity: bool = ...) -> HASH: - """ - new(name, data=b'') - Return a new hashing object using the named algorithm; + """new(name, data=b'') - Return a new hashing object using the named algorithm; optionally initialized with data (which must be a bytes-like object). """ @@ -137,8 +136,7 @@ if sys.version_info >= (3, 11): def file_digest( fileobj: _BytesIOLike | _FileDigestFileObj, digest: str | Callable[[], _HashObject], /, *, _bufsize: int = 262144 ) -> HASH: - """ - Hash the contents of a file-like object. Returns a digest object. + """Hash the contents of a file-like object. Returns a digest object. *fileobj* must be a file-like object opened for reading in binary mode. It accepts file objects from open(), io.BytesIO(), and SocketIO objects. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/heapq.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/heapq.pyi index c5fbf78154..bf6e04806d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/heapq.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/heapq.pyi @@ -45,8 +45,7 @@ __about__: Final[str] def merge( *iterables: Iterable[_S], key: Callable[[_S], SupportsRichComparison] | None = None, reverse: bool = False ) -> Generator[_S]: - """ - Merge multiple sorted inputs into a single sorted output. + """Merge multiple sorted inputs into a single sorted output. Similar to sorted(itertools.chain(*iterables)) but returns a generator, does not pull the data into memory all at once, and assumes that each of @@ -63,20 +62,16 @@ def merge( """ def nlargest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison] | None = None) -> list[_S]: - """ - Find the n largest elements in a dataset. + """Find the n largest elements in a dataset. Equivalent to: sorted(iterable, key=key, reverse=True)[:n] """ def nsmallest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison] | None = None) -> list[_S]: - """ - Find the n smallest elements in a dataset. + """Find the n smallest elements in a dataset. Equivalent to: sorted(iterable, key=key)[:n] """ def _heapify_max(heap: list[Any], /) -> None: # undocumented - """ - Maxheap variant of heapify. - """ + """Maxheap variant of heapify.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/hmac.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/hmac.pyi index 6633982079..597ce815c4 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/hmac.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/hmac.pyi @@ -22,8 +22,7 @@ digest_size: None # if the argument is not given, so we pretend it is a required argument. @overload def new(key: bytes | bytearray, msg: ReadableBuffer | None, digestmod: _DigestMod) -> HMAC: - """ - Create a new hashing object and return it. + """Create a new hashing object and return it. key: bytes or buffer, The starting key for the hash. msg: bytes or buffer, Initial input for the hash, or None. @@ -44,8 +43,7 @@ def new(key: bytes | bytearray, msg: ReadableBuffer | None, digestmod: _DigestMo def new(key: bytes | bytearray, *, digestmod: _DigestMod) -> HMAC: ... class HMAC: - """ - RFC 2104 HMAC class. Also complies with RFC 4231. + """RFC 2104 HMAC class. Also complies with RFC 4231. This supports the API for Cryptographic Hash Functions (PEP 247). """ @@ -55,8 +53,7 @@ class HMAC: @property def name(self) -> str: ... def __init__(self, key: bytes | bytearray, msg: ReadableBuffer | None = None, digestmod: _DigestMod = "") -> None: - """ - Create a new HMAC object. + """Create a new HMAC object. key: bytes or buffer, key for the keyed hash object. msg: bytes or buffer, Initial input for the hash or None. @@ -70,13 +67,10 @@ class HMAC: """ def update(self, msg: ReadableBuffer) -> None: - """ - Feed data from msg into this hashing object. - """ + """Feed data from msg into this hashing object.""" def digest(self) -> bytes: - """ - Return the hash value of this hashing object. + """Return the hash value of this hashing object. This returns the hmac value as bytes. The object is not altered in any way by this function; you can continue @@ -84,20 +78,16 @@ class HMAC: """ def hexdigest(self) -> str: - """ - Like digest(), but returns a string of hexadecimal digits instead. - """ + """Like digest(), but returns a string of hexadecimal digits instead.""" def copy(self) -> HMAC: - """ - Return a separate copy of this hashing object. + """Return a separate copy of this hashing object. An update to this copy won't affect the original object. """ def digest(key: SizedBuffer, msg: ReadableBuffer, digest: _DigestMod) -> bytes: - """ - Fast inline implementation of HMAC. + """Fast inline implementation of HMAC. key: bytes or buffer, The key for the keyed hash object. msg: bytes or buffer, Input message. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/html/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/html/__init__.pyi index af5799ee0c..06b2bbfd1d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/html/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/html/__init__.pyi @@ -1,4 +1,5 @@ """ + General functions for HTML manipulation. """ @@ -7,16 +8,14 @@ from typing import AnyStr __all__ = ["escape", "unescape"] def escape(s: AnyStr, quote: bool = True) -> AnyStr: - """ - Replace special characters "&", "<" and ">" to HTML-safe sequences. + """Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true (the default), the quotation mark characters, both double quote (") and single quote (') characters are also translated. """ def unescape(s: AnyStr) -> AnyStr: - """ - Convert all named and numeric character references (e.g. >, >, + """Convert all named and numeric character references (e.g. >, >, &x3e;) in the string s to the corresponding unicode characters. This function uses the rules defined by the HTML 5 standard for both valid and invalid character references, and the list of diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/html/parser.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/html/parser.pyi index 1381bce13a..69a29c995b 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/html/parser.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/html/parser.pyi @@ -8,8 +8,7 @@ from re import Pattern __all__ = ["HTMLParser"] class HTMLParser(ParserBase): - """ - Find tags and other markup and call handler functions. + """Find tags and other markup and call handler functions. Usage: p = HTMLParser() @@ -31,30 +30,24 @@ class HTMLParser(ParserBase): """ def __init__(self, *, convert_charrefs: bool = True) -> None: - """ - Initialize and reset this instance. + """Initialize and reset this instance. If convert_charrefs is True (the default), all character references are automatically converted to the corresponding Unicode characters. """ def feed(self, data: str) -> None: - """ - Feed data to the parser. + """Feed data to the parser. Call this as often as you want, with as little or as much text as you want (may include '\\n'). """ def close(self) -> None: - """ - Handle any buffered data. - """ + """Handle any buffered data.""" def get_starttag_text(self) -> str | None: - """ - Return full source of start tag: '<...>'. - """ + """Return full source of start tag: '<...>'.""" def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: ... def handle_endtag(self, tag: str) -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/http/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/http/__init__.pyi index d5666eced8..1b65f16219 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/http/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/http/__init__.pyi @@ -10,8 +10,7 @@ else: __all__ = ["HTTPStatus"] class HTTPStatus(IntEnum): - """ - HTTP status codes and reason phrases + """HTTP status codes and reason phrases Status codes from the following RFCs are all observed: @@ -125,8 +124,7 @@ class HTTPStatus(IntEnum): if sys.version_info >= (3, 11): class HTTPMethod(StrEnum): - """ - HTTP methods and descriptions + """HTTP methods and descriptions Methods from the following RFCs are all observed: diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/http/client.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/http/client.pyi index f215b47ed9..c4b862d77d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/http/client.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/http/client.pyi @@ -191,8 +191,7 @@ responses: dict[int, str] class HTTPMessage(email.message.Message[str, str]): def getallmatchingheaders(self, name: str) -> list[str]: # undocumented - """ - Find all header lines matching a given header name. + """Find all header lines matching a given header name. Look through the list of headers and find all lines matching a given header name (and their continuation lines). A list of the lines is @@ -203,9 +202,7 @@ class HTTPMessage(email.message.Message[str, str]): @overload def parse_headers(fp: SupportsReadline[bytes], _class: Callable[[], _MessageT]) -> _MessageT: - """ - Parses only RFC2822 headers from a file pointer. - """ + """Parses only RFC2822 headers from a file pointer.""" @overload def parse_headers(fp: SupportsReadline[bytes]) -> HTTPMessage: ... @@ -230,27 +227,22 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): # type: ignore[misc] # incomp def __init__(self, sock: socket, debuglevel: int = 0, method: str | None = None, url: str | None = None) -> None: ... def peek(self, n: int = -1) -> bytes: ... def read(self, amt: int | None = None) -> bytes: - """ - Read and return the response body, or up to the next amt bytes. - """ + """Read and return the response body, or up to the next amt bytes.""" def read1(self, n: int = -1) -> bytes: - """ - Read with at most one underlying system call. If at least one + """Read with at most one underlying system call. If at least one byte is buffered, return that instead. """ def readinto(self, b: WriteableBuffer) -> int: - """ - Read up to len(b) bytes into bytearray b and return the number + """Read up to len(b) bytes into bytearray b and return the number of bytes read. """ def readline(self, limit: int = -1) -> bytes: ... # type: ignore[override] @overload def getheader(self, name: str) -> str | None: - """ - Returns the value of the header matching *name*. + """Returns the value of the header matching *name*. If there are multiple matching headers, the values are combined into a single string separated by commas and spaces. @@ -264,14 +256,10 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): # type: ignore[misc] # incomp @overload def getheader(self, name: str, default: _T) -> str | _T: ... def getheaders(self) -> list[tuple[str, str]]: - """ - Return list of (header, value) tuples. - """ + """Return list of (header, value) tuples.""" def isclosed(self) -> bool: - """ - True if the connection is closed. - """ + """True if the connection is closed.""" def __iter__(self) -> Iterator[bytes]: ... def __enter__(self) -> Self: ... @@ -279,8 +267,7 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): # type: ignore[misc] # incomp self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None ) -> None: ... def info(self) -> email.message.Message: - """ - Returns an instance of the class mimetools.Message containing + """Returns an instance of the class mimetools.Message containing meta-information associated with the URL. When the method is HTTP, these headers are those returned by @@ -301,8 +288,7 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): # type: ignore[misc] # incomp """ def geturl(self) -> str: - """ - Return the real URL of the page. + """Return the real URL of the page. In some cases, the HTTP server redirects a client to another URL. The urlopen() function handles this transparently, but in @@ -312,8 +298,7 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): # type: ignore[misc] # incomp """ def getcode(self) -> int: - """ - Return the HTTP status code that was sent with the response, + """Return the HTTP status code that was sent with the response, or None if the URL is not an HTTP URL. """ @@ -345,13 +330,10 @@ class HTTPConnection: *, encode_chunked: bool = False, ) -> None: - """ - Send a complete request to the server. - """ + """Send a complete request to the server.""" def getresponse(self) -> HTTPResponse: - """ - Get the response from the server. + """Get the response from the server. If the HTTPConnection is in the correct state, returns an instance of HTTPResponse or of whatever object is returned by @@ -367,8 +349,7 @@ class HTTPConnection: def set_debuglevel(self, level: int) -> None: ... if sys.version_info >= (3, 12): def get_proxy_response_headers(self) -> HTTPMessage | None: - """ - Returns a dictionary with the headers of the response + """Returns a dictionary with the headers of the response received from the proxy server to the CONNECT request sent to set the tunnel. @@ -376,8 +357,7 @@ class HTTPConnection: """ def set_tunnel(self, host: str, port: int | None = None, headers: Mapping[str, str] | None = None) -> None: - """ - Set up host and port for HTTP CONNECT tunnelling. + """Set up host and port for HTTP CONNECT tunnelling. In a connection that uses HTTP CONNECT tunnelling, the host passed to the constructor is used as a proxy server that relays all communication @@ -399,18 +379,13 @@ class HTTPConnection: """ def connect(self) -> None: - """ - Connect to the host and port specified in __init__. - """ + """Connect to the host and port specified in __init__.""" def close(self) -> None: - """ - Close the connection to the HTTP server. - """ + """Close the connection to the HTTP server.""" def putrequest(self, method: str, url: str, skip_host: bool = False, skip_accept_encoding: bool = False) -> None: - """ - Send a request to the server. + """Send a request to the server. 'method' specifies an HTTP request method, e.g. 'GET'. 'url' specifies the object being requested, e.g. '/index.html'. @@ -420,15 +395,13 @@ class HTTPConnection: """ def putheader(self, header: str | bytes, *values: _HeaderValue) -> None: - """ - Send a request header line to the server. + """Send a request header line to the server. For example: h.putheader('Accept', 'text/html') """ def endheaders(self, message_body: _DataType | None = None, *, encode_chunked: bool = False) -> None: - """ - Indicate that the last header line has been sent to the server. + """Indicate that the last header line has been sent to the server. This method sends the request to the server. The optional message_body argument can be used to pass a message body associated with the @@ -436,16 +409,13 @@ class HTTPConnection: """ def send(self, data: _DataType | str) -> None: - """ - Send 'data' to the server. + """Send 'data' to the server. ``data`` can be a string object, a bytes object, an array object, a file-like object that supports a .read() method, or an iterable object. """ class HTTPSConnection(HTTPConnection): - """ - This class allows communication via SSL. - """ + """This class allows communication via SSL.""" # Can be `None` if `.connect()` was not called: sock: ssl.SSLSocket | MaybeNone diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/http/cookiejar.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/http/cookiejar.pyi index 1924dbc72c..37df513fea 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/http/cookiejar.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/http/cookiejar.pyi @@ -49,8 +49,7 @@ _T = TypeVar("_T") class LoadError(OSError): ... class CookieJar: - """ - Collection of HTTP cookies. + """Collection of HTTP cookies. You may not need to know about this class: try urllib.request.build_opener(HTTPCookieProcessor).open(url). @@ -64,36 +63,26 @@ class CookieJar: magic_re: ClassVar[Pattern[str]] # undocumented def __init__(self, policy: CookiePolicy | None = None) -> None: ... def add_cookie_header(self, request: Request) -> None: - """ - Add correct Cookie: header to request (urllib.request.Request object). + """Add correct Cookie: header to request (urllib.request.Request object). The Cookie2 header is also added unless policy.hide_cookie2 is true. """ def extract_cookies(self, response: HTTPResponse, request: Request) -> None: - """ - Extract cookies from response, where allowable given the request. - """ + """Extract cookies from response, where allowable given the request.""" def set_policy(self, policy: CookiePolicy) -> None: ... def make_cookies(self, response: HTTPResponse, request: Request) -> Sequence[Cookie]: - """ - Return sequence of Cookie objects extracted from response object. - """ + """Return sequence of Cookie objects extracted from response object.""" def set_cookie(self, cookie: Cookie) -> None: - """ - Set a cookie, without checking whether or not it should be set. - """ + """Set a cookie, without checking whether or not it should be set.""" def set_cookie_if_ok(self, cookie: Cookie, request: Request) -> None: - """ - Set a cookie if policy says it's OK to do so. - """ + """Set a cookie if policy says it's OK to do so.""" def clear(self, domain: str | None = None, path: str | None = None, name: str | None = None) -> None: - """ - Clear some cookies. + """Clear some cookies. Invoking this method without arguments will clear all cookies. If given a single argument, only cookies belonging to that domain will be @@ -105,16 +94,14 @@ class CookieJar: """ def clear_session_cookies(self) -> None: - """ - Discard all session cookies. + """Discard all session cookies. Note that the .save() method won't save session cookies anyway, unless you ask otherwise by passing a true ignore_discard argument. """ def clear_expired_cookies(self) -> None: # undocumented - """ - Discard all expired cookies. + """Discard all expired cookies. You probably don't need to call this method: expired cookies are never sent back to the server (provided you're using DefaultCookiePolicy), @@ -125,44 +112,33 @@ class CookieJar: def __iter__(self) -> Iterator[Cookie]: ... def __len__(self) -> int: - """ - Return number of contained cookies. - """ + """Return number of contained cookies.""" class FileCookieJar(CookieJar): - """ - CookieJar that can be loaded from and saved to a file. - """ + """CookieJar that can be loaded from and saved to a file.""" filename: str | None delayload: bool def __init__(self, filename: StrPath | None = None, delayload: bool = False, policy: CookiePolicy | None = None) -> None: - """ - Cookies are NOT loaded from the named file until either the .load() or + """Cookies are NOT loaded from the named file until either the .load() or .revert() method is called. """ def save(self, filename: str | None = None, ignore_discard: bool = False, ignore_expires: bool = False) -> None: - """ - Save cookies to a file. - """ + """Save cookies to a file.""" def load(self, filename: str | None = None, ignore_discard: bool = False, ignore_expires: bool = False) -> None: - """ - Load cookies from a file. - """ + """Load cookies from a file.""" def revert(self, filename: str | None = None, ignore_discard: bool = False, ignore_expires: bool = False) -> None: - """ - Clear all cookies and reload cookies from a saved file. + """Clear all cookies and reload cookies from a saved file. Raises LoadError (or OSError) if reversion is not successful; the object's state will not be altered if this happens. """ class MozillaCookieJar(FileCookieJar): - """ - WARNING: you may want to backup your browser's cookies file if you use + """WARNING: you may want to backup your browser's cookies file if you use this class to save cookies. I *think* it works, but there have been bugs in the past! @@ -194,8 +170,7 @@ class MozillaCookieJar(FileCookieJar): header: ClassVar[str] # undocumented class LWPCookieJar(FileCookieJar): - """ - The LWPCookieJar saves a sequence of "Set-Cookie3" lines. + """The LWPCookieJar saves a sequence of "Set-Cookie3" lines. "Set-Cookie3" is the format used by the libwww-perl library, not known to be compatible with any browser, but which is easy to read and doesn't lose information about RFC 2965 cookies. @@ -206,15 +181,13 @@ class LWPCookieJar(FileCookieJar): """ def as_lwp_str(self, ignore_discard: bool = True, ignore_expires: bool = True) -> str: # undocumented - """ - Return cookies as a string of "\\n"-separated "Set-Cookie3" headers. + """Return cookies as a string of "\\n"-separated "Set-Cookie3" headers. ignore_discard and ignore_expires: see docstring for FileCookieJar.save """ class CookiePolicy: - """ - Defines which cookies get accepted from and returned to server. + """Defines which cookies get accepted from and returned to server. May also modify cookies, though this is probably a bad idea. @@ -226,32 +199,23 @@ class CookiePolicy: rfc2965: bool hide_cookie2: bool def set_ok(self, cookie: Cookie, request: Request) -> bool: - """ - Return true if (and only if) cookie should be accepted from server. + """Return true if (and only if) cookie should be accepted from server. Currently, pre-expired cookies never get this far -- the CookieJar class deletes such cookies itself. """ def return_ok(self, cookie: Cookie, request: Request) -> bool: - """ - Return true if (and only if) cookie should be returned to server. - """ + """Return true if (and only if) cookie should be returned to server.""" def domain_return_ok(self, domain: str, request: Request) -> bool: - """ - Return false if cookies should not be returned, given cookie domain. - """ + """Return false if cookies should not be returned, given cookie domain.""" def path_return_ok(self, path: str, request: Request) -> bool: - """ - Return false if cookies should not be returned, given cookie path. - """ + """Return false if cookies should not be returned, given cookie path.""" class DefaultCookiePolicy(CookiePolicy): - """ - Implements the standard rules for accepting and returning cookies. - """ + """Implements the standard rules for accepting and returning cookies.""" rfc2109_as_netscape: bool strict_domain: bool @@ -281,30 +245,20 @@ class DefaultCookiePolicy(CookiePolicy): strict_ns_set_path: bool = False, secure_protocols: Sequence[str] = ("https", "wss"), ) -> None: - """ - Constructor arguments should be passed as keyword arguments only. - """ + """Constructor arguments should be passed as keyword arguments only.""" def blocked_domains(self) -> tuple[str, ...]: - """ - Return the sequence of blocked domains (as a tuple). - """ + """Return the sequence of blocked domains (as a tuple).""" def set_blocked_domains(self, blocked_domains: Sequence[str]) -> None: - """ - Set the sequence of blocked domains. - """ + """Set the sequence of blocked domains.""" def is_blocked(self, domain: str) -> bool: ... def allowed_domains(self) -> tuple[str, ...] | None: - """ - Return None, or the sequence of allowed domains (as a tuple). - """ + """Return None, or the sequence of allowed domains (as a tuple).""" def set_allowed_domains(self, allowed_domains: Sequence[str] | None) -> None: - """ - Set the sequence of allowed domains, or None. - """ + """Set the sequence of allowed domains, or None.""" def is_not_allowed(self, domain: str) -> bool: ... def set_ok_version(self, cookie: Cookie, request: Request) -> bool: ... # undocumented @@ -321,8 +275,7 @@ class DefaultCookiePolicy(CookiePolicy): def return_ok_domain(self, cookie: Cookie, request: Request) -> bool: ... # undocumented class Cookie: - """ - HTTP Cookie. + """HTTP Cookie. This class represents both Netscape and RFC 2965 cookies. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/http/cookies.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/http/cookies.pyi index 03f43899c8..a9eacda2b8 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/http/cookies.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/http/cookies.pyi @@ -1,4 +1,5 @@ """ + Here's a sample session to show how to use this module. At the moment, this is the only documentation. @@ -100,8 +101,7 @@ _T = TypeVar("_T") @overload def _quote(str: None) -> None: - """ - Quote a string for use in a cookie header. + """Quote a string for use in a cookie header. If the string does not need to be double-quoted, then just return the string. Otherwise, surround the string in doublequotes and quote @@ -118,8 +118,7 @@ def _unquote(str: str) -> str: ... class CookieError(Exception): ... class Morsel(dict[str, Any], Generic[_T]): - """ - A class to hold ONE (key, value) pair. + """A class to hold ONE (key, value) pair. In a cookie, each such pair may have several attributes, so this class is used to keep the attributes associated with the appropriate key,value pair. @@ -149,21 +148,17 @@ class Morsel(dict[str, Any], Generic[_T]): def __eq__(self, morsel: object) -> bool: ... def __setitem__(self, K: str, V: Any) -> None: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ class BaseCookie(dict[str, Morsel[_T]], Generic[_T]): - """ - A container class for a set of Morsels. - """ + """A container class for a set of Morsels.""" def __init__(self, input: _DataType | None = None) -> None: ... def value_decode(self, val: str) -> tuple[_T, str]: - """ - real_value, coded_value = value_decode(STRING) + """real_value, coded_value = value_decode(STRING) Called prior to setting a cookie's value from the network representation. The VALUE is the value read from HTTP header. @@ -171,39 +166,30 @@ class BaseCookie(dict[str, Morsel[_T]], Generic[_T]): """ def value_encode(self, val: _T) -> tuple[_T, str]: - """ - real_value, coded_value = value_encode(VALUE) + """real_value, coded_value = value_encode(VALUE) Called prior to setting a cookie's value from the dictionary representation. The VALUE is the value being assigned. Override this function to modify the behavior of cookies. """ def output(self, attrs: list[str] | None = None, header: str = "Set-Cookie:", sep: str = "\r\n") -> str: - """ - Return a string suitable for HTTP. - """ + """Return a string suitable for HTTP.""" __str__ = output def js_output(self, attrs: list[str] | None = None) -> str: - """ - Return a string suitable for JavaScript. - """ + """Return a string suitable for JavaScript.""" def load(self, rawdata: _DataType) -> None: - """ - Load cookies from a string (presumably HTTP_COOKIE) or + """Load cookies from a string (presumably HTTP_COOKIE) or from a dictionary. Loading cookies from a dictionary 'd' is equivalent to calling: map(Cookie.__setitem__, d.keys(), d.values()) """ def __setitem__(self, key: str, value: str | Morsel[_T]) -> None: - """ - Dictionary style assignment. - """ + """Dictionary style assignment.""" class SimpleCookie(BaseCookie[str]): - """ - SimpleCookie supports strings as cookie values. When setting + """SimpleCookie supports strings as cookie values. When setting the value using the dictionary assignment notation, SimpleCookie calls the builtin str() to convert the value to a string. Values received from HTTP are kept as strings. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/http/server.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/http/server.pyi index fb70bda390..963b4655e1 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/http/server.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/http/server.pyi @@ -93,15 +93,12 @@ if sys.version_info >= (3, 14): alpn_protocols: Iterable[str] | None = None, ) -> None: ... def server_activate(self) -> None: - """ - Wrap the socket in SSLSocket. - """ + """Wrap the socket in SSLSocket.""" class ThreadingHTTPSServer(socketserver.ThreadingMixIn, HTTPSServer): ... class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): - """ - HTTP request handler base class. + """HTTP request handler base class. The following explanation of HTTP serves to guide you through the code as well as to expose any misunderstandings I may have about @@ -220,8 +217,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): weekdayname: ClassVar[Sequence[str]] # undocumented monthname: ClassVar[Sequence[str | None]] # undocumented def handle_one_request(self) -> None: - """ - Handle a single HTTP request. + """Handle a single HTTP request. You normally don't need to override this method; see the class __doc__ string for information on how to handle specific HTTP @@ -229,8 +225,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): """ def handle_expect_100(self) -> bool: - """ - Decide what to do with an "Expect: 100-continue" header. + """Decide what to do with an "Expect: 100-continue" header. If the client is expecting a 100 Continue response, we must respond with either a 100 Continue or a final response before @@ -244,8 +239,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): """ def send_error(self, code: int, message: str | None = None, explain: str | None = None) -> None: - """ - Send and log an error reply. + """Send and log an error reply. Arguments are * code: an HTTP error code @@ -262,8 +256,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): """ def send_response(self, code: int, message: str | None = None) -> None: - """ - Add the response header to the headers buffer and log the + """Add the response header to the headers buffer and log the response code. Also send two standard headers with the server software @@ -271,31 +264,23 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): """ def send_header(self, keyword: str, value: str) -> None: - """ - Send a MIME header to the headers buffer. - """ + """Send a MIME header to the headers buffer.""" def send_response_only(self, code: int, message: str | None = None) -> None: - """ - Send the response header only. - """ + """Send the response header only.""" def end_headers(self) -> None: - """ - Send the blank line ending the MIME headers. - """ + """Send the blank line ending the MIME headers.""" def flush_headers(self) -> None: ... def log_request(self, code: int | str = "-", size: int | str = "-") -> None: - """ - Log an accepted request. + """Log an accepted request. This is called by send_response(). """ def log_error(self, format: str, *args: Any) -> None: - """ - Log an error. + """Log an error. This is called when a request cannot be fulfilled. By default it passes the message on to log_message(). @@ -306,8 +291,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): """ def log_message(self, format: str, *args: Any) -> None: - """ - Log an arbitrary message. + """Log an arbitrary message. This is used by all other logging functions. Override it if you have specific logging wishes. @@ -326,28 +310,19 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): """ def version_string(self) -> str: - """ - Return the server software version string. - """ + """Return the server software version string.""" def date_time_string(self, timestamp: float | None = None) -> str: - """ - Return the current date and time formatted for a message header. - """ + """Return the current date and time formatted for a message header.""" def log_date_time_string(self) -> str: - """ - Return the current time formatted for logging. - """ + """Return the current time formatted for logging.""" def address_string(self) -> str: - """ - Return the client address. - """ + """Return the client address.""" def parse_request(self) -> bool: # undocumented - """ - Parse a request (internal). + """Parse a request (internal). The request should be stored in self.raw_requestline; the results are in self.command, self.path, self.request_version and @@ -358,8 +333,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): """ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): - """ - Simple HTTP request handler with GET and HEAD commands. + """Simple HTTP request handler with GET and HEAD commands. This serves files from the current directory and any of its subdirectories. The MIME type for files is determined by @@ -382,18 +356,13 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): directory: StrPath | None = None, ) -> None: ... def do_GET(self) -> None: - """ - Serve a GET request. - """ + """Serve a GET request.""" def do_HEAD(self) -> None: - """ - Serve a HEAD request. - """ + """Serve a HEAD request.""" def send_head(self) -> io.BytesIO | BinaryIO | None: # undocumented - """ - Common code for GET and HEAD commands. + """Common code for GET and HEAD commands. This sends the response code and MIME headers. @@ -404,8 +373,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): """ def list_directory(self, path: StrPath) -> io.BytesIO | None: # undocumented - """ - Helper to produce a directory listing (absent index.html). + """Helper to produce a directory listing (absent index.html). Return value is either a file object, or None (indicating an error). In either case, the headers are sent, making the @@ -413,8 +381,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): """ def translate_path(self, path: str) -> str: # undocumented - """ - Translate a /-separated PATH to the local filename syntax. + """Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should @@ -422,8 +389,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): """ def copyfile(self, source: SupportsRead[AnyStr], outputfile: SupportsWrite[AnyStr]) -> None: # undocumented - """ - Copy all data between two file objects. + """Copy all data between two file objects. The SOURCE argument is a file object open for reading (or anything with a read() method) and the DESTINATION @@ -437,8 +403,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): """ def guess_type(self, path: StrPath) -> str: # undocumented - """ - Guess the type of a file. + """Guess the type of a file. Argument is a PATH (a filename). @@ -452,14 +417,11 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): """ def executable(path: StrPath) -> bool: # undocumented - """ - Test for executable file. - """ + """Test for executable file.""" @deprecated("Deprecated in Python 3.13; removal scheduled for Python 3.15") class CGIHTTPRequestHandler(SimpleHTTPRequestHandler): - """ - Complete HTTP server with GET, HEAD and POST commands. + """Complete HTTP server with GET, HEAD and POST commands. GET and HEAD also support running CGI scripts. @@ -469,15 +431,13 @@ class CGIHTTPRequestHandler(SimpleHTTPRequestHandler): cgi_directories: list[str] have_fork: bool # undocumented def do_POST(self) -> None: - """ - Serve a POST request. + """Serve a POST request. This is only implemented for CGI scripts. """ def is_cgi(self) -> bool: # undocumented - """ - Test whether self.path corresponds to a CGI script. + """Test whether self.path corresponds to a CGI script. Returns True and updates the cgi_info attribute to the tuple (dir, rest) if self.path requires running a CGI script. @@ -492,16 +452,10 @@ class CGIHTTPRequestHandler(SimpleHTTPRequestHandler): """ def is_executable(self, path: StrPath) -> bool: # undocumented - """ - Test whether argument path is an executable file. - """ + """Test whether argument path is an executable file.""" def is_python(self, path: StrPath) -> bool: # undocumented - """ - Test whether argument path is a Python script. - """ + """Test whether argument path is a Python script.""" def run_cgi(self) -> None: # undocumented - """ - Execute a CGI script. - """ + """Execute a CGI script.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/imaplib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/imaplib.pyi index 7e66db1d6a..8f8ec666af 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/imaplib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/imaplib.pyi @@ -36,8 +36,7 @@ _AnyResponseData: TypeAlias = list[None] | list[bytes | tuple[bytes, bytes]] Commands: dict[str, tuple[str, ...]] class IMAP4: - """ - IMAP4 client class. + """IMAP4 client class. Instantiate with: IMAP4([host[, port[, timeout=None]]]) @@ -103,8 +102,7 @@ class IMAP4: PROTOCOL_VERSION: str def __init__(self, host: str = "", port: int = 143, timeout: float | None = None) -> None: ... def open(self, host: str = "", port: int = 143, timeout: float | None = None) -> None: - """ - Setup connection to remote server on "host:port" + """Setup connection to remote server on "host:port" (default: localhost:standard IMAP4 port). This connection will be used by the routines: read, readline, send, shutdown. @@ -121,35 +119,25 @@ class IMAP4: port: int sock: _socket def read(self, size: int) -> bytes: - """ - Read 'size' bytes from remote. - """ + """Read 'size' bytes from remote.""" def readline(self) -> bytes: - """ - Read line from remote. - """ + """Read line from remote.""" def send(self, data: ReadableBuffer) -> None: - """ - Send data to remote. - """ + """Send data to remote.""" def shutdown(self) -> None: - """ - Close I/O established in "open". - """ + """Close I/O established in "open".""" def socket(self) -> _socket: - """ - Return socket instance used to connect to IMAP4 server. + """Return socket instance used to connect to IMAP4 server. socket = .socket() """ def recent(self) -> _CommandResults: - """ - Return most recent 'RECENT' responses if any exist, + """Return most recent 'RECENT' responses if any exist, else prompt server for an update using the 'NOOP' command. (typ, [data]) = .recent() @@ -159,8 +147,7 @@ class IMAP4: """ def response(self, code: str) -> _CommandResults: - """ - Return data for response 'code' if received, or None. + """Return data for response 'code' if received, or None. Old value for response 'code' is cleared. @@ -168,8 +155,7 @@ class IMAP4: """ def append(self, mailbox: str, flags: str, date_time: str, message: ReadableBuffer) -> str: - """ - Append message to named mailbox. + """Append message to named mailbox. (typ, [data]) = .append(mailbox, flags, date_time, message) @@ -177,8 +163,7 @@ class IMAP4: """ def authenticate(self, mechanism: str, authobject: Callable[[bytes], bytes | None]) -> tuple[str, str]: - """ - Authenticate command - requires response processing. + """Authenticate command - requires response processing. 'mechanism' specifies which authentication mechanism is to be used - it must appear in .capabilities in the @@ -195,21 +180,18 @@ class IMAP4: """ def capability(self) -> _CommandResults: - """ - (typ, [data]) = .capability() + """(typ, [data]) = .capability() Fetch capabilities list from server. """ def check(self) -> _CommandResults: - """ - Checkpoint mailbox on server. + """Checkpoint mailbox on server. (typ, [data]) = .check() """ def close(self) -> _CommandResults: - """ - Close currently selected mailbox. + """Close currently selected mailbox. Deleted messages are removed from writable mailbox. This is the recommended command before 'LOGOUT'. @@ -218,36 +200,31 @@ class IMAP4: """ def copy(self, message_set: str, new_mailbox: str) -> _CommandResults: - """ - Copy 'message_set' messages onto end of 'new_mailbox'. + """Copy 'message_set' messages onto end of 'new_mailbox'. (typ, [data]) = .copy(message_set, new_mailbox) """ def create(self, mailbox: str) -> _CommandResults: - """ - Create new mailbox. + """Create new mailbox. (typ, [data]) = .create(mailbox) """ def delete(self, mailbox: str) -> _CommandResults: - """ - Delete old mailbox. + """Delete old mailbox. (typ, [data]) = .delete(mailbox) """ def deleteacl(self, mailbox: str, who: str) -> _CommandResults: - """ - Delete the ACLs (remove any rights) set for who on mailbox. + """Delete the ACLs (remove any rights) set for who on mailbox. (typ, [data]) = .deleteacl(mailbox, who) """ def enable(self, capability: str) -> _CommandResults: - """ - Send an RFC5161 enable string to the server. + """Send an RFC5161 enable string to the server. (typ, [data]) = .enable(capability) """ @@ -255,8 +232,7 @@ class IMAP4: def __enter__(self) -> Self: ... def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... def expunge(self) -> _CommandResults: - """ - Permanently remove deleted items from selected mailbox. + """Permanently remove deleted items from selected mailbox. Generates 'EXPUNGE' response for each deleted message. @@ -266,8 +242,7 @@ class IMAP4: """ def fetch(self, message_set: str, message_parts: str) -> tuple[str, _AnyResponseData]: - """ - Fetch (parts of) messages. + """Fetch (parts of) messages. (typ, [data, ...]) = .fetch(message_set, message_parts) @@ -278,21 +253,18 @@ class IMAP4: """ def getacl(self, mailbox: str) -> _CommandResults: - """ - Get the ACLs for a mailbox. + """Get the ACLs for a mailbox. (typ, [data]) = .getacl(mailbox) """ def getannotation(self, mailbox: str, entry: str, attribute: str) -> _CommandResults: - """ - (typ, [data]) = .getannotation(mailbox, entry, attribute) + """(typ, [data]) = .getannotation(mailbox, entry, attribute) Retrieve ANNOTATIONs. """ def getquota(self, root: str) -> _CommandResults: - """ - Get the quota root's resource usage and limits. + """Get the quota root's resource usage and limits. Part of the IMAP4 QUOTA extension defined in rfc2087. @@ -300,15 +272,13 @@ class IMAP4: """ def getquotaroot(self, mailbox: str) -> _CommandResults: - """ - Get the list of quota roots for the named mailbox. + """Get the list of quota roots for the named mailbox. (typ, [[QUOTAROOT responses...], [QUOTA responses]]) = .getquotaroot(mailbox) """ if sys.version_info >= (3, 14): def idle(self, duration: float | None = None) -> Idler: - """ - Return an iterable IDLE context manager producing untagged responses. + """Return an iterable IDLE context manager producing untagged responses. If the argument is not None, limit iteration to 'duration' seconds. with M.idle(duration=29 * 60) as idler: @@ -319,8 +289,7 @@ class IMAP4: """ def list(self, directory: str = '""', pattern: str = "*") -> tuple[str, _AnyResponseData]: - """ - List mailbox names in directory matching pattern. + """List mailbox names in directory matching pattern. (typ, [data]) = .list(directory='""', pattern='*') @@ -328,8 +297,7 @@ class IMAP4: """ def login(self, user: str, password: str) -> tuple[Literal["OK"], _list[bytes]]: - """ - Identify client using plaintext password. + """Identify client using plaintext password. (typ, [data]) = .login(user, password) @@ -337,15 +305,13 @@ class IMAP4: """ def login_cram_md5(self, user: str, password: str) -> _CommandResults: - """ - Force use of CRAM-MD5 authentication. + """Force use of CRAM-MD5 authentication. (typ, [data]) = .login_cram_md5(user, password) """ def logout(self) -> tuple[str, _AnyResponseData]: - """ - Shutdown connection to server. + """Shutdown connection to server. (typ, [data]) = .logout() @@ -353,8 +319,7 @@ class IMAP4: """ def lsub(self, directory: str = '""', pattern: str = "*") -> _CommandResults: - """ - List 'subscribed' mailbox names in directory matching pattern. + """List 'subscribed' mailbox names in directory matching pattern. (typ, [data, ...]) = .lsub(directory='""', pattern='*') @@ -362,29 +327,25 @@ class IMAP4: """ def myrights(self, mailbox: str) -> _CommandResults: - """ - Show my ACLs for a mailbox (i.e. the rights that I have on mailbox). + """Show my ACLs for a mailbox (i.e. the rights that I have on mailbox). (typ, [data]) = .myrights(mailbox) """ def namespace(self) -> _CommandResults: - """ - Returns IMAP namespaces ala rfc2342 + """Returns IMAP namespaces ala rfc2342 (typ, [data, ...]) = .namespace() """ def noop(self) -> tuple[str, _list[bytes]]: - """ - Send NOOP command. + """Send NOOP command. (typ, [data]) = .noop() """ def partial(self, message_num: str, message_part: str, start: str, length: str) -> _CommandResults: - """ - Fetch truncated part of a message. + """Fetch truncated part of a message. (typ, [data, ...]) = .partial(message_num, message_part, start, length) @@ -392,8 +353,7 @@ class IMAP4: """ def proxyauth(self, user: str) -> _CommandResults: - """ - Assume authentication as "user". + """Assume authentication as "user". Allows an authorised administrator to proxy into any user's mailbox. @@ -402,15 +362,13 @@ class IMAP4: """ def rename(self, oldmailbox: str, newmailbox: str) -> _CommandResults: - """ - Rename old mailbox name to new. + """Rename old mailbox name to new. (typ, [data]) = .rename(oldmailbox, newmailbox) """ def search(self, charset: str | None, *criteria: str) -> _CommandResults: - """ - Search mailbox for matching messages. + """Search mailbox for matching messages. (typ, [data]) = .search(charset, criterion, ...) @@ -419,8 +377,7 @@ class IMAP4: """ def select(self, mailbox: str = "INBOX", readonly: bool = False) -> tuple[str, _list[bytes | None]]: - """ - Select a mailbox. + """Select a mailbox. Flush all untagged responses. @@ -433,64 +390,55 @@ class IMAP4: """ def setacl(self, mailbox: str, who: str, what: str) -> _CommandResults: - """ - Set a mailbox acl. + """Set a mailbox acl. (typ, [data]) = .setacl(mailbox, who, what) """ def setannotation(self, *args: str) -> _CommandResults: - """ - (typ, [data]) = .setannotation(mailbox[, entry, attribute]+) + """(typ, [data]) = .setannotation(mailbox[, entry, attribute]+) Set ANNOTATIONs. """ def setquota(self, root: str, limits: str) -> _CommandResults: - """ - Set the quota root's resource limits. + """Set the quota root's resource limits. (typ, [data]) = .setquota(root, limits) """ def sort(self, sort_criteria: str, charset: str, *search_criteria: str) -> _CommandResults: - """ - IMAP4rev1 extension SORT command. + """IMAP4rev1 extension SORT command. (typ, [data]) = .sort(sort_criteria, charset, search_criteria, ...) """ def starttls(self, ssl_context: Any | None = None) -> tuple[Literal["OK"], _list[None]]: ... def status(self, mailbox: str, names: str) -> _CommandResults: - """ - Request named status conditions for mailbox. + """Request named status conditions for mailbox. (typ, [data]) = .status(mailbox, names) """ def store(self, message_set: str, command: str, flags: str) -> _CommandResults: - """ - Alters flag dispositions for messages in mailbox. + """Alters flag dispositions for messages in mailbox. (typ, [data]) = .store(message_set, command, flags) """ def subscribe(self, mailbox: str) -> _CommandResults: - """ - Subscribe to new mailbox. + """Subscribe to new mailbox. (typ, [data]) = .subscribe(mailbox) """ def thread(self, threading_algorithm: str, charset: str, *search_criteria: str) -> _CommandResults: - """ - IMAPrev1 extension THREAD command. + """IMAPrev1 extension THREAD command. (type, [data]) = .thread(threading_algorithm, charset, search_criteria, ...) """ def uid(self, command: str, *args: str) -> _CommandResults: - """ - Execute "command arg ..." with messages identified by UID, + """Execute "command arg ..." with messages identified by UID, rather than message number. (typ, [data]) = .uid(command, arg1, arg2, ...) @@ -499,15 +447,13 @@ class IMAP4: """ def unsubscribe(self, mailbox: str) -> _CommandResults: - """ - Unsubscribe from old mailbox. + """Unsubscribe from old mailbox. (typ, [data]) = .unsubscribe(mailbox) """ def unselect(self) -> _CommandResults: - """ - Free server's resources associated with the selected mailbox + """Free server's resources associated with the selected mailbox and returns the server to the authenticated state. This command performs the same actions as CLOSE, except that no messages are permanently removed from the currently @@ -517,8 +463,7 @@ class IMAP4: """ def xatom(self, name: str, *args: str) -> _CommandResults: - """ - Allow simple extension commands + """Allow simple extension commands notified by server in CAPABILITY response. Assumes command is legal in current state. @@ -532,8 +477,7 @@ class IMAP4: if sys.version_info >= (3, 14): class Idler: - """ - Iterable IDLE context manager: start IDLE & produce untagged responses. + """Iterable IDLE context manager: start IDLE & produce untagged responses. An object of this type is returned by the IMAP4.idle() method. @@ -546,8 +490,7 @@ if sys.version_info >= (3, 14): def __iter__(self) -> Self: ... def __next__(self) -> tuple[str, float | None]: ... def burst(self, interval: float = 0.1) -> Generator[tuple[str, float | None]]: - """ - Yield a burst of responses no more than 'interval' seconds apart. + """Yield a burst of responses no more than 'interval' seconds apart. with M.idle() as idler: # get a response and any others following by < 0.1 seconds @@ -559,8 +502,7 @@ if sys.version_info >= (3, 14): """ class IMAP4_SSL(IMAP4): - """ - IMAP4 client class over SSL connection + """IMAP4 client class over SSL connection Instantiate with: IMAP4_SSL([host[, port[, ssl_context[, timeout=None]]]]) @@ -600,8 +542,7 @@ class IMAP4_SSL(IMAP4): file: IO[Any] def open(self, host: str = "", port: int | None = 993, timeout: float | None = None) -> None: - """ - Setup connection to remote server on "host:port". + """Setup connection to remote server on "host:port". (default: localhost:standard IMAP4 SSL port). This connection will be used by the routines: read, readline, send, shutdown. @@ -610,8 +551,7 @@ class IMAP4_SSL(IMAP4): def ssl(self) -> SSLSocket: ... class IMAP4_stream(IMAP4): - """ - IMAP4 client class over a stream + """IMAP4 client class over a stream Instantiate with: IMAP4_stream(command) @@ -632,15 +572,13 @@ class IMAP4_stream(IMAP4): writefile: IO[Any] readfile: IO[Any] def open(self, host: str | None = None, port: int | None = None, timeout: float | None = None) -> None: - """ - Setup a stream connection. + """Setup a stream connection. This connection will be used by the routines: read, readline, send, shutdown. """ class _Authenticator: - """ - Private class to provide en/decoding + """Private class to provide en/decoding for base64-based authentication conversation. """ @@ -651,26 +589,20 @@ class _Authenticator: def decode(self, inp: str | SizedBuffer) -> bytes: ... def Internaldate2tuple(resp: ReadableBuffer) -> time.struct_time | None: - """ - Parse an IMAP4 INTERNALDATE string. + """Parse an IMAP4 INTERNALDATE string. Return corresponding local time. The return value is a time.struct_time tuple or None if the string has wrong format. """ def Int2AP(num: SupportsAbs[SupportsInt]) -> bytes: - """ - Convert integer to A-P string representation. - """ + """Convert integer to A-P string representation.""" def ParseFlags(resp: ReadableBuffer) -> tuple[bytes, ...]: - """ - Convert IMAP4 flags response to python tuple. - """ + """Convert IMAP4 flags response to python tuple.""" def Time2Internaldate(date_time: float | time.struct_time | time._TimeTuple | datetime | str) -> str: - """ - Convert date_time to IMAP4 INTERNALDATE representation. + """Convert date_time to IMAP4 INTERNALDATE representation. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'. The date_time argument can be a number (int or float) representing diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/imghdr.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/imghdr.pyi index 8823747fbf..00b8af25bc 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/imghdr.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/imghdr.pyi @@ -15,9 +15,7 @@ class _ReadableBinary(Protocol): @overload def what(file: StrPath | _ReadableBinary, h: None = None) -> str | None: - """ - Return the type of image contained in a file or byte stream. - """ + """Return the type of image contained in a file or byte stream.""" @overload def what(file: Any, h: bytes) -> str | None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/imp.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/imp.pyi index a5d95613fc..eb1fccb1ec 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/imp.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/imp.pyi @@ -35,8 +35,7 @@ PY_CODERESOURCE: int IMP_HOOK: int def new_module(name: str) -> types.ModuleType: - """ - **DEPRECATED** + """**DEPRECATED** Create a new module. @@ -44,20 +43,16 @@ def new_module(name: str) -> types.ModuleType: """ def get_magic() -> bytes: - """ - **DEPRECATED** + """**DEPRECATED** Return the magic number for .pyc files. """ def get_tag() -> str: - """ - Return the magic tag for .pyc files. - """ + """Return the magic tag for .pyc files.""" def cache_from_source(path: StrPath, debug_override: bool | None = None) -> str: - """ - **DEPRECATED** + """**DEPRECATED** Given the path to a .py file, return the path to its .pyc file. @@ -71,8 +66,7 @@ def cache_from_source(path: StrPath, debug_override: bool | None = None) -> str: """ def source_from_cache(path: StrPath) -> str: - """ - **DEPRECATED** + """**DEPRECATED** Given the path to a .pyc. file, return the path to its .py file. @@ -83,22 +77,17 @@ def source_from_cache(path: StrPath) -> str: """ def get_suffixes() -> list[tuple[str, str, int]]: - """ - **DEPRECATED** - """ + """**DEPRECATED**""" class NullImporter: - """ - **DEPRECATED** + """**DEPRECATED** Null import object. """ def __init__(self, path: StrPath) -> None: ... def find_module(self, fullname: Any) -> None: - """ - Always returns None. - """ + """Always returns None.""" # Technically, a text file has to support a slightly different set of operations than a binary file, # but we ignore that here. @@ -113,18 +102,13 @@ class _FileLike(Protocol): # PathLike doesn't work for the pathname argument here def load_source(name: str, pathname: str, file: _FileLike | None = None) -> types.ModuleType: ... def load_compiled(name: str, pathname: str, file: _FileLike | None = None) -> types.ModuleType: - """ - **DEPRECATED** - """ + """**DEPRECATED**""" def load_package(name: str, path: StrPath) -> types.ModuleType: - """ - **DEPRECATED** - """ + """**DEPRECATED**""" def load_module(name: str, file: _FileLike | None, filename: str, details: tuple[str, str, int]) -> types.ModuleType: - """ - **DEPRECATED** + """**DEPRECATED** Load a module, given information returned by find_module(). @@ -135,8 +119,7 @@ def load_module(name: str, file: _FileLike | None, filename: str, details: tuple def find_module( name: str, path: None | list[str] | list[PathLike[str]] | list[StrPath] = None ) -> tuple[IO[Any], str, tuple[str, str, int]]: - """ - **DEPRECATED** + """**DEPRECATED** Search for a module. @@ -147,8 +130,7 @@ def find_module( """ def reload(module: types.ModuleType) -> types.ModuleType: - """ - **DEPRECATED** + """**DEPRECATED** Reload the module and return it. @@ -156,16 +138,14 @@ def reload(module: types.ModuleType) -> types.ModuleType: """ def init_builtin(name: str) -> types.ModuleType | None: - """ - **DEPRECATED** + """**DEPRECATED** Load and return a built-in module by name, or None is such module doesn't exist """ def load_dynamic(name: str, path: str, file: Any = None) -> types.ModuleType: # file argument is ignored - """ - **DEPRECATED** + """**DEPRECATED** Load an extension module. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/__init__.pyi index f122c7c1b4..a7c8a8e075 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/__init__.pyi @@ -11,8 +11,7 @@ __all__ = ["__import__", "import_module", "invalidate_caches", "reload"] # `importlib.import_module` return type should be kept the same as `builtins.__import__` def import_module(name: str, package: str | None = None) -> ModuleType: - """ - Import a module. + """Import a module. The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the @@ -21,8 +20,7 @@ def import_module(name: str, package: str | None = None) -> ModuleType: if sys.version_info < (3, 12): def find_loader(name: str, path: str | None = None) -> Loader | None: - """ - Return the loader for the specified module. + """Return the loader for the specified module. This is a backward-compatible wrapper around find_spec(). @@ -30,14 +28,12 @@ if sys.version_info < (3, 12): """ def invalidate_caches() -> None: - """ - Call the invalidate_caches() method on all meta path finders stored in + """Call the invalidate_caches() method on all meta path finders stored in sys.meta_path (where implemented). """ def reload(module: ModuleType) -> ModuleType: - """ - Reload the module and return it. + """Reload the module and return it. The module must have been successfully imported before. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/_abc.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/_abc.pyi index 2876a86ccf..e53e76180d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/_abc.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/_abc.pyi @@ -9,13 +9,10 @@ from importlib.machinery import ModuleSpec if sys.version_info >= (3, 10): class Loader(metaclass=ABCMeta): - """ - Abstract base class for import loaders. - """ + """Abstract base class for import loaders.""" def load_module(self, fullname: str) -> types.ModuleType: - """ - Return the loaded module. + """Return the loaded module. The module must be added to sys.modules and have import-related attributes set properly. The fullname is a str. @@ -30,8 +27,7 @@ if sys.version_info >= (3, 10): def module_repr(self, module: types.ModuleType) -> str: ... def create_module(self, spec: ModuleSpec) -> types.ModuleType | None: - """ - Return a module to initialize and into which to load. + """Return a module to initialize and into which to load. This method should raise ImportError if anything prevents it from creating a new module. It may return None to indicate diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/abc.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/abc.pyi index 68c290e64a..d7dc14bd5e 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/abc.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/abc.pyi @@ -33,13 +33,10 @@ if sys.version_info >= (3, 10): from importlib._abc import Loader as Loader else: class Loader(metaclass=ABCMeta): - """ - Abstract base class for import loaders. - """ + """Abstract base class for import loaders.""" def load_module(self, fullname: str) -> types.ModuleType: - """ - Return the loaded module. + """Return the loaded module. The module must be added to sys.modules and have import-related attributes set properly. The fullname is a str. @@ -52,8 +49,7 @@ else: """ def module_repr(self, module: types.ModuleType) -> str: - """ - Return a module's repr. + """Return a module's repr. Used by the module type when the method does not raise NotImplementedError. @@ -62,8 +58,7 @@ else: """ def create_module(self, spec: ModuleSpec) -> types.ModuleType | None: - """ - Return a module to initialize and into which to load. + """Return a module to initialize and into which to load. This method should raise ImportError if anything prevents it from creating a new module. It may return None to indicate @@ -75,8 +70,7 @@ else: if sys.version_info < (3, 12): class Finder(metaclass=ABCMeta): - """ - Legacy abstract base class for import finders. + """Legacy abstract base class for import finders. It may be subclassed for compatibility with legacy third party reimplementations of the import system. Otherwise, finder @@ -88,8 +82,7 @@ if sys.version_info < (3, 12): @deprecated("Deprecated as of Python 3.7: Use importlib.resources.abc.TraversableResources instead.") class ResourceLoader(Loader): - """ - Abstract base class for loaders which can return data from their + """Abstract base class for loaders which can return data from their back-end storage. This ABC represents one of the optional protocols specified by PEP 302. @@ -97,30 +90,26 @@ class ResourceLoader(Loader): @abstractmethod def get_data(self, path: str) -> bytes: - """ - Abstract method which when implemented should return the bytes for + """Abstract method which when implemented should return the bytes for the specified path. The path must be a str. """ class InspectLoader(Loader): - """ - Abstract base class for loaders which support inspection about the + """Abstract base class for loaders which support inspection about the modules they can load. This ABC represents one of the optional protocols specified by PEP 302. """ def is_package(self, fullname: str) -> bool: - """ - Optional method which when implemented should return whether the + """Optional method which when implemented should return whether the module is a package. The fullname is a str. Returns a bool. Raises ImportError if the module cannot be found. """ def get_code(self, fullname: str) -> types.CodeType | None: - """ - Method which returns the code object for the module. + """Method which returns the code object for the module. The fullname is a str. Returns a types.CodeType if possible, else returns None if a code object does not make sense @@ -130,32 +119,27 @@ class InspectLoader(Loader): @abstractmethod def get_source(self, fullname: str) -> str | None: - """ - Abstract method which should return the source code for the + """Abstract method which should return the source code for the module. The fullname is a str. Returns a str. Raises ImportError if the module cannot be found. """ def exec_module(self, module: types.ModuleType) -> None: - """ - Execute the module. - """ + """Execute the module.""" @staticmethod def source_to_code( data: ReadableBuffer | str | _ast.Module | _ast.Expression | _ast.Interactive, path: ReadableBuffer | StrPath = "" ) -> types.CodeType: - """ - Compile 'data' into a code object. + """Compile 'data' into a code object. The 'data' argument can be anything that compile() can handle. The'path' argument should be where the data was retrieved (when applicable). """ class ExecutionLoader(InspectLoader): - """ - Abstract base class for loaders that wish to support the execution of + """Abstract base class for loaders that wish to support the execution of modules as scripts. This ABC represents one of the optional protocols specified in PEP 302. @@ -163,16 +147,14 @@ class ExecutionLoader(InspectLoader): @abstractmethod def get_filename(self, fullname: str) -> str: - """ - Abstract method which should return the value that __file__ is to be + """Abstract method which should return the value that __file__ is to be set to. Raises ImportError if the module cannot be found. """ class SourceLoader(_bootstrap_external.SourceLoader, ResourceLoader, ExecutionLoader, metaclass=ABCMeta): # type: ignore[misc] # incompatible definitions of source_to_code in the base classes - """ - Abstract base class for loading source code (and optionally any + """Abstract base class for loading source code (and optionally any corresponding bytecode). To support loading from source code, the abstractmethods inherited from @@ -188,13 +170,10 @@ class SourceLoader(_bootstrap_external.SourceLoader, ResourceLoader, ExecutionLo @deprecated("Deprecated as of Python 3.3: Use importlib.resources.abc.SourceLoader.path_stats instead.") def path_mtime(self, path: str) -> float: - """ - Return the (int) modification time for the path (str). - """ + """Return the (int) modification time for the path (str).""" def set_data(self, path: str, data: bytes) -> None: - """ - Write the bytes to the path (if possible). + """Write the bytes to the path (if possible). Accepts a str path and data as bytes. @@ -204,13 +183,10 @@ class SourceLoader(_bootstrap_external.SourceLoader, ResourceLoader, ExecutionLo """ def get_source(self, fullname: str) -> str | None: - """ - Concrete implementation of InspectLoader.get_source. - """ + """Concrete implementation of InspectLoader.get_source.""" def path_stats(self, path: str) -> Mapping[str, Any]: - """ - Return a metadata dict for the source pointed to by the path (str). + """Return a metadata dict for the source pointed to by the path (str). Possible keys: - 'mtime' (mandatory) is the numeric timestamp of last source code modification; @@ -221,16 +197,13 @@ class SourceLoader(_bootstrap_external.SourceLoader, ResourceLoader, ExecutionLo if sys.version_info >= (3, 10): # Please keep in sync with _typeshed.importlib.MetaPathFinderProtocol class MetaPathFinder(metaclass=ABCMeta): - """ - Abstract base class for import finders on sys.meta_path. - """ + """Abstract base class for import finders on sys.meta_path.""" if sys.version_info < (3, 12): def find_module(self, fullname: str, path: Sequence[str] | None) -> Loader | None: ... def invalidate_caches(self) -> None: - """ - An optional method for clearing the finder's cache, if any. + """An optional method for clearing the finder's cache, if any. This method is used by importlib.invalidate_caches(). """ # Not defined on the actual class, but expected to exist. @@ -239,17 +212,14 @@ if sys.version_info >= (3, 10): ) -> ModuleSpec | None: ... class PathEntryFinder(metaclass=ABCMeta): - """ - Abstract base class for path entry finders used by PathFinder. - """ + """Abstract base class for path entry finders used by PathFinder.""" if sys.version_info < (3, 12): def find_module(self, fullname: str) -> Loader | None: ... def find_loader(self, fullname: str) -> tuple[Loader | None, Sequence[str]]: ... def invalidate_caches(self) -> None: - """ - An optional method for clearing the finder's cache, if any. + """An optional method for clearing the finder's cache, if any. This method is used by PathFinder.invalidate_caches(). """ # Not defined on the actual class, but expected to exist. @@ -258,13 +228,10 @@ if sys.version_info >= (3, 10): else: # Please keep in sync with _typeshed.importlib.MetaPathFinderProtocol class MetaPathFinder(Finder): - """ - Abstract base class for import finders on sys.meta_path. - """ + """Abstract base class for import finders on sys.meta_path.""" def find_module(self, fullname: str, path: Sequence[str] | None) -> Loader | None: - """ - Return a loader for the module. + """Return a loader for the module. If no module is found, return None. The fullname is a str and the path is a list of strings or None. @@ -275,8 +242,7 @@ else: """ def invalidate_caches(self) -> None: - """ - An optional method for clearing the finder's cache, if any. + """An optional method for clearing the finder's cache, if any. This method is used by importlib.invalidate_caches(). """ # Not defined on the actual class, but expected to exist. @@ -285,21 +251,17 @@ else: ) -> ModuleSpec | None: ... class PathEntryFinder(Finder): - """ - Abstract base class for path entry finders used by PathFinder. - """ + """Abstract base class for path entry finders used by PathFinder.""" def find_module(self, fullname: str) -> Loader | None: - """ - Try to find a loader for the specified module by delegating to + """Try to find a loader for the specified module by delegating to self.find_loader(). This method is deprecated in favor of finder.find_spec(). """ def find_loader(self, fullname: str) -> tuple[Loader | None, Sequence[str]]: - """ - Return (loader, namespace portion) for the path entry. + """Return (loader, namespace portion) for the path entry. The fullname is a str. The namespace portion is a sequence of path entries contributing to part of a namespace package. The @@ -315,54 +277,43 @@ else: """ def invalidate_caches(self) -> None: - """ - An optional method for clearing the finder's cache, if any. + """An optional method for clearing the finder's cache, if any. This method is used by PathFinder.invalidate_caches(). """ # Not defined on the actual class, but expected to exist. def find_spec(self, fullname: str, target: types.ModuleType | None = ...) -> ModuleSpec | None: ... class FileLoader(_bootstrap_external.FileLoader, ResourceLoader, ExecutionLoader, metaclass=ABCMeta): - """ - Abstract base class partially implementing the ResourceLoader and + """Abstract base class partially implementing the ResourceLoader and ExecutionLoader ABCs. """ name: str path: str def __init__(self, fullname: str, path: str) -> None: - """ - Cache the module name and the path to the file found by the + """Cache the module name and the path to the file found by the finder. """ def get_data(self, path: str) -> bytes: - """ - Return the data from path as raw bytes. - """ + """Return the data from path as raw bytes.""" def get_filename(self, name: str | None = None) -> str: - """ - Return the path to the source file as found by the finder. - """ + """Return the path to the source file as found by the finder.""" def load_module(self, name: str | None = None) -> types.ModuleType: - """ - Load a module from a file. + """Load a module from a file. This method is deprecated. Use exec_module() instead. """ if sys.version_info < (3, 11): class ResourceReader(metaclass=ABCMeta): - """ - Abstract base class for loaders to provide resource reading support. - """ + """Abstract base class for loaders to provide resource reading support.""" @abstractmethod def open_resource(self, resource: str) -> IO[bytes]: - """ - Return an opened, file-like object for binary reading. + """Return an opened, file-like object for binary reading. The 'resource' argument is expected to represent only a file name. If the resource cannot be found, FileNotFoundError is raised. @@ -370,8 +321,7 @@ if sys.version_info < (3, 11): @abstractmethod def resource_path(self, resource: str) -> str: - """ - Return the file system path to the specified resource. + """Return the file system path to the specified resource. The 'resource' argument is expected to represent only a file name. If the resource does not exist on the file system, raise @@ -380,70 +330,54 @@ if sys.version_info < (3, 11): if sys.version_info >= (3, 10): @abstractmethod def is_resource(self, path: str) -> bool: - """ - Return True if the named 'path' is a resource. + """Return True if the named 'path' is a resource. Files are resources, directories are not. """ else: @abstractmethod def is_resource(self, name: str) -> bool: - """ - Return True if the named 'path' is a resource. + """Return True if the named 'path' is a resource. Files are resources, directories are not. """ @abstractmethod def contents(self) -> Iterator[str]: - """ - Return an iterable of entries in `package`. - """ + """Return an iterable of entries in `package`.""" @runtime_checkable class Traversable(Protocol): - """ - An object with a subset of pathlib.Path methods suitable for + """An object with a subset of pathlib.Path methods suitable for traversing directories and opening files. """ @abstractmethod def is_dir(self) -> bool: - """ - Return True if self is a dir - """ + """Return True if self is a dir""" @abstractmethod def is_file(self) -> bool: - """ - Return True if self is a file - """ + """Return True if self is a file""" @abstractmethod def iterdir(self) -> Iterator[Traversable]: - """ - Yield Traversable objects in self - """ + """Yield Traversable objects in self""" if sys.version_info >= (3, 11): @abstractmethod def joinpath(self, *descendants: str) -> Traversable: - """ - Return Traversable child in self - """ + """Return Traversable child in self""" else: @abstractmethod def joinpath(self, child: str, /) -> Traversable: - """ - Return Traversable child in self - """ + """Return Traversable child in self""" # The documentation and runtime protocol allows *args, **kwargs arguments, # but this would mean that all implementers would have to support them, # which is not the case. @overload @abstractmethod def open(self, mode: Literal["r"] = "r", *, encoding: str | None = None, errors: str | None = None) -> IO[str]: - """ - mode may be 'r' or 'rb' to open as text or binary. Return a handle + """mode may be 'r' or 'rb' to open as text or binary. Return a handle suitable for reading (same as pathlib.Path.open). When opening as text, accepts encoding parameters such as those @@ -456,44 +390,31 @@ if sys.version_info < (3, 11): @property @abstractmethod def name(self) -> str: - """ - The base name of this object without any parent references. - """ + """The base name of this object without any parent references.""" if sys.version_info >= (3, 10): def __truediv__(self, child: str, /) -> Traversable: - """ - Return Traversable child in self - """ + """Return Traversable child in self""" else: @abstractmethod def __truediv__(self, child: str, /) -> Traversable: - """ - Return Traversable child in self - """ + """Return Traversable child in self""" @abstractmethod def read_bytes(self) -> bytes: - """ - Read contents of self as bytes - """ + """Read contents of self as bytes""" @abstractmethod def read_text(self, encoding: str | None = None) -> str: - """ - Read contents of self as text - """ + """Read contents of self as text""" class TraversableResources(ResourceReader): - """ - The required interface for providing traversable + """The required interface for providing traversable resources. """ @abstractmethod def files(self) -> Traversable: - """ - Return a Traversable object for the loaded package. - """ + """Return a Traversable object for the loaded package.""" def open_resource(self, resource: str) -> BufferedReader: ... def resource_path(self, resource: Any) -> str: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/machinery.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/machinery.pyi index 815294998b..815f861a7f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/machinery.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/machinery.pyi @@ -24,9 +24,7 @@ if sys.version_info >= (3, 14): from importlib._bootstrap_external import AppleFrameworkLoader as AppleFrameworkLoader def all_suffixes() -> list[str]: - """ - Returns a list of all recognized module suffixes for this process - """ + """Returns a list of all recognized module suffixes for this process""" if sys.version_info >= (3, 14): __all__ = [ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/metadata/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/metadata/__init__.pyi index 8b5c16afdd..6c8679cd60 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/metadata/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/metadata/__init__.pyi @@ -36,8 +36,7 @@ if sys.version_info >= (3, 10): if sys.version_info >= (3, 10): from importlib.metadata._meta import PackageMetadata as PackageMetadata, SimplePath def packages_distributions() -> Mapping[str, list[str]]: - """ - Return a mapping of top-level packages to their + """Return a mapping of top-level packages to their distributions. >>> import collections.abc @@ -51,9 +50,7 @@ else: _SimplePath: TypeAlias = Path class PackageNotFoundError(ModuleNotFoundError): - """ - The package was not found. - """ + """The package was not found.""" @property def name(self) -> str: ... # type: ignore[override] @@ -62,8 +59,7 @@ if sys.version_info >= (3, 13): _EntryPointBase = object elif sys.version_info >= (3, 11): class DeprecatedTuple: - """ - Provide subscript item access for backward compatibility. + """Provide subscript item access for backward compatibility. >>> recwarn = getfixture('recwarn') >>> ep = EntryPoint(name='name', value='value', group='group') @@ -85,8 +81,7 @@ else: group: str class EntryPoint(_EntryPointBase): - """ - An entry point as defined by Python packaging conventions. + """An entry point as defined by Python packaging conventions. See `the packaging docs on entry points `_ @@ -111,8 +106,7 @@ class EntryPoint(_EntryPointBase): def __init__(self, name: str, value: str, group: str) -> None: ... def load(self) -> Any: # Callable[[], Any] or an importable module - """ - Load the entry point from its definition. If only a module + """Load the entry point from its definition. If only a module is indicated by the value, return that module. Otherwise, return the named object. """ @@ -135,8 +129,7 @@ class EntryPoint(_EntryPointBase): attr: str = ..., extras: list[str] = ..., ) -> bool: # undocumented - """ - EntryPoint matches the given parameters. + """EntryPoint matches the given parameters. >>> ep = EntryPoint(group='foo', name='bar', value='bing:bong [extra1, extra2]') >>> ep.matches(group='foo') @@ -164,14 +157,10 @@ class EntryPoint(_EntryPointBase): if sys.version_info >= (3, 12): class EntryPoints(tuple[EntryPoint, ...]): - """ - An immutable collection of selectable EntryPoint objects. - """ + """An immutable collection of selectable EntryPoint objects.""" def __getitem__(self, name: str) -> EntryPoint: # type: ignore[override] - """ - Get the EntryPoint in self matching name. - """ + """Get the EntryPoint in self matching name.""" def select( self, @@ -183,27 +172,21 @@ if sys.version_info >= (3, 12): attr: str = ..., extras: list[str] = ..., ) -> EntryPoints: - """ - Select entry points from self that match the + """Select entry points from self that match the given parameters (typically group and/or name). """ @property def names(self) -> set[str]: - """ - Return the set of all names of all entry points. - """ + """Return the set of all names of all entry points.""" @property def groups(self) -> set[str]: - """ - Return the set of all groups of all entry points. - """ + """Return the set of all groups of all entry points.""" elif sys.version_info >= (3, 10): class DeprecatedList(list[_T]): - """ - Allow an otherwise immutable object to implement mutability + """Allow an otherwise immutable object to implement mutability for compatibility. >>> recwarn = getfixture('recwarn') @@ -234,15 +217,11 @@ elif sys.version_info >= (3, 10): """ class EntryPoints(DeprecatedList[EntryPoint]): # use as list is deprecated since 3.10 - """ - An immutable collection of selectable EntryPoint objects. - """ + """An immutable collection of selectable EntryPoint objects.""" # int argument is deprecated since 3.10 def __getitem__(self, name: int | str) -> EntryPoint: # type: ignore[override] - """ - Get the EntryPoint in self matching name. - """ + """Get the EntryPoint in self matching name.""" def select( self, @@ -254,21 +233,17 @@ elif sys.version_info >= (3, 10): attr: str = ..., extras: list[str] = ..., ) -> EntryPoints: - """ - Select entry points from self that match the + """Select entry points from self that match the given parameters (typically group and/or name). """ @property def names(self) -> set[str]: - """ - Return the set of all names of all entry points. - """ + """Return the set of all names of all entry points.""" @property def groups(self) -> set[str]: - """ - Return the set of all groups of all entry points. + """Return the set of all groups of all entry points. For coverage while SelectableGroups is present. >>> EntryPoints().groups @@ -277,8 +252,7 @@ elif sys.version_info >= (3, 10): if sys.version_info >= (3, 10) and sys.version_info < (3, 12): class Deprecated(Generic[_KT, _VT]): - """ - Compatibility add-in for mapping to indicate that + """Compatibility add-in for mapping to indicate that mapping behavior is deprecated. >>> recwarn = getfixture('recwarn') @@ -312,8 +286,7 @@ if sys.version_info >= (3, 10) and sys.version_info < (3, 12): def values(self) -> dict_values[_KT, _VT]: ... class SelectableGroups(Deprecated[str, EntryPoints], dict[str, EntryPoints]): # use as dict is deprecated since 3.10 - """ - A backward- and forward-compatible result from + """A backward- and forward-compatible result from entry_points that fully implements the dict interface. """ @@ -323,8 +296,7 @@ if sys.version_info >= (3, 10) and sys.version_info < (3, 12): def groups(self) -> set[str]: ... @property def names(self) -> set[str]: - """ - for coverage: + """for coverage: >>> SelectableGroups().names set() """ @@ -344,16 +316,12 @@ if sys.version_info >= (3, 10) and sys.version_info < (3, 12): ) -> EntryPoints: ... class PackagePath(pathlib.PurePosixPath): - """ - A reference to a path in a package - """ + """A reference to a path in a package""" def read_text(self, encoding: str = "utf-8") -> str: ... def read_binary(self) -> bytes: ... def locate(self) -> PathLike[str]: - """ - Return a path-like object for this path - """ + """Return a path-like object for this path""" # The following attributes are not defined on PackagePath, but are dynamically added by Distribution.files: hash: FileHash | None size: int | None @@ -371,8 +339,7 @@ else: _distribution_parent = object class Distribution(_distribution_parent): - """ - An abstract Python distribution package. + """An abstract Python distribution package. Custom providers may derive from this class and define the abstract methods to provide a concrete implementation @@ -383,8 +350,7 @@ class Distribution(_distribution_parent): @abc.abstractmethod def read_text(self, filename: str) -> str | None: - """ - Attempt to load metadata file given by the name. + """Attempt to load metadata file given by the name. Python distribution metadata is organized by blobs of text typically represented as "files" in the metadata directory @@ -407,15 +373,13 @@ class Distribution(_distribution_parent): @abc.abstractmethod def locate_file(self, path: StrPath) -> _SimplePath: - """ - Given a path to a file in this distribution, return a SimplePath + """Given a path to a file in this distribution, return a SimplePath to it. """ @classmethod def from_name(cls, name: str) -> Distribution: - """ - Return the Distribution for the given package name. + """Return the Distribution for the given package name. :param name: The name of the distribution package to search for. :return: The Distribution instance (or subclass thereof) for the named @@ -428,8 +392,7 @@ class Distribution(_distribution_parent): @overload @classmethod def discover(cls, *, context: DistributionFinder.Context) -> Iterable[Distribution]: - """ - Return an iterable of Distribution objects for all packages. + """Return an iterable of Distribution objects for all packages. Pass a ``context`` or pass keyword arguments for constructing a context. @@ -446,8 +409,7 @@ class Distribution(_distribution_parent): ) -> Iterable[Distribution]: ... @staticmethod def at(path: StrPath) -> PathDistribution: - """ - Return a Distribution for the indicated metadata path. + """Return a Distribution for the indicated metadata path. :param path: a string or path-like object :return: a concrete Distribution instance for the path @@ -455,8 +417,7 @@ class Distribution(_distribution_parent): if sys.version_info >= (3, 10): @property def metadata(self) -> PackageMetadata: - """ - Return the parsed metadata for this Distribution. + """Return the parsed metadata for this Distribution. The returned object will have keys that name the various bits of metadata per the @@ -468,8 +429,7 @@ class Distribution(_distribution_parent): @property def entry_points(self) -> EntryPoints: - """ - Return EntryPoints for this distribution. + """Return EntryPoints for this distribution. Custom providers may provide the ``entry_points.txt`` file or override this property. @@ -477,8 +437,7 @@ class Distribution(_distribution_parent): else: @property def metadata(self) -> Message: - """ - Return the parsed metadata for this Distribution. + """Return the parsed metadata for this Distribution. The returned object will have keys that name the various bits of metadata per the @@ -490,8 +449,7 @@ class Distribution(_distribution_parent): @property def entry_points(self) -> list[EntryPoint]: - """ - Return EntryPoints for this distribution. + """Return EntryPoints for this distribution. Custom providers may provide the ``entry_points.txt`` file or override this property. @@ -499,14 +457,11 @@ class Distribution(_distribution_parent): @property def version(self) -> str: - """ - Return the 'Version' metadata for the distribution package. - """ + """Return the 'Version' metadata for the distribution package.""" @property def files(self) -> list[PackagePath] | None: - """ - Files in this distribution. + """Files in this distribution. :return: List of PackagePath for this distribution or None @@ -522,30 +477,24 @@ class Distribution(_distribution_parent): @property def requires(self) -> list[str] | None: - """ - Generated requirements specified for this Distribution - """ + """Generated requirements specified for this Distribution""" if sys.version_info >= (3, 10): @property def name(self) -> str: - """ - Return the 'Name' metadata for the distribution package. - """ + """Return the 'Name' metadata for the distribution package.""" if sys.version_info >= (3, 13): @property def origin(self) -> types.SimpleNamespace: ... class DistributionFinder(MetaPathFinder): - """ - A MetaPathFinder capable of discovering installed distributions. + """A MetaPathFinder capable of discovering installed distributions. Custom providers should implement this interface in order to supply metadata. """ class Context: - """ - Keyword arguments presented by the caller to + """Keyword arguments presented by the caller to ``distributions()`` or ``Distribution.discover()`` to narrow the scope of a search for distributions in all DistributionFinders. @@ -570,8 +519,7 @@ class DistributionFinder(MetaPathFinder): def __init__(self, *, name: str | None = ..., path: list[str] = ..., **kwargs: Any) -> None: ... @property def path(self) -> list[str]: - """ - The sequence of directory path that a distribution finder + """The sequence of directory path that a distribution finder should search. Typically refers to Python installed package paths such as @@ -580,8 +528,7 @@ class DistributionFinder(MetaPathFinder): @abc.abstractmethod def find_distributions(self, context: DistributionFinder.Context = ...) -> Iterable[Distribution]: - """ - Find distributions. + """Find distributions. Return an iterable of all Distribution instances capable of loading the metadata for packages matching the ``context``, @@ -591,8 +538,7 @@ class DistributionFinder(MetaPathFinder): class MetadataPathFinder(DistributionFinder): @classmethod def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: - """ - Find distributions. + """Find distributions. Return an iterable of all Distribution instances capable of loading the metadata for packages matching ``context.name`` @@ -602,30 +548,26 @@ class MetadataPathFinder(DistributionFinder): if sys.version_info >= (3, 11): @classmethod def invalidate_caches(cls) -> None: - """ - An optional method for clearing the finder's cache, if any. + """An optional method for clearing the finder's cache, if any. This method is used by importlib.invalidate_caches(). """ elif sys.version_info >= (3, 10): # Yes, this is an instance method that has a parameter named "cls" def invalidate_caches(cls) -> None: - """ - An optional method for clearing the finder's cache, if any. + """An optional method for clearing the finder's cache, if any. This method is used by importlib.invalidate_caches(). """ class PathDistribution(Distribution): _path: _SimplePath def __init__(self, path: _SimplePath) -> None: - """ - Construct a distribution. + """Construct a distribution. :param path: SimplePath indicating the metadata directory. """ def read_text(self, filename: StrPath) -> str | None: - """ - Attempt to load metadata file given by the name. + """Attempt to load metadata file given by the name. Python distribution metadata is organized by blobs of text typically represented as "files" in the metadata directory @@ -649,8 +591,7 @@ class PathDistribution(Distribution): def locate_file(self, path: StrPath) -> _SimplePath: ... def distribution(distribution_name: str) -> Distribution: - """ - Get the ``Distribution`` instance for the named package. + """Get the ``Distribution`` instance for the named package. :param distribution_name: The name of the distribution package as a string. :return: A ``Distribution`` instance (or subclass thereof). @@ -658,8 +599,7 @@ def distribution(distribution_name: str) -> Distribution: @overload def distributions(*, context: DistributionFinder.Context) -> Iterable[Distribution]: - """ - Get all ``Distribution`` instances in the current environment. + """Get all ``Distribution`` instances in the current environment. :return: An iterable of ``Distribution`` instances. """ @@ -671,8 +611,7 @@ def distributions( if sys.version_info >= (3, 10): def metadata(distribution_name: str) -> PackageMetadata: - """ - Get the metadata for the named package. + """Get the metadata for the named package. :param distribution_name: The name of the distribution package to query. :return: A PackageMetadata containing the parsed metadata. @@ -680,8 +619,7 @@ if sys.version_info >= (3, 10): else: def metadata(distribution_name: str) -> Message: - """ - Get the metadata for the named package. + """Get the metadata for the named package. :param distribution_name: The name of the distribution package to query. :return: An email.Message containing the parsed metadata. @@ -691,8 +629,7 @@ if sys.version_info >= (3, 12): def entry_points( *, name: str = ..., value: str = ..., group: str = ..., module: str = ..., attr: str = ..., extras: list[str] = ... ) -> EntryPoints: - """ - Return EntryPoint objects for all installed packages. + """Return EntryPoint objects for all installed packages. Pass selection parameters (group or name) to filter the result to entry points matching those properties (see @@ -704,8 +641,7 @@ if sys.version_info >= (3, 12): elif sys.version_info >= (3, 10): @overload def entry_points() -> SelectableGroups: - """ - Return EntryPoint objects for all installed packages. + """Return EntryPoint objects for all installed packages. Pass selection parameters (group or name) to filter the result to entry points matching those properties (see @@ -729,15 +665,13 @@ elif sys.version_info >= (3, 10): else: def entry_points() -> dict[str, list[EntryPoint]]: - """ - Return EntryPoint objects for all installed packages. + """Return EntryPoint objects for all installed packages. :return: EntryPoint objects for all installed packages. """ def version(distribution_name: str) -> str: - """ - Get the version string for the named package. + """Get the version string for the named package. :param distribution_name: The name of the distribution package to query. :return: The version string for the package as defined in the package's @@ -745,16 +679,14 @@ def version(distribution_name: str) -> str: """ def files(distribution_name: str) -> list[PackagePath] | None: - """ - Return a list of files for the named package. + """Return a list of files for the named package. :param distribution_name: The name of the distribution package to query. :return: List of files composing the distribution. """ def requires(distribution_name: str) -> list[str] | None: - """ - Return a list of requirements for the named package. + """Return a list of requirements for the named package. :return: An iterable of requirements, suitable for packaging.requirement.Requirement. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/metadata/_meta.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/metadata/_meta.pyi index c8f38f66ac..a9fab3cf46 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/metadata/_meta.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/metadata/_meta.pyi @@ -15,33 +15,25 @@ class PackageMetadata(Protocol): def __iter__(self) -> Iterator[str]: ... @property def json(self) -> dict[str, str | list[str]]: - """ - A JSON-compatible form of the metadata. - """ + """A JSON-compatible form of the metadata.""" @overload def get_all(self, name: str, failobj: None = None) -> list[Any] | None: - """ - Helper for @overload to raise when called. - """ + """Helper for @overload to raise when called.""" @overload def get_all(self, name: str, failobj: _T) -> list[Any] | _T: ... if sys.version_info >= (3, 12): @overload def get(self, name: str, failobj: None = None) -> str | None: - """ - Helper for @overload to raise when called. - """ + """Helper for @overload to raise when called.""" @overload def get(self, name: str, failobj: _T) -> _T | str: ... if sys.version_info >= (3, 13): class SimplePath(Protocol): - """ - A minimal subset of pathlib.Path required by Distribution. - """ + """A minimal subset of pathlib.Path required by Distribution.""" def joinpath(self, other: StrPath, /) -> SimplePath: ... def __truediv__(self, other: StrPath, /) -> SimplePath: ... @@ -54,9 +46,7 @@ if sys.version_info >= (3, 13): elif sys.version_info >= (3, 12): class SimplePath(Protocol[_T_co]): - """ - A minimal subset of pathlib.Path required by PathDistribution. - """ + """A minimal subset of pathlib.Path required by PathDistribution.""" # At runtime this is defined as taking `str | _T`, but that causes trouble. # See #11436. @@ -69,9 +59,7 @@ elif sys.version_info >= (3, 12): else: class SimplePath(Protocol): - """ - A minimal subset of pathlib.Path required by PathDistribution. - """ + """A minimal subset of pathlib.Path required by PathDistribution.""" # Actually takes only self at runtime, but that's clearly wrong def joinpath(self, other: Any, /) -> SimplePath: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/readers.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/readers.pyi index 029111a3c7..ed6936150a 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/readers.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/readers.pyi @@ -1,4 +1,5 @@ """ + Compatibility shim for .resources.readers as found on Python 3.10. Consumers that can rely on Python 3.11 should use the other @@ -40,8 +41,7 @@ if sys.version_info >= (3, 10): path: pathlib.Path def __init__(self, loader: FileLoader) -> None: ... def resource_path(self, resource: StrPath) -> str: - """ - Return the file system path to prevent + """Return the file system path to prevent `resources.path()` from creating a temporary copy. """ @@ -54,16 +54,14 @@ if sys.version_info >= (3, 10): def __init__(self, loader: zipimporter, module: str) -> None: ... def open_resource(self, resource: str) -> BufferedReader: ... def is_resource(self, path: StrPath) -> bool: - """ - Workaround for `zipfile.Path.is_file` returning true + """Workaround for `zipfile.Path.is_file` returning true for non-existent paths. """ def files(self) -> zipfile.Path: ... class MultiplexedPath(abc.Traversable): - """ - Given a series of Traversable objects, implement a merged + """Given a series of Traversable objects, implement a merged version of the interface across all objects. Useful for namespace packages which may be multihomed at a single name. @@ -94,8 +92,7 @@ if sys.version_info >= (3, 10): path: MultiplexedPath def __init__(self, namespace_path: Iterable[str]) -> None: ... def resource_path(self, resource: str) -> str: - """ - Return the file system path to prevent + """Return the file system path to prevent `resources.path()` from creating a temporary copy. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/__init__.pyi index 237419bb33..ad5ec45608 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/__init__.pyi @@ -1,4 +1,5 @@ """ + Read resources contained within a package. This codebase is shared between importlib.resources in the stdlib @@ -68,31 +69,23 @@ if sys.version_info >= (3, 13): else: def open_binary(package: Package, resource: Resource) -> BinaryIO: - """ - Return a file-like object opened for binary reading of the resource. - """ + """Return a file-like object opened for binary reading of the resource.""" def open_text(package: Package, resource: Resource, encoding: str = "utf-8", errors: str = "strict") -> TextIO: - """ - Return a file-like object opened for text reading of the resource. - """ + """Return a file-like object opened for text reading of the resource.""" def read_binary(package: Package, resource: Resource) -> bytes: - """ - Return the binary contents of the resource. - """ + """Return the binary contents of the resource.""" def read_text(package: Package, resource: Resource, encoding: str = "utf-8", errors: str = "strict") -> str: - """ - Return the decoded string of the resource. + """Return the decoded string of the resource. The decoding-related arguments have the same semantics as those of bytes.decode(). """ def path(package: Package, resource: Resource) -> AbstractContextManager[Path, Literal[False]]: - """ - A context manager providing a file path object to the resource. + """A context manager providing a file path object to the resource. If the resource does not already exist on its own on the file system, a temporary file will be created. If the file was created, the file @@ -102,15 +95,13 @@ else: """ def is_resource(package: Package, name: str) -> bool: - """ - True if `name` is a resource inside `package`. + """True if `name` is a resource inside `package`. Directories are *not* resources. """ def contents(package: Package) -> Iterator[str]: - """ - Return an iterable of entries in `package`. + """Return an iterable of entries in `package`. Note that not all entries are resources. Specifically, directories are not considered resources. Use `is_resource()` on each entry returned here @@ -121,8 +112,7 @@ if sys.version_info >= (3, 11): from importlib.resources._common import as_file as as_file else: def as_file(path: Traversable) -> AbstractContextManager[Path, Literal[False]]: - """ - Given a Traversable object, return that object as a + """Given a Traversable object, return that object as a path on the local file system in a context manager. """ @@ -130,9 +120,7 @@ if sys.version_info >= (3, 11): from importlib.resources._common import files as files else: def files(package: Package) -> Traversable: - """ - Get a Traversable resource from a package - """ + """Get a Traversable resource from a package""" if sys.version_info >= (3, 11): from importlib.resources.abc import ResourceReader as ResourceReader diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/_common.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/_common.pyi index c09a97a7b5..7b70c589d4 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/_common.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/_common.pyi @@ -18,8 +18,7 @@ if sys.version_info >= (3, 11): def package_to_anchor( func: Callable[[Anchor | None], Traversable], ) -> Callable[[Anchor | None, Anchor | None], Traversable]: - """ - Replace 'package' parameter as 'anchor' and warn about the change. + """Replace 'package' parameter as 'anchor' and warn about the change. Other errors should fall through. @@ -32,9 +31,7 @@ if sys.version_info >= (3, 11): @overload def files(anchor: Anchor | None = None) -> Traversable: - """ - Get a Traversable resource for an anchor. - """ + """Get a Traversable resource for an anchor.""" @overload @deprecated("First parameter to files is renamed to 'anchor'") @@ -42,14 +39,10 @@ if sys.version_info >= (3, 11): else: def files(package: Package) -> Traversable: - """ - Get a Traversable resource from a package - """ + """Get a Traversable resource from a package""" def get_resource_reader(package: types.ModuleType) -> ResourceReader | None: - """ - Return the package's loader if it's a ResourceReader. - """ + """Return the package's loader if it's a ResourceReader.""" if sys.version_info >= (3, 12): def resolve(cand: Anchor | None) -> types.ModuleType: ... @@ -58,19 +51,15 @@ if sys.version_info >= (3, 11): if sys.version_info < (3, 12): def get_package(package: Package) -> types.ModuleType: - """ - Take a package name or module object and return the module. + """Take a package name or module object and return the module. Raise an exception if the resolved module is not a package. """ def from_package(package: types.ModuleType) -> Traversable: - """ - Return a Traversable object for the given package. - """ + """Return a Traversable object for the given package.""" def as_file(path: Traversable) -> AbstractContextManager[Path, Literal[False]]: - """ - Given a Traversable object, return that object as a + """Given a Traversable object, return that object as a path on the local file system in a context manager. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/_functional.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/_functional.pyi index a9e5a44382..32a2297629 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/_functional.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/_functional.pyi @@ -16,50 +16,38 @@ if sys.version_info >= (3, 13): from typing_extensions import Unpack def open_binary(anchor: Anchor, *path_names: StrPath) -> BinaryIO: - """ - Open for binary reading the *resource* within *package*. - """ + """Open for binary reading the *resource* within *package*.""" @overload def open_text( anchor: Anchor, *path_names: Unpack[tuple[StrPath]], encoding: str | None = "utf-8", errors: str | None = "strict" ) -> TextIOWrapper: - """ - Open for text reading the *resource* within *package*. - """ + """Open for text reading the *resource* within *package*.""" @overload def open_text(anchor: Anchor, *path_names: StrPath, encoding: str | None, errors: str | None = "strict") -> TextIOWrapper: ... def read_binary(anchor: Anchor, *path_names: StrPath) -> bytes: - """ - Read and return contents of *resource* within *package* as bytes. - """ + """Read and return contents of *resource* within *package* as bytes.""" @overload def read_text( anchor: Anchor, *path_names: Unpack[tuple[StrPath]], encoding: str | None = "utf-8", errors: str | None = "strict" ) -> str: - """ - Read and return contents of *resource* within *package* as str. - """ + """Read and return contents of *resource* within *package* as str.""" @overload def read_text(anchor: Anchor, *path_names: StrPath, encoding: str | None, errors: str | None = "strict") -> str: ... def path(anchor: Anchor, *path_names: StrPath) -> AbstractContextManager[Path, Literal[False]]: - """ - Return the path to the *resource* as an actual file system path. - """ + """Return the path to the *resource* as an actual file system path.""" def is_resource(anchor: Anchor, *path_names: StrPath) -> bool: - """ - Return ``True`` if there is a resource named *name* in the package, + """Return ``True`` if there is a resource named *name* in the package, Otherwise returns ``False``. """ def contents(anchor: Anchor, *path_names: StrPath) -> Iterator[str]: - """ - Return an iterable over the named resources within the package. + """Return an iterable over the named resources within the package. The iterable returns :class:`str` resources (e.g. files). The iterable does not recurse into subdirectories. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/abc.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/abc.pyi index f64e9f8ea0..dfe9156668 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/abc.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/abc.pyi @@ -6,14 +6,11 @@ from typing import IO, Any, Literal, Protocol, overload, runtime_checkable if sys.version_info >= (3, 11): class ResourceReader(metaclass=ABCMeta): - """ - Abstract base class for loaders to provide resource reading support. - """ + """Abstract base class for loaders to provide resource reading support.""" @abstractmethod def open_resource(self, resource: str) -> IO[bytes]: - """ - Return an opened, file-like object for binary reading. + """Return an opened, file-like object for binary reading. The 'resource' argument is expected to represent only a file name. If the resource cannot be found, FileNotFoundError is raised. @@ -21,8 +18,7 @@ if sys.version_info >= (3, 11): @abstractmethod def resource_path(self, resource: str) -> str: - """ - Return the file system path to the specified resource. + """Return the file system path to the specified resource. The 'resource' argument is expected to represent only a file name. If the resource does not exist on the file system, raise @@ -31,30 +27,25 @@ if sys.version_info >= (3, 11): if sys.version_info >= (3, 10): @abstractmethod def is_resource(self, path: str) -> bool: - """ - Return True if the named 'path' is a resource. + """Return True if the named 'path' is a resource. Files are resources, directories are not. """ else: @abstractmethod def is_resource(self, name: str) -> bool: - """ - Return True if the named 'path' is a resource. + """Return True if the named 'path' is a resource. Files are resources, directories are not. """ @abstractmethod def contents(self) -> Iterator[str]: - """ - Return an iterable of entries in `package`. - """ + """Return an iterable of entries in `package`.""" @runtime_checkable class Traversable(Protocol): - """ - An object with a subset of pathlib.Path methods suitable for + """An object with a subset of pathlib.Path methods suitable for traversing directories and opening files. Any exceptions that occur when accessing the backing resource @@ -63,26 +54,19 @@ if sys.version_info >= (3, 11): @abstractmethod def is_dir(self) -> bool: - """ - Return True if self is a directory - """ + """Return True if self is a directory""" @abstractmethod def is_file(self) -> bool: - """ - Return True if self is a file - """ + """Return True if self is a file""" @abstractmethod def iterdir(self) -> Iterator[Traversable]: - """ - Yield Traversable objects in self - """ + """Yield Traversable objects in self""" if sys.version_info >= (3, 11): @abstractmethod def joinpath(self, *descendants: str) -> Traversable: - """ - Return Traversable resolved with any descendants applied. + """Return Traversable resolved with any descendants applied. Each descendant should be a path segment relative to self and each may contain multiple levels separated by @@ -91,8 +75,7 @@ if sys.version_info >= (3, 11): else: @abstractmethod def joinpath(self, child: str, /) -> Traversable: - """ - Return Traversable resolved with any descendants applied. + """Return Traversable resolved with any descendants applied. Each descendant should be a path segment relative to self and each may contain multiple levels separated by @@ -104,8 +87,7 @@ if sys.version_info >= (3, 11): @overload @abstractmethod def open(self, mode: Literal["r"] = "r", *, encoding: str | None = None, errors: str | None = None) -> IO[str]: - """ - mode may be 'r' or 'rb' to open as text or binary. Return a handle + """mode may be 'r' or 'rb' to open as text or binary. Return a handle suitable for reading (same as pathlib.Path.open). When opening as text, accepts encoding parameters such as those @@ -118,44 +100,31 @@ if sys.version_info >= (3, 11): @property @abstractmethod def name(self) -> str: - """ - The base name of this object without any parent references. - """ + """The base name of this object without any parent references.""" if sys.version_info >= (3, 10): def __truediv__(self, child: str, /) -> Traversable: - """ - Return Traversable child in self - """ + """Return Traversable child in self""" else: @abstractmethod def __truediv__(self, child: str, /) -> Traversable: - """ - Return Traversable child in self - """ + """Return Traversable child in self""" @abstractmethod def read_bytes(self) -> bytes: - """ - Read contents of self as bytes - """ + """Read contents of self as bytes""" @abstractmethod def read_text(self, encoding: str | None = None) -> str: - """ - Read contents of self as text - """ + """Read contents of self as text""" class TraversableResources(ResourceReader): - """ - The required interface for providing traversable + """The required interface for providing traversable resources. """ @abstractmethod def files(self) -> Traversable: - """ - Return a Traversable object for the loaded package. - """ + """Return a Traversable object for the loaded package.""" def open_resource(self, resource: str) -> BufferedReader: ... def resource_path(self, resource: Any) -> str: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/simple.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/simple.pyi index eebdf6f98d..15ab5872db 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/simple.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/resources/simple.pyi @@ -1,4 +1,5 @@ """ + Interface adapters for low-level readers. """ @@ -13,44 +14,34 @@ if sys.version_info >= (3, 11): from .abc import Traversable, TraversableResources class SimpleReader(abc.ABC): - """ - The minimum, low-level interface required from a resource + """The minimum, low-level interface required from a resource provider. """ @property @abc.abstractmethod def package(self) -> str: - """ - The name of the package for which this reader loads resources. - """ + """The name of the package for which this reader loads resources.""" @abc.abstractmethod def children(self) -> list[SimpleReader]: - """ - Obtain an iterable of SimpleReader for available + """Obtain an iterable of SimpleReader for available child containers (e.g. directories). """ @abc.abstractmethod def resources(self) -> list[str]: - """ - Obtain available named resources for this virtual package. - """ + """Obtain available named resources for this virtual package.""" @abc.abstractmethod def open_binary(self, resource: str) -> BinaryIO: - """ - Obtain a File-like for a named resource. - """ + """Obtain a File-like for a named resource.""" @property def name(self) -> str: ... class ResourceHandle(Traversable, metaclass=abc.ABCMeta): - """ - Handle to a named resource in a ResourceReader. - """ + """Handle to a named resource in a ResourceReader.""" parent: ResourceContainer def __init__(self, parent: ResourceContainer, name: str) -> None: ... @@ -73,9 +64,7 @@ if sys.version_info >= (3, 11): def joinpath(self, name: Never) -> NoReturn: ... # type: ignore[override] class ResourceContainer(Traversable, metaclass=abc.ABCMeta): - """ - Traversable container for a package's resources via its reader. - """ + """Traversable container for a package's resources via its reader.""" reader: SimpleReader def __init__(self, reader: SimpleReader) -> None: ... @@ -85,8 +74,7 @@ if sys.version_info >= (3, 11): def open(self, *args: Never, **kwargs: Never) -> NoReturn: ... # type: ignore[override] if sys.version_info < (3, 12): def joinpath(self, *descendants: str) -> Traversable: - """ - Return Traversable resolved with any descendants applied. + """Return Traversable resolved with any descendants applied. Each descendant should be a path segment relative to self and each may contain multiple levels separated by @@ -94,8 +82,7 @@ if sys.version_info >= (3, 11): """ class TraversableReader(TraversableResources, SimpleReader, metaclass=abc.ABCMeta): - """ - A TraversableResources based on SimpleReader. Resource providers + """A TraversableResources based on SimpleReader. Resource providers may derive from this class to provide the TraversableResources interface by supplying the SimpleReader interface. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/simple.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/simple.pyi index 4c6f230844..c8a78d3dbe 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/simple.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/simple.pyi @@ -1,4 +1,5 @@ """ + Compatibility shim for .resources.simple as found on Python 3.10. Consumers that can rely on Python 3.11 should use the other diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/util.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/util.pyi index 9ef641da87..b92f591585 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/importlib/util.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/importlib/util.pyi @@ -22,8 +22,7 @@ _P = ParamSpec("_P") if sys.version_info < (3, 12): def module_for_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: - """ - Decorator to handle selecting the proper module for loaders. + """Decorator to handle selecting the proper module for loaders. The decorated function is passed the module to use instead of the module name. The module passed in to the function is either from sys.modules if @@ -41,27 +40,22 @@ if sys.version_info < (3, 12): """ def set_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: - """ - Set __loader__ on the returned module. + """Set __loader__ on the returned module. This function is deprecated. """ def set_package(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: - """ - Set __package__ on the returned module. + """Set __package__ on the returned module. This function is deprecated. """ def resolve_name(name: str, package: str | None) -> str: - """ - Resolve a relative module name to an absolute one. - """ + """Resolve a relative module name to an absolute one.""" def find_spec(name: str, package: str | None = None) -> importlib.machinery.ModuleSpec | None: - """ - Return the spec for the specified module. + """Return the spec for the specified module. First, sys.modules is checked to see if the module was already imported. If so, then sys.modules[name].__spec__ is returned. If that happens to be @@ -78,26 +72,18 @@ def find_spec(name: str, package: str | None = None) -> importlib.machinery.Modu """ class LazyLoader(Loader): - """ - A loader that creates a module which defers loading until attribute access. - """ + """A loader that creates a module which defers loading until attribute access.""" def __init__(self, loader: Loader) -> None: ... @classmethod def factory(cls, loader: Loader) -> Callable[..., LazyLoader]: - """ - Construct a callable which returns the eager loader made lazy. - """ + """Construct a callable which returns the eager loader made lazy.""" def exec_module(self, module: types.ModuleType) -> None: - """ - Make the module load lazily. - """ + """Make the module load lazily.""" def source_hash(source_bytes: ReadableBuffer) -> bytes: - """ - Return the hash of *source_bytes* as used in hash-based pyc files. - """ + """Return the hash of *source_bytes* as used in hash-based pyc files.""" if sys.version_info >= (3, 14): __all__ = [ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/inspect.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/inspect.pyi index 6fc4d5960f..9e21a229f2 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/inspect.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/inspect.pyi @@ -186,9 +186,7 @@ _V_contra = TypeVar("_V_contra", contravariant=True) class EndOfBlock(Exception): ... class BlockFinder: - """ - Provide a tokeneater() method to detect the end of a code block. - """ + """Provide a tokeneater() method to detect the end of a code block.""" indent: int islambda: bool @@ -223,8 +221,7 @@ _GetMembersReturn: TypeAlias = list[tuple[str, _T]] @overload def getmembers(object: object, predicate: _GetMembersPredicateTypeGuard[_T]) -> _GetMembersReturn[_T]: - """ - Return all members of an object as (name, value) pairs sorted by name. + """Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate. """ @@ -236,8 +233,7 @@ def getmembers(object: object, predicate: _GetMembersPredicate | None = None) -> if sys.version_info >= (3, 11): @overload def getmembers_static(object: object, predicate: _GetMembersPredicateTypeGuard[_T]) -> _GetMembersReturn[_T]: - """ - Return all members of an object as (name, value) pairs sorted by name + """Return all members of an object as (name, value) pairs sorted by name without triggering dynamic lookup via the descriptor protocol, __getattr__ or __getattribute__. Optionally, only return members that satisfy a given predicate. @@ -255,35 +251,24 @@ if sys.version_info >= (3, 11): def getmembers_static(object: object, predicate: _GetMembersPredicate | None = None) -> _GetMembersReturn[Any]: ... def getmodulename(path: StrPath) -> str | None: - """ - Return the module name for a given file, or None. - """ + """Return the module name for a given file, or None.""" def ismodule(object: object) -> TypeIs[ModuleType]: - """ - Return true if the object is a module. - """ + """Return true if the object is a module.""" def isclass(object: object) -> TypeIs[type[Any]]: - """ - Return true if the object is a class. - """ + """Return true if the object is a class.""" def ismethod(object: object) -> TypeIs[MethodType]: - """ - Return true if the object is an instance method. - """ + """Return true if the object is an instance method.""" if sys.version_info >= (3, 14): # Not TypeIs because it does not return True for all modules def ispackage(object: object) -> TypeGuard[ModuleType]: - """ - Return true if the object is a package. - """ + """Return true if the object is a package.""" def isfunction(object: object) -> TypeIs[FunctionType]: - """ - Return true if the object is a user-defined function. + """Return true if the object is a user-defined function. Function objects provide these attributes: __doc__ documentation string @@ -302,14 +287,11 @@ def isfunction(object: object) -> TypeIs[FunctionType]: if sys.version_info >= (3, 12): def markcoroutinefunction(func: _F) -> _F: - """ - Decorator to ensure callable is recognised as a coroutine function. - """ + """Decorator to ensure callable is recognised as a coroutine function.""" @overload def isgeneratorfunction(obj: Callable[..., Generator[Any, Any, Any]]) -> bool: - """ - Return true if the object is a user-defined generator function. + """Return true if the object is a user-defined generator function. Generator function objects provide the same attributes as functions. See help(isfunction) for a list of attributes. @@ -321,8 +303,7 @@ def isgeneratorfunction(obj: Callable[_P, Any]) -> TypeGuard[Callable[_P, Genera def isgeneratorfunction(obj: object) -> TypeGuard[Callable[..., GeneratorType[Any, Any, Any]]]: ... @overload def iscoroutinefunction(obj: Callable[..., Coroutine[Any, Any, Any]]) -> bool: - """ - Return true if the object is a coroutine function. + """Return true if the object is a coroutine function. Coroutine functions are normally defined with "async def" syntax, but may be marked via markcoroutinefunction. @@ -335,8 +316,7 @@ def iscoroutinefunction(obj: Callable[_P, object]) -> TypeGuard[Callable[_P, Cor @overload def iscoroutinefunction(obj: object) -> TypeGuard[Callable[..., CoroutineType[Any, Any, Any]]]: ... def isgenerator(object: object) -> TypeIs[GeneratorType[Any, Any, Any]]: - """ - Return true if the object is a generator. + """Return true if the object is a generator. Generator objects provide these attributes: gi_code code object @@ -354,19 +334,14 @@ def isgenerator(object: object) -> TypeIs[GeneratorType[Any, Any, Any]]: """ def iscoroutine(object: object) -> TypeIs[CoroutineType[Any, Any, Any]]: - """ - Return true if the object is a coroutine. - """ + """Return true if the object is a coroutine.""" def isawaitable(object: object) -> TypeIs[Awaitable[Any]]: - """ - Return true if object can be passed to an ``await`` expression. - """ + """Return true if object can be passed to an ``await`` expression.""" @overload def isasyncgenfunction(obj: Callable[..., AsyncGenerator[Any, Any]]) -> bool: - """ - Return true if the object is an asynchronous generator function. + """Return true if the object is an asynchronous generator function. Asynchronous generator functions are defined with "async def" syntax and have "yield" expressions in their body. @@ -384,13 +359,10 @@ class _SupportsDelete(Protocol[_T_contra]): def __delete__(self, instance: _T_contra, /) -> None: ... def isasyncgen(object: object) -> TypeIs[AsyncGeneratorType[Any, Any]]: - """ - Return true if the object is an asynchronous generator. - """ + """Return true if the object is an asynchronous generator.""" def istraceback(object: object) -> TypeIs[TracebackType]: - """ - Return true if the object is a traceback. + """Return true if the object is a traceback. Traceback objects provide these attributes: tb_frame frame object at this level @@ -400,8 +372,7 @@ def istraceback(object: object) -> TypeIs[TracebackType]: """ def isframe(object: object) -> TypeIs[FrameType]: - """ - Return true if the object is a frame object. + """Return true if the object is a frame object. Frame objects provide these attributes: f_back next outer frame object (this frame's caller) @@ -419,8 +390,7 @@ def isframe(object: object) -> TypeIs[FrameType]: """ def iscode(object: object) -> TypeIs[CodeType]: - """ - Return true if the object is a code object. + """Return true if the object is a code object. Code objects provide these attributes: co_argcount number of arguments (not including *, ** args @@ -451,8 +421,7 @@ def iscode(object: object) -> TypeIs[CodeType]: """ def isbuiltin(object: object) -> TypeIs[BuiltinFunctionType]: - """ - Return true if the object is a built-in function or method. + """Return true if the object is a built-in function or method. Built-in functions and methods provide these attributes: __doc__ documentation string @@ -462,9 +431,7 @@ def isbuiltin(object: object) -> TypeIs[BuiltinFunctionType]: if sys.version_info >= (3, 11): def ismethodwrapper(object: object) -> TypeIs[MethodWrapperType]: - """ - Return true if the object is a method wrapper. - """ + """Return true if the object is a method wrapper.""" def isroutine( object: object, @@ -478,13 +445,10 @@ def isroutine( | MethodDescriptorType | ClassMethodDescriptorType ]: - """ - Return true if the object is any kind of function or method. - """ + """Return true if the object is any kind of function or method.""" def ismethoddescriptor(object: object) -> TypeIs[MethodDescriptorType]: - """ - Return true if the object is a method descriptor. + """Return true if the object is a method descriptor. But not if ismethod() or isclass() or isfunction() are true. @@ -501,29 +465,24 @@ def ismethoddescriptor(object: object) -> TypeIs[MethodDescriptorType]: """ def ismemberdescriptor(object: object) -> TypeIs[MemberDescriptorType]: - """ - Return true if the object is a member descriptor. + """Return true if the object is a member descriptor. Member descriptors are specialized descriptors defined in extension modules. """ def isabstract(object: object) -> bool: - """ - Return true if the object is an abstract base class (ABC). - """ + """Return true if the object is an abstract base class (ABC).""" def isgetsetdescriptor(object: object) -> TypeIs[GetSetDescriptorType]: - """ - Return true if the object is a getset descriptor. + """Return true if the object is a getset descriptor. getset descriptors are specialized descriptors defined in extension modules. """ def isdatadescriptor(object: object) -> TypeIs[_SupportsSet[Any, Any] | _SupportsDelete[Any]]: - """ - Return true if the object is a data descriptor. + """Return true if the object is a data descriptor. Data descriptors have a __set__ or a __delete__ attribute. Examples are properties (defined in Python) and getsets and members (defined in C). @@ -540,8 +499,7 @@ _SourceObjectType: TypeAlias = ( ) def findsource(object: _SourceObjectType) -> tuple[list[str], int]: - """ - Return the entire source file and starting line number for an object. + """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines @@ -550,8 +508,7 @@ def findsource(object: _SourceObjectType) -> tuple[list[str], int]: """ def getabsfile(object: _SourceObjectType, _filename: str | None = None) -> str: - """ - Return an absolute path to the source or compiled file for an object. + """Return an absolute path to the source or compiled file for an object. The idea is for each object to have a unique origin, so this routine normalizes the result as much as possible. @@ -561,17 +518,14 @@ def getabsfile(object: _SourceObjectType, _filename: str | None = None) -> str: # to avoid the annoyingly vague `Sequence[str]` return type @overload def getblock(lines: list[str]) -> list[str]: - """ - Extract the block of code at the top of the given list of lines. - """ + """Extract the block of code at the top of the given list of lines.""" @overload def getblock(lines: tuple[str, ...]) -> tuple[str, ...]: ... @overload def getblock(lines: Sequence[str]) -> Sequence[str]: ... def getdoc(object: object) -> str | None: - """ - Get the documentation string for an object. + """Get the documentation string for an object. All tabs are expanded to spaces. To clean up docstrings that are indented to line up with blocks of code, any whitespace than can be @@ -579,31 +533,24 @@ def getdoc(object: object) -> str | None: """ def getcomments(object: object) -> str | None: - """ - Get lines of comments immediately preceding an object's source code. + """Get lines of comments immediately preceding an object's source code. Returns None when source can't be found. """ def getfile(object: _SourceObjectType) -> str: - """ - Work out which source or compiled file an object was defined in. - """ + """Work out which source or compiled file an object was defined in.""" def getmodule(object: object, _filename: str | None = None) -> ModuleType | None: - """ - Return the module an object was defined in, or None if not found. - """ + """Return the module an object was defined in, or None if not found.""" def getsourcefile(object: _SourceObjectType) -> str | None: - """ - Return the filename that can be used to locate an object's source. + """Return the filename that can be used to locate an object's source. Return None if no way can be identified to get the source. """ def getsourcelines(object: _SourceObjectType) -> tuple[list[str], int]: - """ - Return a list of source lines and starting line number for an object. + """Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines @@ -613,8 +560,7 @@ def getsourcelines(object: _SourceObjectType) -> tuple[list[str], int]: """ def getsource(object: _SourceObjectType) -> str: - """ - Return the text of the source code for an object. + """Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An @@ -622,17 +568,14 @@ def getsource(object: _SourceObjectType) -> str: """ def cleandoc(doc: str) -> str: - """ - Clean up indentation from docstrings. + """Clean up indentation from docstrings. Any whitespace that can be uniformly removed from the second line onwards is removed. """ def indentsize(line: str) -> int: - """ - Return the indent size, in spaces, at the start of a line of text. - """ + """Return the indent size, in spaces, at the start of a line of text.""" _IntrospectableCallable: TypeAlias = Callable[..., Any] @@ -649,9 +592,7 @@ if sys.version_info >= (3, 14): eval_str: bool = False, annotation_format: Format = Format.VALUE, # noqa: Y011 ) -> Signature: - """ - Get a signature object for the passed callable. - """ + """Get a signature object for the passed callable.""" elif sys.version_info >= (3, 10): def signature( @@ -662,29 +603,20 @@ elif sys.version_info >= (3, 10): locals: Mapping[str, Any] | None = None, eval_str: bool = False, ) -> Signature: - """ - Get a signature object for the passed callable. - """ + """Get a signature object for the passed callable.""" else: def signature(obj: _IntrospectableCallable, *, follow_wrapped: bool = True) -> Signature: - """ - Get a signature object for the passed callable. - """ + """Get a signature object for the passed callable.""" class _void: - """ - A private marker - used in Parameter & Signature. - """ + """A private marker - used in Parameter & Signature.""" class _empty: - """ - Marker object for Signature.empty and Parameter.empty. - """ + """Marker object for Signature.empty and Parameter.empty.""" class Signature: - """ - A Signature object represents the overall signature of a function. + """A Signature object represents the overall signature of a function. It stores a Parameter object for each parameter accepted by the function, as well as information specific to the function itself. @@ -709,8 +641,7 @@ class Signature: def __init__( self, parameters: Sequence[Parameter] | None = None, *, return_annotation: Any = ..., __validate_parameters__: bool = True ) -> None: - """ - Constructs Signature from the given list of Parameter + """Constructs Signature from the given list of Parameter objects and 'return_annotation'. All arguments are optional. """ empty = _empty @@ -719,22 +650,19 @@ class Signature: @property def return_annotation(self) -> Any: ... def bind(self, *args: Any, **kwargs: Any) -> BoundArguments: - """ - Get a BoundArguments object, that maps the passed `args` + """Get a BoundArguments object, that maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound. """ def bind_partial(self, *args: Any, **kwargs: Any) -> BoundArguments: - """ - Get a BoundArguments object, that partially maps the + """Get a BoundArguments object, that partially maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound. """ def replace(self, *, parameters: Sequence[Parameter] | type[_void] | None = ..., return_annotation: Any = ...) -> Self: - """ - Creates a customized copy of the Signature. + """Creates a customized copy of the Signature. Pass 'parameters' and/or 'return_annotation' arguments to override them in the new copy. """ @@ -751,9 +679,7 @@ class Signature: eval_str: bool = False, annotation_format: Format = Format.VALUE, # noqa: Y011 ) -> Self: - """ - Constructs Signature for the given callable object. - """ + """Constructs Signature for the given callable object.""" elif sys.version_info >= (3, 10): @classmethod def from_callable( @@ -765,19 +691,14 @@ class Signature: locals: Mapping[str, Any] | None = None, eval_str: bool = False, ) -> Self: - """ - Constructs Signature for the given callable object. - """ + """Constructs Signature for the given callable object.""" else: @classmethod def from_callable(cls, obj: _IntrospectableCallable, *, follow_wrapped: bool = True) -> Self: - """ - Constructs Signature for the given callable object. - """ + """Constructs Signature for the given callable object.""" if sys.version_info >= (3, 14): def format(self, *, max_width: int | None = None, quote_annotation_strings: bool = True) -> str: - """ - Create a string representation of the Signature object. + """Create a string representation of the Signature object. If *max_width* integer is passed, signature will try to fit into the *max_width*. @@ -791,8 +712,7 @@ class Signature: """ elif sys.version_info >= (3, 13): def format(self, *, max_width: int | None = None) -> str: - """ - Create a string representation of the Signature object. + """Create a string representation of the Signature object. If *max_width* integer is passed, signature will try to fit into the *max_width*. @@ -818,8 +738,7 @@ elif sys.version_info >= (3, 10): locals: Mapping[str, Any] | None = None, # value types depend on the key eval_str: bool = False, ) -> dict[str, AnnotationForm]: # values are type expressions - """ - Compute the annotations dict for an object. + """Compute the annotations dict for an object. obj may be a callable, class, or module. Passing in an object of any other type raises TypeError. @@ -866,9 +785,7 @@ elif sys.version_info >= (3, 10): # The name is the same as the enum's name in CPython class _ParameterKind(enum.IntEnum): - """ - An enumeration. - """ + """An enumeration.""" POSITIONAL_ONLY = 0 POSITIONAL_OR_KEYWORD = 1 @@ -888,8 +805,7 @@ if sys.version_info >= (3, 12): def getasyncgenstate( agen: AsyncGenerator[Any, Any], ) -> Literal["AGEN_CREATED", "AGEN_RUNNING", "AGEN_SUSPENDED", "AGEN_CLOSED"]: - """ - Get current state of an asynchronous generator object. + """Get current state of an asynchronous generator object. Possible states are: AGEN_CREATED: Waiting to start execution. @@ -899,8 +815,7 @@ if sys.version_info >= (3, 12): """ def getasyncgenlocals(agen: AsyncGeneratorType[Any, Any]) -> dict[str, Any]: - """ - Get the mapping of asynchronous generator local variables to their current + """Get the mapping of asynchronous generator local variables to their current values. A dict is returned, with the keys the local variable names and values the @@ -908,8 +823,7 @@ if sys.version_info >= (3, 12): """ class Parameter: - """ - Represents a parameter in a function signature. + """Represents a parameter in a function signature. Has the following public attributes: @@ -954,9 +868,7 @@ class Parameter: default: Any = ..., annotation: Any = ..., ) -> Self: - """ - Creates a customized copy of the Parameter. - """ + """Creates a customized copy of the Parameter.""" if sys.version_info >= (3, 13): __replace__ = replace @@ -964,8 +876,7 @@ class Parameter: def __hash__(self) -> int: ... class BoundArguments: - """ - Result of `Signature.bind` call. Holds the mapping of arguments + """Result of `Signature.bind` call. Holds the mapping of arguments to the function's parameters. Has the following public attributes: @@ -990,8 +901,7 @@ class BoundArguments: def signature(self) -> Signature: ... def __init__(self, signature: Signature, arguments: OrderedDict[str, Any]) -> None: ... def apply_defaults(self) -> None: - """ - Set default values for missing arguments. + """Set default values for missing arguments. For variable-positional arguments (*args) the default is an empty tuple. @@ -1010,8 +920,7 @@ class BoundArguments: _ClassTreeItem: TypeAlias = list[tuple[type, ...]] | list[_ClassTreeItem] def getclasstree(classes: list[type], unique: bool = False) -> _ClassTreeItem: - """ - Arrange the given list of classes into a hierarchy of nested lists. + """Arrange the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list. Each entry is a 2-tuple @@ -1022,22 +931,17 @@ def getclasstree(classes: list[type], unique: bool = False) -> _ClassTreeItem: """ def walktree(classes: list[type], children: Mapping[type[Any], list[type]], parent: type[Any] | None) -> _ClassTreeItem: - """ - Recursive helper function for getclasstree(). - """ + """Recursive helper function for getclasstree().""" class Arguments(NamedTuple): - """ - Arguments(args, varargs, varkw) - """ + """Arguments(args, varargs, varkw)""" args: list[str] varargs: str | None varkw: str | None def getargs(co: CodeType) -> Arguments: - """ - Get information about the arguments accepted by a code object. + """Get information about the arguments accepted by a code object. Three things are returned: (args, varargs, varkw), where 'args' is the list of argument names. Keyword-only arguments are @@ -1047,9 +951,7 @@ def getargs(co: CodeType) -> Arguments: if sys.version_info < (3, 11): class ArgSpec(NamedTuple): - """ - ArgSpec(args, varargs, keywords, defaults) - """ + """ArgSpec(args, varargs, keywords, defaults)""" args: list[str] varargs: str | None @@ -1057,8 +959,7 @@ if sys.version_info < (3, 11): defaults: tuple[Any, ...] def getargspec(func: object) -> ArgSpec: - """ - Get the names and default values of a function's parameters. + """Get the names and default values of a function's parameters. A tuple of four things is returned: (args, varargs, keywords, defaults). 'args' is a list of the argument names, including keyword-only argument names. @@ -1079,9 +980,7 @@ if sys.version_info < (3, 11): """ class FullArgSpec(NamedTuple): - """ - FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations) - """ + """FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)""" args: list[str] varargs: str | None @@ -1092,8 +991,7 @@ class FullArgSpec(NamedTuple): annotations: dict[str, Any] def getfullargspec(func: object) -> FullArgSpec: - """ - Get the names and default values of a callable object's parameters. + """Get the names and default values of a callable object's parameters. A tuple of seven things is returned: (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations). @@ -1110,9 +1008,7 @@ def getfullargspec(func: object) -> FullArgSpec: """ class ArgInfo(NamedTuple): - """ - ArgInfo(args, varargs, keywords, locals) - """ + """ArgInfo(args, varargs, keywords, locals)""" args: list[str] varargs: str | None @@ -1120,8 +1016,7 @@ class ArgInfo(NamedTuple): locals: dict[str, Any] def getargvalues(frame: FrameType) -> ArgInfo: - """ - Get information about arguments passed into a particular frame. + """Get information about arguments passed into a particular frame. A tuple of four things is returned: (args, varargs, varkw, locals). 'args' is a list of the argument names. @@ -1153,8 +1048,7 @@ if sys.version_info < (3, 11): formatreturns: Callable[[Any], str] = ..., formatannotation: Callable[[Any], str] = ..., ) -> str: - """ - Format an argument spec from the values returned by getfullargspec. + """Format an argument spec from the values returned by getfullargspec. The first seven arguments are (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations). The other five arguments @@ -1176,8 +1070,7 @@ def formatargvalues( formatvarkw: Callable[[str], str] | None = ..., formatvalue: Callable[[Any], str] | None = ..., ) -> str: - """ - Format an argument spec from the 4 values returned by getargvalues. + """Format an argument spec from the 4 values returned by getargvalues. The first four arguments are (args, varargs, varkw, locals). The next four arguments are the corresponding optional formatting functions @@ -1186,13 +1079,10 @@ def formatargvalues( """ def getmro(cls: type) -> tuple[type, ...]: - """ - Return tuple of base classes (including cls) in method resolution order. - """ + """Return tuple of base classes (including cls) in method resolution order.""" def getcallargs(func: Callable[_P, Any], /, *args: _P.args, **kwds: _P.kwargs) -> dict[str, Any]: - """ - Get the mapping of arguments to values. + """Get the mapping of arguments to values. A dict is returned, with keys the function argument names (including the names of the * and ** arguments, if any), and values the respective bound @@ -1200,9 +1090,7 @@ def getcallargs(func: Callable[_P, Any], /, *args: _P.args, **kwds: _P.kwargs) - """ class ClosureVars(NamedTuple): - """ - ClosureVars(nonlocals, globals, builtins, unbound) - """ + """ClosureVars(nonlocals, globals, builtins, unbound)""" nonlocals: Mapping[str, Any] globals: Mapping[str, Any] @@ -1210,8 +1098,7 @@ class ClosureVars(NamedTuple): unbound: AbstractSet[str] def getclosurevars(func: _IntrospectableCallable) -> ClosureVars: - """ - Get the mapping of free variables to their current values. + """Get the mapping of free variables to their current values. Returns a named tuple of dicts mapping the current nonlocal, global and builtin references as seen by the body of the function. A final @@ -1219,8 +1106,7 @@ def getclosurevars(func: _IntrospectableCallable) -> ClosureVars: """ def unwrap(func: Callable[..., Any], *, stop: Callable[[Callable[..., Any]], Any] | None = None) -> Any: - """ - Get the object wrapped by *func*. + """Get the object wrapped by *func*. Follows the chain of :attr:`__wrapped__` attributes returning the last object in the chain. @@ -1241,9 +1127,7 @@ def unwrap(func: Callable[..., Any], *, stop: Callable[[Callable[..., Any]], Any if sys.version_info >= (3, 11): class _Traceback(NamedTuple): - """ - _Traceback(filename, lineno, function, code_context, index) - """ + """_Traceback(filename, lineno, function, code_context, index)""" filename: str lineno: int @@ -1265,9 +1149,7 @@ if sys.version_info >= (3, 11): ) -> Self: ... class _FrameInfo(NamedTuple): - """ - _FrameInfo(frame, filename, lineno, function, code_context, index) - """ + """_FrameInfo(frame, filename, lineno, function, code_context, index)""" frame: FrameType filename: str @@ -1292,9 +1174,7 @@ if sys.version_info >= (3, 11): else: class Traceback(NamedTuple): - """ - Traceback(filename, lineno, function, code_context, index) - """ + """Traceback(filename, lineno, function, code_context, index)""" filename: str lineno: int @@ -1303,9 +1183,7 @@ else: index: int | None # type: ignore[assignment] class FrameInfo(NamedTuple): - """ - FrameInfo(frame, filename, lineno, function, code_context, index) - """ + """FrameInfo(frame, filename, lineno, function, code_context, index)""" frame: FrameType filename: str @@ -1315,8 +1193,7 @@ else: index: int | None # type: ignore[assignment] def getframeinfo(frame: FrameType | TracebackType, context: int = 1) -> Traceback: - """ - Get information about a frame or traceback object. + """Get information about a frame or traceback object. A tuple of five things is returned: the filename, the line number of the current line, the function name, a list of lines of context from @@ -1326,48 +1203,37 @@ def getframeinfo(frame: FrameType | TracebackType, context: int = 1) -> Tracebac """ def getouterframes(frame: Any, context: int = 1) -> list[FrameInfo]: - """ - Get a list of records for a frame and all higher (calling) frames. + """Get a list of records for a frame and all higher (calling) frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context. """ def getinnerframes(tb: TracebackType, context: int = 1) -> list[FrameInfo]: - """ - Get a list of records for a traceback's frame and all lower frames. + """Get a list of records for a traceback's frame and all lower frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context. """ def getlineno(frame: FrameType) -> int: - """ - Get the line number from a frame object, allowing for optimization. - """ + """Get the line number from a frame object, allowing for optimization.""" def currentframe() -> FrameType | None: - """ - Return the frame of the caller or None if this is not possible. - """ + """Return the frame of the caller or None if this is not possible.""" def stack(context: int = 1) -> list[FrameInfo]: - """ - Return a list of records for the stack above the caller's frame. - """ + """Return a list of records for the stack above the caller's frame.""" def trace(context: int = 1) -> list[FrameInfo]: - """ - Return a list of records for the stack below the current exception. - """ + """Return a list of records for the stack below the current exception.""" # # Fetching attributes statically # def getattr_static(obj: object, attr: str, default: Any | None = ...) -> Any: - """ - Retrieve attributes without triggering dynamic lookup via the + """Retrieve attributes without triggering dynamic lookup via the descriptor protocol, __getattr__ or __getattribute__. Note: this function may not be able to retrieve all attributes @@ -1390,8 +1256,7 @@ GEN_CLOSED: Final = "GEN_CLOSED" def getgeneratorstate( generator: Generator[Any, Any, Any], ) -> Literal["GEN_CREATED", "GEN_RUNNING", "GEN_SUSPENDED", "GEN_CLOSED"]: - """ - Get current state of a generator-iterator. + """Get current state of a generator-iterator. Possible states are: GEN_CREATED: Waiting to start execution. @@ -1408,8 +1273,7 @@ CORO_CLOSED: Final = "CORO_CLOSED" def getcoroutinestate( coroutine: Coroutine[Any, Any, Any], ) -> Literal["CORO_CREATED", "CORO_RUNNING", "CORO_SUSPENDED", "CORO_CLOSED"]: - """ - Get current state of a coroutine object. + """Get current state of a coroutine object. Possible states are: CORO_CREATED: Waiting to start execution. @@ -1419,16 +1283,14 @@ def getcoroutinestate( """ def getgeneratorlocals(generator: Generator[Any, Any, Any]) -> dict[str, Any]: - """ - Get the mapping of generator local variables to their current values. + """Get the mapping of generator local variables to their current values. A dict is returned, with the keys the local variable names and values the bound values. """ def getcoroutinelocals(coroutine: Coroutine[Any, Any, Any]) -> dict[str, Any]: - """ - Get the mapping of coroutine local variables to their current values. + """Get the mapping of coroutine local variables to their current values. A dict is returned, with the keys the local variable names and values the bound values. @@ -1439,9 +1301,7 @@ def getcoroutinelocals(coroutine: Coroutine[Any, Any, Any]) -> dict[str, Any]: _Object: TypeAlias = object class Attribute(NamedTuple): - """ - Attribute(name, kind, defining_class, object) - """ + """Attribute(name, kind, defining_class, object)""" name: str kind: Literal["class method", "static method", "property", "method", "data"] @@ -1449,8 +1309,7 @@ class Attribute(NamedTuple): object: _Object def classify_class_attrs(cls: type) -> list[Attribute]: - """ - Return list of attribute-descriptor tuples. + """Return list of attribute-descriptor tuples. For each name in dir(cls), the return list contains a 4-tuple with these elements: diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/io.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/io.pyi index 34001ce1da..0b70621594 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/io.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/io.pyi @@ -98,8 +98,7 @@ SEEK_END: Final = 2 class UnsupportedOperation(OSError, ValueError): ... class IOBase(_IOBase, metaclass=abc.ABCMeta): - """ - The abstract base class for all I/O classes. + """The abstract base class for all I/O classes. This class provides dummy implementations for many methods that derived classes can override selectively; the default implementations @@ -131,13 +130,10 @@ class IOBase(_IOBase, metaclass=abc.ABCMeta): """ class RawIOBase(_RawIOBase, IOBase): - """ - Base class for raw binary I/O. - """ + """Base class for raw binary I/O.""" class BufferedIOBase(_BufferedIOBase, IOBase): - """ - Base class for buffered IO objects. + """Base class for buffered IO objects. The main difference with RawIOBase is that the read() method supports omitting the size argument, and does not have a default @@ -153,8 +149,7 @@ class BufferedIOBase(_BufferedIOBase, IOBase): """ class TextIOBase(_TextIOBase, IOBase): - """ - Base class for text I/O. + """Base class for text I/O. This class provides a character and line based interface to stream I/O. There is no readinto method because Python's character strings @@ -163,28 +158,23 @@ class TextIOBase(_TextIOBase, IOBase): if sys.version_info >= (3, 14): class Reader(Protocol[_T_co]): - """ - Protocol for simple I/O reader instances. + """Protocol for simple I/O reader instances. This protocol only supports blocking I/O. """ def read(self, size: int = ..., /) -> _T_co: - """ - Read data from the input stream and return it. + """Read data from the input stream and return it. If *size* is specified, at most *size* items (bytes/characters) will be read. """ class Writer(Protocol[_T_contra]): - """ - Protocol for simple I/O writer instances. + """Protocol for simple I/O writer instances. This protocol only supports blocking I/O. """ def write(self, data: _T_contra, /) -> int: - """ - Write *data* to the output stream and return the number of items written. - """ + """Write *data* to the output stream and return the number of items written.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/ipaddress.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/ipaddress.pyi index a2f7afa579..0924d38d14 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/ipaddress.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/ipaddress.pyi @@ -21,8 +21,7 @@ _RawIPAddress: TypeAlias = int | str | bytes | IPv4Address | IPv6Address _RawNetworkPart: TypeAlias = IPv4Network | IPv6Network | IPv4Interface | IPv6Interface def ip_address(address: _RawIPAddress) -> IPv4Address | IPv6Address: - """ - Take an IP string/int and return an object of the correct type. + """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or @@ -40,8 +39,7 @@ def ip_address(address: _RawIPAddress) -> IPv4Address | IPv6Address: def ip_network( address: _RawIPAddress | _RawNetworkPart | tuple[_RawIPAddress] | tuple[_RawIPAddress, int], strict: bool = True ) -> IPv4Network | IPv6Network: - """ - Take an IP string/int and return an object of the correct type. + """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP network. Either IPv4 or @@ -59,8 +57,7 @@ def ip_network( def ip_interface( address: _RawIPAddress | _RawNetworkPart | tuple[_RawIPAddress] | tuple[_RawIPAddress, int], ) -> IPv4Interface | IPv6Interface: - """ - Take an IP string/int and return an object of the correct type. + """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or @@ -81,26 +78,19 @@ def ip_interface( """ class _IPAddressBase: - """ - The mother class. - """ + """The mother class.""" @property def compressed(self) -> str: - """ - Return the shorthand version of the IP address as a string. - """ + """Return the shorthand version of the IP address as a string.""" @property def exploded(self) -> str: - """ - Return the longhand version of the IP address as a string. - """ + """Return the longhand version of the IP address as a string.""" @property def reverse_pointer(self) -> str: - """ - The name of the reverse DNS pointer for the IP address, e.g.: + """The name of the reverse DNS pointer for the IP address, e.g.: >>> ipaddress.ip_address("127.0.0.1").reverse_pointer '1.0.0.127.in-addr.arpa' >>> ipaddress.ip_address("2001:db8::1").reverse_pointer @@ -111,8 +101,7 @@ class _IPAddressBase: def version(self) -> int: ... class _BaseAddress(_IPAddressBase): - """ - A generic IP object. + """A generic IP object. This IP class contains the version independent methods which are used by single IP addresses. @@ -123,8 +112,7 @@ class _BaseAddress(_IPAddressBase): def __int__(self) -> int: ... def __sub__(self, other: int) -> Self: ... def __format__(self, fmt: str) -> str: - """ - Returns an IP address as a formatted string. + """Returns an IP address as a formatted string. Supported presentation types are: 's': returns the IP address as a string (default) @@ -140,38 +128,25 @@ class _BaseAddress(_IPAddressBase): def __lt__(self, other: Self) -> bool: ... if sys.version_info >= (3, 11): def __ge__(self, other: Self) -> bool: - """ - Return a >= b. Computed by @total_ordering from (not a < b). - """ + """Return a >= b. Computed by @total_ordering from (not a < b).""" def __gt__(self, other: Self) -> bool: - """ - Return a > b. Computed by @total_ordering from (not a < b) and (a != b). - """ + """Return a > b. Computed by @total_ordering from (not a < b) and (a != b).""" def __le__(self, other: Self) -> bool: - """ - Return a <= b. Computed by @total_ordering from (a < b) or (a == b). - """ + """Return a <= b. Computed by @total_ordering from (a < b) or (a == b).""" else: def __ge__(self, other: Self, NotImplemented: Any = ...) -> bool: - """ - Return a >= b. Computed by @total_ordering from (not a < b). - """ + """Return a >= b. Computed by @total_ordering from (not a < b).""" def __gt__(self, other: Self, NotImplemented: Any = ...) -> bool: - """ - Return a > b. Computed by @total_ordering from (not a < b) and (a != b). - """ + """Return a > b. Computed by @total_ordering from (not a < b) and (a != b).""" def __le__(self, other: Self, NotImplemented: Any = ...) -> bool: - """ - Return a <= b. Computed by @total_ordering from (a < b) or (a == b). - """ + """Return a <= b. Computed by @total_ordering from (a < b) or (a == b).""" class _BaseNetwork(_IPAddressBase, Generic[_A]): - """ - A generic IP network object. + """A generic IP network object. This IP class contains the version independent methods which are used by networks. @@ -187,38 +162,25 @@ class _BaseNetwork(_IPAddressBase, Generic[_A]): def __lt__(self, other: Self) -> bool: ... if sys.version_info >= (3, 11): def __ge__(self, other: Self) -> bool: - """ - Return a >= b. Computed by @total_ordering from (not a < b). - """ + """Return a >= b. Computed by @total_ordering from (not a < b).""" def __gt__(self, other: Self) -> bool: - """ - Return a > b. Computed by @total_ordering from (not a < b) and (a != b). - """ + """Return a > b. Computed by @total_ordering from (not a < b) and (a != b).""" def __le__(self, other: Self) -> bool: - """ - Return a <= b. Computed by @total_ordering from (a < b) or (a == b). - """ + """Return a <= b. Computed by @total_ordering from (a < b) or (a == b).""" else: def __ge__(self, other: Self, NotImplemented: Any = ...) -> bool: - """ - Return a >= b. Computed by @total_ordering from (not a < b). - """ + """Return a >= b. Computed by @total_ordering from (not a < b).""" def __gt__(self, other: Self, NotImplemented: Any = ...) -> bool: - """ - Return a > b. Computed by @total_ordering from (not a < b) and (a != b). - """ + """Return a > b. Computed by @total_ordering from (not a < b) and (a != b).""" def __le__(self, other: Self, NotImplemented: Any = ...) -> bool: - """ - Return a <= b. Computed by @total_ordering from (a < b) or (a == b). - """ + """Return a <= b. Computed by @total_ordering from (a < b) or (a == b).""" def address_exclude(self, other: Self) -> Iterator[Self]: - """ - Remove an address from a larger block. + """Remove an address from a larger block. For example: @@ -256,8 +218,7 @@ class _BaseNetwork(_IPAddressBase, Generic[_A]): @property def broadcast_address(self) -> _A: ... def compare_networks(self, other: Self) -> int: - """ - Compare two IP objects. + """Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the @@ -289,8 +250,7 @@ class _BaseNetwork(_IPAddressBase, Generic[_A]): """ def hosts(self) -> Iterator[_A]: - """ - Generate Iterator over usable hosts in a network. + """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the network or broadcast addresses. @@ -298,8 +258,7 @@ class _BaseNetwork(_IPAddressBase, Generic[_A]): @property def is_global(self) -> bool: - """ - Test if this address is allocated for public networks. + """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per @@ -308,8 +267,7 @@ class _BaseNetwork(_IPAddressBase, Generic[_A]): @property def is_link_local(self) -> bool: - """ - Test if the address is reserved for link-local. + """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. @@ -317,8 +275,7 @@ class _BaseNetwork(_IPAddressBase, Generic[_A]): @property def is_loopback(self) -> bool: - """ - Test if the address is a loopback address. + """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in @@ -327,8 +284,7 @@ class _BaseNetwork(_IPAddressBase, Generic[_A]): @property def is_multicast(self) -> bool: - """ - Test if the address is reserved for multicast use. + """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. @@ -337,8 +293,7 @@ class _BaseNetwork(_IPAddressBase, Generic[_A]): @property def is_private(self) -> bool: - """ - Test if this network belongs to a private range. + """Test if this network belongs to a private range. Returns: A boolean, True if the network is reserved per @@ -347,8 +302,7 @@ class _BaseNetwork(_IPAddressBase, Generic[_A]): @property def is_reserved(self) -> bool: - """ - Test if the address is otherwise IETF reserved. + """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the @@ -357,8 +311,7 @@ class _BaseNetwork(_IPAddressBase, Generic[_A]): @property def is_unspecified(self) -> bool: - """ - Test if the address is unspecified. + """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in @@ -367,30 +320,21 @@ class _BaseNetwork(_IPAddressBase, Generic[_A]): @property def num_addresses(self) -> int: - """ - Number of hosts in the current subnet. - """ + """Number of hosts in the current subnet.""" def overlaps(self, other: _BaseNetwork[IPv4Address] | _BaseNetwork[IPv6Address]) -> bool: - """ - Tell if self is partly contained in other. - """ + """Tell if self is partly contained in other.""" @property def prefixlen(self) -> int: ... def subnet_of(self, other: Self) -> bool: - """ - Return True if this network is a subnet of other. - """ + """Return True if this network is a subnet of other.""" def supernet_of(self, other: Self) -> bool: - """ - Return True if this network is a supernet of other. - """ + """Return True if this network is a supernet of other.""" def subnets(self, prefixlen_diff: int = 1, new_prefix: int | None = None) -> Iterator[Self]: - """ - The subnets which join to make the current subnet. + """The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 @@ -416,8 +360,7 @@ class _BaseNetwork(_IPAddressBase, Generic[_A]): """ def supernet(self, prefixlen_diff: int = 1, new_prefix: int | None = None) -> Self: - """ - The supernet containing the current network. + """The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of @@ -447,8 +390,7 @@ class _BaseNetwork(_IPAddressBase, Generic[_A]): def hostmask(self) -> _A: ... class _BaseV4: - """ - Base IPv4 object. + """Base IPv4 object. The following methods are used by IPv4 objects in both single IP addresses and networks. @@ -460,8 +402,7 @@ class _BaseV4: else: @property def version(self) -> Literal[4]: - """ - int([x]) -> integer + """int([x]) -> integer int(x, base=10) -> integer Convert a number or string to an integer, or return 0 if no arguments @@ -479,8 +420,7 @@ class _BaseV4: @property def max_prefixlen(self) -> Literal[32]: - """ - int([x]) -> integer + """int([x]) -> integer int(x, base=10) -> integer Convert a number or string to an integer, or return 0 if no arguments @@ -497,13 +437,10 @@ class _BaseV4: """ class IPv4Address(_BaseV4, _BaseAddress): - """ - Represent and manipulate single IPv4 Addresses. - """ + """Represent and manipulate single IPv4 Addresses.""" def __init__(self, address: object) -> None: - """ - Args: + """Args: address: A string or integer representing the IP Additionally, an integer can be passed, so @@ -518,8 +455,7 @@ class IPv4Address(_BaseV4, _BaseAddress): @property def is_global(self) -> bool: - """ - ``True`` if the address is defined as globally reachable by + """``True`` if the address is defined as globally reachable by iana-ipv4-special-registry_ (for IPv4) or iana-ipv6-special-registry_ (for IPv6) with the following exception: @@ -535,8 +471,7 @@ class IPv4Address(_BaseV4, _BaseAddress): @property def is_link_local(self) -> bool: - """ - Test if the address is reserved for link-local. + """Test if the address is reserved for link-local. Returns: A boolean, True if the address is link-local per RFC 3927. @@ -544,8 +479,7 @@ class IPv4Address(_BaseV4, _BaseAddress): @property def is_loopback(self) -> bool: - """ - Test if the address is a loopback address. + """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback per RFC 3330. @@ -553,8 +487,7 @@ class IPv4Address(_BaseV4, _BaseAddress): @property def is_multicast(self) -> bool: - """ - Test if the address is reserved for multicast use. + """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is multicast. @@ -563,8 +496,7 @@ class IPv4Address(_BaseV4, _BaseAddress): @property def is_private(self) -> bool: - """ - ``True`` if the address is defined as not globally reachable by + """``True`` if the address is defined as not globally reachable by iana-ipv4-special-registry_ (for IPv4) or iana-ipv6-special-registry_ (for IPv6) with the following exceptions: @@ -581,8 +513,7 @@ class IPv4Address(_BaseV4, _BaseAddress): @property def is_reserved(self) -> bool: - """ - Test if the address is otherwise IETF reserved. + """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within the @@ -591,8 +522,7 @@ class IPv4Address(_BaseV4, _BaseAddress): @property def is_unspecified(self) -> bool: - """ - Test if the address is unspecified. + """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in @@ -601,22 +531,18 @@ class IPv4Address(_BaseV4, _BaseAddress): @property def packed(self) -> bytes: - """ - The binary representation of this address. - """ + """The binary representation of this address.""" if sys.version_info >= (3, 13): @property def ipv6_mapped(self) -> IPv6Address: - """ - Return the IPv4-mapped IPv6 address. + """Return the IPv4-mapped IPv6 address. Returns: The IPv4-mapped IPv6 address per RFC 4291. """ class IPv4Network(_BaseV4, _BaseNetwork[IPv4Address]): - """ - This class represents and manipulates 32-bit IPv4 network + addresses.. + """This class represents and manipulates 32-bit IPv4 network + addresses.. Attributes: [examples for IPv4Network('192.0.2.0/27')] .network_address: IPv4Address('192.0.2.0') @@ -627,8 +553,7 @@ class IPv4Network(_BaseV4, _BaseNetwork[IPv4Address]): """ def __init__(self, address: object, strict: bool = ...) -> None: - """ - Instantiate a new IPv4 network object. + """Instantiate a new IPv4 network object. Args: address: A string or integer representing the IP [& network]. @@ -680,8 +605,7 @@ class IPv4Interface(IPv4Address): def with_prefixlen(self) -> str: ... class _BaseV6: - """ - Base IPv6 object. + """Base IPv6 object. The following methods are used by IPv6 objects in both single IP addresses and networks. @@ -693,8 +617,7 @@ class _BaseV6: else: @property def version(self) -> Literal[6]: - """ - int([x]) -> integer + """int([x]) -> integer int(x, base=10) -> integer Convert a number or string to an integer, or return 0 if no arguments @@ -712,8 +635,7 @@ class _BaseV6: @property def max_prefixlen(self) -> Literal[128]: - """ - int([x]) -> integer + """int([x]) -> integer int(x, base=10) -> integer Convert a number or string to an integer, or return 0 if no arguments @@ -730,13 +652,10 @@ class _BaseV6: """ class IPv6Address(_BaseV6, _BaseAddress): - """ - Represent and manipulate single IPv6 Addresses. - """ + """Represent and manipulate single IPv6 Addresses.""" def __init__(self, address: object) -> None: - """ - Instantiate a new IPv6 address object. + """Instantiate a new IPv6 address object. Args: address: A string or integer representing the IP @@ -754,8 +673,7 @@ class IPv6Address(_BaseV6, _BaseAddress): @property def is_global(self) -> bool: - """ - ``True`` if the address is defined as globally reachable by + """``True`` if the address is defined as globally reachable by iana-ipv4-special-registry_ (for IPv4) or iana-ipv6-special-registry_ (for IPv6) with the following exception: @@ -771,8 +689,7 @@ class IPv6Address(_BaseV6, _BaseAddress): @property def is_link_local(self) -> bool: - """ - Test if the address is reserved for link-local. + """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. @@ -780,8 +697,7 @@ class IPv6Address(_BaseV6, _BaseAddress): @property def is_loopback(self) -> bool: - """ - Test if the address is a loopback address. + """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in @@ -790,8 +706,7 @@ class IPv6Address(_BaseV6, _BaseAddress): @property def is_multicast(self) -> bool: - """ - Test if the address is reserved for multicast use. + """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. @@ -800,8 +715,7 @@ class IPv6Address(_BaseV6, _BaseAddress): @property def is_private(self) -> bool: - """ - ``True`` if the address is defined as not globally reachable by + """``True`` if the address is defined as not globally reachable by iana-ipv4-special-registry_ (for IPv4) or iana-ipv6-special-registry_ (for IPv6) with the following exceptions: @@ -818,8 +732,7 @@ class IPv6Address(_BaseV6, _BaseAddress): @property def is_reserved(self) -> bool: - """ - Test if the address is otherwise IETF reserved. + """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the @@ -828,8 +741,7 @@ class IPv6Address(_BaseV6, _BaseAddress): @property def is_unspecified(self) -> bool: - """ - Test if the address is unspecified. + """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in @@ -838,14 +750,11 @@ class IPv6Address(_BaseV6, _BaseAddress): @property def packed(self) -> bytes: - """ - The binary representation of this address. - """ + """The binary representation of this address.""" @property def ipv4_mapped(self) -> IPv4Address | None: - """ - Return the IPv4 mapped address. + """Return the IPv4 mapped address. Returns: If the IPv6 address is a v4 mapped address, return the @@ -854,8 +763,7 @@ class IPv6Address(_BaseV6, _BaseAddress): @property def is_site_local(self) -> bool: - """ - Test if the address is reserved for site-local. + """Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local @@ -867,8 +775,7 @@ class IPv6Address(_BaseV6, _BaseAddress): @property def sixtofour(self) -> IPv4Address | None: - """ - Return the IPv4 6to4 embedded address. + """Return the IPv4 6to4 embedded address. Returns: The IPv4 6to4-embedded address if present or None if the @@ -877,8 +784,7 @@ class IPv6Address(_BaseV6, _BaseAddress): @property def teredo(self) -> tuple[IPv4Address, IPv4Address] | None: - """ - Tuple of embedded teredo IPs. + """Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address @@ -888,8 +794,7 @@ class IPv6Address(_BaseV6, _BaseAddress): @property def scope_id(self) -> str | None: - """ - Identifier of a particular zone of the address's scope. + """Identifier of a particular zone of the address's scope. See RFC 4007 for details. @@ -901,8 +806,7 @@ class IPv6Address(_BaseV6, _BaseAddress): def __eq__(self, other: object) -> bool: ... class IPv6Network(_BaseV6, _BaseNetwork[IPv6Address]): - """ - This class represents and manipulates 128-bit IPv6 networks. + """This class represents and manipulates 128-bit IPv6 networks. Attributes: [examples for IPv6('2001:db8::1000/124')] .network_address: IPv6Address('2001:db8::1000') @@ -913,8 +817,7 @@ class IPv6Network(_BaseV6, _BaseNetwork[IPv6Address]): """ def __init__(self, address: object, strict: bool = ...) -> None: - """ - Instantiate a new IPv6 Network object. + """Instantiate a new IPv6 Network object. Args: address: A string or integer representing the IPv6 network or the @@ -947,8 +850,7 @@ class IPv6Network(_BaseV6, _BaseNetwork[IPv6Address]): @property def is_site_local(self) -> bool: - """ - Test if the address is reserved for site-local. + """Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local @@ -975,8 +877,7 @@ class IPv6Interface(IPv6Address): def with_prefixlen(self) -> str: ... def v4_int_to_packed(address: int) -> bytes: - """ - Represent an address as 4 packed bytes in network (big-endian) order. + """Represent an address as 4 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv4 IP address. @@ -990,8 +891,7 @@ def v4_int_to_packed(address: int) -> bytes: """ def v6_int_to_packed(address: int) -> bytes: - """ - Represent an address as 16 packed bytes in network (big-endian) order. + """Represent an address as 16 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv6 IP address. @@ -1003,8 +903,7 @@ def v6_int_to_packed(address: int) -> bytes: # Third overload is technically incorrect, but convenient when first and last are return values of ip_address() @overload def summarize_address_range(first: IPv4Address, last: IPv4Address) -> Iterator[IPv4Network]: - """ - Summarize a network range given the first and last IP addresses. + """Summarize a network range given the first and last IP addresses. Example: >>> list(summarize_address_range(IPv4Address('192.0.2.0'), @@ -1036,8 +935,7 @@ def summarize_address_range( first: IPv4Address | IPv6Address, last: IPv4Address | IPv6Address ) -> Iterator[IPv4Network] | Iterator[IPv6Network]: ... def collapse_addresses(addresses: Iterable[_N]) -> Iterator[_N]: - """ - Collapse a list of IP objects. + """Collapse a list of IP objects. Example: collapse_addresses([IPv4Network('192.0.2.0/25'), @@ -1056,8 +954,7 @@ def collapse_addresses(addresses: Iterable[_N]) -> Iterator[_N]: @overload def get_mixed_type_key(obj: _A) -> tuple[int, _A]: - """ - Return a key suitable for sorting between networks and addresses. + """Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression @@ -1080,11 +977,7 @@ def get_mixed_type_key(obj: IPv4Network) -> tuple[int, IPv4Address, IPv4Address] def get_mixed_type_key(obj: IPv6Network) -> tuple[int, IPv6Address, IPv6Address]: ... class AddressValueError(ValueError): - """ - A Value Error related to the address. - """ + """A Value Error related to the address.""" class NetmaskValueError(ValueError): - """ - A Value Error related to the netmask. - """ + """A Value Error related to the netmask.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/itertools.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/itertools.pyi index 51d45a1fe6..c196950715 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/itertools.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/itertools.pyi @@ -60,8 +60,7 @@ _Predicate: TypeAlias = Callable[[_T], object] # Technically count can take anything that implements a number protocol and has an add method # but we can't enforce the add method class count(Generic[_N]): - """ - Return a count object whose .__next__() method returns consecutive values. + """Return a count object whose .__next__() method returns consecutive values. Equivalent to: def count(firstval=0, step=1): @@ -78,34 +77,23 @@ class count(Generic[_N]): @overload def __new__(cls, *, step: _N) -> count[_N]: ... def __next__(self) -> _N: - """ - Implement next(self). - """ + """Implement next(self).""" def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" class cycle(Generic[_T]): - """ - Return elements from the iterable until it is exhausted. Then repeat the sequence indefinitely. - """ + """Return elements from the iterable until it is exhausted. Then repeat the sequence indefinitely.""" def __new__(cls, iterable: Iterable[_T], /) -> Self: ... def __next__(self) -> _T: - """ - Implement next(self). - """ + """Implement next(self).""" def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" class repeat(Generic[_T]): - """ - repeat(object [,times]) -> create an iterator which returns the object + """repeat(object [,times]) -> create an iterator which returns the object for the specified number of times. If not specified, returns the object endlessly. """ @@ -115,72 +103,50 @@ class repeat(Generic[_T]): @overload def __new__(cls, object: _T, times: int) -> Self: ... def __next__(self) -> _T: - """ - Implement next(self). - """ + """Implement next(self).""" def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __length_hint__(self) -> int: - """ - Private method returning an estimate of len(list(it)). - """ + """Private method returning an estimate of len(list(it)).""" class accumulate(Generic[_T]): - """ - Return series of accumulated sums (or other binary function results). - """ + """Return series of accumulated sums (or other binary function results).""" @overload def __new__(cls, iterable: Iterable[_T], func: None = None, *, initial: _T | None = ...) -> Self: ... @overload def __new__(cls, iterable: Iterable[_S], func: Callable[[_T, _S], _T], *, initial: _T | None = ...) -> Self: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> _T: - """ - Implement next(self). - """ + """Implement next(self).""" class chain(Generic[_T]): - """ - Return a chain object whose .__next__() method returns elements from the + """Return a chain object whose .__next__() method returns elements from the first iterable until it is exhausted, then elements from the next iterable, until all of the iterables are exhausted. """ def __new__(cls, *iterables: Iterable[_T]) -> Self: ... def __next__(self) -> _T: - """ - Implement next(self). - """ + """Implement next(self).""" def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" @classmethod # We use type[Any] and not type[_S] to not lose the type inference from __iterable def from_iterable(cls: type[Any], iterable: Iterable[Iterable[_S]], /) -> chain[_S]: - """ - Alternative chain() constructor taking a single iterable argument that evaluates lazily. - """ + """Alternative chain() constructor taking a single iterable argument that evaluates lazily.""" def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" class compress(Generic[_T]): - """ - Return data elements corresponding to true selector elements. + """Return data elements corresponding to true selector elements. Forms a shorter iterator from selected data elements using the selectors to choose the data elements. @@ -188,54 +154,39 @@ class compress(Generic[_T]): def __new__(cls, data: Iterable[_T], selectors: Iterable[Any]) -> Self: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> _T: - """ - Implement next(self). - """ + """Implement next(self).""" class dropwhile(Generic[_T]): - """ - Drop items from the iterable while predicate(item) is true. + """Drop items from the iterable while predicate(item) is true. Afterwards, return every element until the iterable is exhausted. """ def __new__(cls, predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Self: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> _T: - """ - Implement next(self). - """ + """Implement next(self).""" class filterfalse(Generic[_T]): - """ - Return those items of iterable for which function(item) is false. + """Return those items of iterable for which function(item) is false. If function is None, return the items that are false. """ def __new__(cls, function: _Predicate[_T] | None, iterable: Iterable[_T], /) -> Self: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> _T: - """ - Implement next(self). - """ + """Implement next(self).""" class groupby(Generic[_T_co, _S_co]): - """ - make an iterator that returns consecutive keys and groups from the iterable + """make an iterator that returns consecutive keys and groups from the iterable iterable Elements to divide into groups according to the key function. @@ -250,18 +201,13 @@ class groupby(Generic[_T_co, _S_co]): @overload def __new__(cls, iterable: Iterable[_T1], key: Callable[[_T1], _T2]) -> groupby[_T2, _T1]: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> tuple[_T_co, Iterator[_S_co]]: - """ - Implement next(self). - """ + """Implement next(self).""" class islice(Generic[_T]): - """ - islice(iterable, stop) --> islice object + """islice(iterable, stop) --> islice object islice(iterable, start, stop[, step]) --> islice object Return an iterator whose next() method returns selected values from an @@ -277,55 +223,36 @@ class islice(Generic[_T]): @overload def __new__(cls, iterable: Iterable[_T], start: int | None, stop: int | None, step: int | None = ..., /) -> Self: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> _T: - """ - Implement next(self). - """ + """Implement next(self).""" class starmap(Generic[_T_co]): - """ - Return an iterator whose values are returned from the function evaluated with an argument tuple taken from the given sequence. - """ + """Return an iterator whose values are returned from the function evaluated with an argument tuple taken from the given sequence.""" def __new__(cls, function: Callable[..., _T], iterable: Iterable[Iterable[Any]], /) -> starmap[_T]: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> _T_co: - """ - Implement next(self). - """ + """Implement next(self).""" class takewhile(Generic[_T]): - """ - Return successive entries from an iterable as long as the predicate evaluates to true for each entry. - """ + """Return successive entries from an iterable as long as the predicate evaluates to true for each entry.""" def __new__(cls, predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Self: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> _T: - """ - Implement next(self). - """ + """Implement next(self).""" def tee(iterable: Iterable[_T], n: int = 2, /) -> tuple[Iterator[_T], ...]: - """ - Returns a tuple of n independent iterators. - """ + """Returns a tuple of n independent iterators.""" class zip_longest(Generic[_T_co]): - """ - Return a zip_longest object whose .__next__() method returns a tuple where + """Return a zip_longest object whose .__next__() method returns a tuple where the i-th element comes from the i-th iterable argument. The .__next__() method continues until the longest iterable in the argument sequence is exhausted and then it raises StopIteration. When the shorter iterables @@ -408,18 +335,13 @@ class zip_longest(Generic[_T_co]): fillvalue: _T, ) -> zip_longest[tuple[_T, ...]]: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> _T_co: - """ - Implement next(self). - """ + """Implement next(self).""" class product(Generic[_T_co]): - """ - Cartesian product of input iterables. Equivalent to nested for-loops. + """Cartesian product of input iterables. Equivalent to nested for-loops. For example, product(A, B) returns the same as: ((x,y) for x in A for y in B). The leftmost iterators are in the outermost for-loop, so the output tuples @@ -516,18 +438,13 @@ class product(Generic[_T_co]): @overload def __new__(cls, *iterables: Iterable[_T1], repeat: int = 1) -> product[tuple[_T1, ...]]: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> _T_co: - """ - Implement next(self). - """ + """Implement next(self).""" class permutations(Generic[_T_co]): - """ - Return successive r-length permutations of elements in the iterable. + """Return successive r-length permutations of elements in the iterable. permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1) """ @@ -543,18 +460,13 @@ class permutations(Generic[_T_co]): @overload def __new__(cls, iterable: Iterable[_T], r: int | None = ...) -> permutations[tuple[_T, ...]]: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> _T_co: - """ - Implement next(self). - """ + """Implement next(self).""" class combinations(Generic[_T_co]): - """ - Return successive r-length combinations of elements in the iterable. + """Return successive r-length combinations of elements in the iterable. combinations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3) """ @@ -570,18 +482,13 @@ class combinations(Generic[_T_co]): @overload def __new__(cls, iterable: Iterable[_T], r: int) -> combinations[tuple[_T, ...]]: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> _T_co: - """ - Implement next(self). - """ + """Implement next(self).""" class combinations_with_replacement(Generic[_T_co]): - """ - Return successive r-length combinations of elements in the iterable allowing individual elements to have successive repeats. + """Return successive r-length combinations of elements in the iterable allowing individual elements to have successive repeats. combinations_with_replacement('ABC', 2) --> ('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C') """ @@ -597,38 +504,28 @@ class combinations_with_replacement(Generic[_T_co]): @overload def __new__(cls, iterable: Iterable[_T], r: int) -> combinations_with_replacement[tuple[_T, ...]]: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> _T_co: - """ - Implement next(self). - """ + """Implement next(self).""" if sys.version_info >= (3, 10): class pairwise(Generic[_T_co]): - """ - Return an iterator of overlapping pairs taken from the input iterator. + """Return an iterator of overlapping pairs taken from the input iterator. s -> (s0,s1), (s1,s2), (s2, s3), ... """ def __new__(cls, iterable: Iterable[_T], /) -> pairwise[tuple[_T, _T]]: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> _T_co: - """ - Implement next(self). - """ + """Implement next(self).""" if sys.version_info >= (3, 12): class batched(Generic[_T_co]): - """ - Batch data into tuples of length n. The last batch may be shorter than n. + """Batch data into tuples of length n. The last batch may be shorter than n. Loops over the input iterable and accumulates data into tuples up to size n. The input is consumed lazily, just enough to @@ -652,11 +549,7 @@ if sys.version_info >= (3, 12): def __new__(cls, iterable: Iterable[_T_co], n: int) -> Self: ... def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> tuple[_T_co, ...]: - """ - Implement next(self). - """ + """Implement next(self).""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/json/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/json/__init__.pyi index 06ad14c4b7..fd0fc27da9 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/json/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/json/__init__.pyi @@ -120,8 +120,7 @@ def dumps( sort_keys: bool = False, **kwds: Any, ) -> str: - """ - Serialize ``obj`` to a JSON formatted ``str``. + """Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is true then ``dict`` keys that are not basic types (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped @@ -176,8 +175,7 @@ def dump( sort_keys: bool = False, **kwds: Any, ) -> None: - """ - Serialize ``obj`` as a JSON formatted stream to ``fp`` (a + """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a ``.write()``-supporting file-like object). If ``skipkeys`` is true then ``dict`` keys that are not basic types @@ -229,8 +227,7 @@ def loads( object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, **kwds: Any, ) -> Any: - """ - Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance + """Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance containing a JSON document) to a Python object. ``object_hook`` is an optional function that will be called with the @@ -274,8 +271,7 @@ def load( object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, **kwds: Any, ) -> Any: - """ - Deserialize ``fp`` (a ``.read()``-supporting file-like object containing + """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. ``object_hook`` is an optional function that will be called with the diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/json/decoder.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/json/decoder.pyi index cc98ed4e1b..e1f898f2d7 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/json/decoder.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/json/decoder.pyi @@ -8,8 +8,7 @@ from typing import Any __all__ = ["JSONDecoder", "JSONDecodeError"] class JSONDecodeError(ValueError): - """ - Subclass of ValueError with the following additional properties: + """Subclass of ValueError with the following additional properties: msg: The unformatted error message doc: The JSON document being parsed @@ -26,8 +25,7 @@ class JSONDecodeError(ValueError): def __init__(self, msg: str, doc: str, pos: int) -> None: ... class JSONDecoder: - """ - Simple JSON decoder + """Simple JSON decoder Performs the following translations in decoding by default: @@ -71,8 +69,7 @@ class JSONDecoder: strict: bool = True, object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = None, ) -> None: - """ - ``object_hook``, if specified, will be called with the result + """``object_hook``, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given ``dict``. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). @@ -106,14 +103,12 @@ class JSONDecoder: """ def decode(self, s: str, _w: Callable[..., Any] = ...) -> Any: # _w is undocumented - """ - Return the Python representation of ``s`` (a ``str`` instance + """Return the Python representation of ``s`` (a ``str`` instance containing a JSON document). """ def raw_decode(self, s: str, idx: int = 0) -> tuple[Any, int]: - """ - Decode a JSON document from ``s`` (a ``str`` beginning with + """Decode a JSON document from ``s`` (a ``str`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/json/encoder.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/json/encoder.pyi index 118b7ce59d..7652045282 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/json/encoder.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/json/encoder.pyi @@ -13,32 +13,25 @@ ESCAPE_DCT: Final[dict[str, str]] # undocumented INFINITY: Final[float] # undocumented def py_encode_basestring(s: str) -> str: # undocumented - """ - Return a JSON representation of a Python string - """ + """Return a JSON representation of a Python string""" def py_encode_basestring_ascii(s: str) -> str: # undocumented - """ - Return an ASCII-only JSON representation of a Python string - """ + """Return an ASCII-only JSON representation of a Python string""" def encode_basestring(s: str, /) -> str: # undocumented - """ - encode_basestring(string) -> string + """encode_basestring(string) -> string Return a JSON representation of a Python string """ def encode_basestring_ascii(s: str, /) -> str: # undocumented - """ - encode_basestring_ascii(string) -> string + """encode_basestring_ascii(string) -> string Return an ASCII-only JSON representation of a Python string """ class JSONEncoder: - """ - Extensible JSON encoder for Python data structures. + """Extensible JSON encoder for Python data structures. Supports the following objects and types by default: @@ -87,8 +80,7 @@ class JSONEncoder: separators: tuple[str, str] | None = None, default: Callable[..., Any] | None = None, ) -> None: - """ - Constructor for JSONEncoder, with sensible defaults. + """Constructor for JSONEncoder, with sensible defaults. If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float, bool or None. @@ -128,8 +120,7 @@ class JSONEncoder: """ def default(self, o: Any) -> Any: - """ - Implement this method in a subclass such that it returns + """Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). @@ -148,8 +139,7 @@ class JSONEncoder: """ def encode(self, o: Any) -> str: - """ - Return a JSON string representation of a Python data structure. + """Return a JSON string representation of a Python data structure. >>> from json.encoder import JSONEncoder >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) @@ -157,8 +147,7 @@ class JSONEncoder: """ def iterencode(self, o: Any, _one_shot: bool = False) -> Iterator[str]: - """ - Encode the given object and yield each string + """Encode the given object and yield each string representation as available. For example:: diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/keyword.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/keyword.pyi index c90a38ef29..4e0f3023dd 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/keyword.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/keyword.pyi @@ -17,18 +17,14 @@ from typing import Final __all__ = ["iskeyword", "issoftkeyword", "kwlist", "softkwlist"] def iskeyword(s: str, /) -> bool: - """ - x.__contains__(y) <==> y in x. - """ + """x.__contains__(y) <==> y in x.""" # a list at runtime, but you're not meant to mutate it; # type it as a sequence kwlist: Final[Sequence[str]] def issoftkeyword(s: str, /) -> bool: - """ - x.__contains__(y) <==> y in x. - """ + """x.__contains__(y) <==> y in x.""" # a list at runtime, but you're not meant to mutate it; # type it as a sequence diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/btm_matcher.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/btm_matcher.pyi index b34af26301..1c7797dd51 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/btm_matcher.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/btm_matcher.pyi @@ -15,9 +15,7 @@ from .fixer_base import BaseFix from .pytree import Leaf, Node class BMNode: - """ - Class for a node of the Aho-Corasick automaton used in matching - """ + """Class for a node of the Aho-Corasick automaton used in matching""" count: Incomplete transition_table: Incomplete @@ -27,8 +25,7 @@ class BMNode: def __init__(self) -> None: ... class BottomMatcher: - """ - The main matcher class. After instantiating the patterns should + """The main matcher class. After instantiating the patterns should be added using the add_fixer method """ @@ -39,21 +36,17 @@ class BottomMatcher: logger: Incomplete def __init__(self) -> None: ... def add_fixer(self, fixer: BaseFix) -> None: - """ - Reduces a fixer's pattern tree to a linear path and adds it + """Reduces a fixer's pattern tree to a linear path and adds it to the matcher(a common Aho-Corasick automaton). The fixer is appended on the matching states and called when they are reached """ def add(self, pattern: SupportsGetItem[int | slice, Incomplete] | None, start: BMNode) -> list[BMNode]: - """ - Recursively adds a linear pattern to the AC automaton - """ + """Recursively adds a linear pattern to the AC automaton""" def run(self, leaves: Iterable[Leaf]) -> defaultdict[BaseFix, list[Node | Leaf]]: - """ - The main interface with the bottom matcher. The tree is + """The main interface with the bottom matcher. The tree is traversed from the bottom using the constructed automaton. Nodes are only checked once as the tree is retraversed. When the automaton fails, we give it one more @@ -70,8 +63,6 @@ class BottomMatcher: """ def print_ac(self) -> None: - """ - Prints a graphviz diagram of the BM automaton(for debugging) - """ + """Prints a graphviz diagram of the BM automaton(for debugging)""" def type_repr(type_num: int) -> str | int: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixer_base.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixer_base.pyi index 7acbfd017a..361b55eb08 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixer_base.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixer_base.pyi @@ -12,8 +12,7 @@ from .pytree import Base, Leaf, Node _N = TypeVar("_N", bound=Base) class BaseFix: - """ - Optional base class for fixers. + """Optional base class for fixers. The subclass name must be FixFooBar where FooBar is the result of removing underscores and capitalizing the words of the fix name. @@ -36,8 +35,7 @@ class BaseFix: syms: Incomplete log: Incomplete def __init__(self, options: MutableMapping[str, Incomplete], log: list[str]) -> None: - """ - Initializer. Subclass may override. + """Initializer. Subclass may override. Args: options: a dict containing the options passed to RefactoringTool @@ -46,23 +44,20 @@ class BaseFix: """ def compile_pattern(self) -> None: - """ - Compiles self.PATTERN into self.pattern. + """Compiles self.PATTERN into self.pattern. Subclass may override if it doesn't want to use self.{pattern,PATTERN} in .match(). """ def set_filename(self, filename: StrPath) -> None: - """ - Set the filename. + """Set the filename. The main refactoring tool should call this. """ def match(self, node: _N) -> Literal[False] | dict[str, _N]: - """ - Returns match for a given parse tree node. + """Returns match for a given parse tree node. Should return a true or false object (not necessarily a bool). It may return a non-empty dict of matching sub-nodes as @@ -73,8 +68,7 @@ class BaseFix: @abstractmethod def transform(self, node: Base, results: dict[str, Base]) -> Node | Leaf | None: - """ - Returns the transformation for a given parse tree node. + """Returns the transformation for a given parse tree node. Args: node: the root of the parse tree that matched the fixer. @@ -89,16 +83,14 @@ class BaseFix: """ def new_name(self, template: str = "xxx_todo_changeme") -> str: - """ - Return a string suitable for use as an identifier + """Return a string suitable for use as an identifier The new name is guaranteed not to conflict with other identifiers. """ first_log: bool def log_message(self, message: str) -> None: ... def cannot_convert(self, node: Base, reason: str | None = None) -> None: - """ - Warn the user that a given chunk of code is not valid Python 3, + """Warn the user that a given chunk of code is not valid Python 3, but that it cannot be converted automatically. First argument is the top-level node for the code in question. @@ -106,8 +98,7 @@ class BaseFix: """ def warning(self, node: Base, reason: str) -> None: - """ - Used for warning the user about possible uncertainty in the + """Used for warning the user about possible uncertainty in the translation. First argument is the top-level node for the code in question. @@ -115,8 +106,7 @@ class BaseFix: """ def start_tree(self, tree: Node, filename: StrPath) -> None: - """ - Some fixers need to maintain tree-wide state. + """Some fixers need to maintain tree-wide state. This method is called once, at the start of tree fix-up. tree - the root node of the tree to be processed. @@ -124,8 +114,7 @@ class BaseFix: """ def finish_tree(self, tree: Node, filename: StrPath) -> None: - """ - Some fixers need to maintain tree-wide state. + """Some fixers need to maintain tree-wide state. This method is called once, at the conclusion of tree fix-up. tree - the root node of the tree to be processed. @@ -133,9 +122,7 @@ class BaseFix: """ class ConditionalFix(BaseFix, metaclass=ABCMeta): - """ - Base class for fixers which not execute if an import is found. - """ + """Base class for fixers which not execute if an import is found.""" skip_on: ClassVar[str | None] def start_tree(self, tree: Node, filename: StrPath, /) -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_exitfunc.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_exitfunc.pyi index b0cd78d8fe..6403ada4ac 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_exitfunc.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_exitfunc.pyi @@ -1,4 +1,5 @@ """ + Convert use of sys.exitfunc to use the atexit module. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_getcwdu.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_getcwdu.pyi index fb20d47718..d575746fe2 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_getcwdu.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_getcwdu.pyi @@ -1,4 +1,5 @@ """ + Fixer that changes os.getcwdu() to os.getcwd(). """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_import.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_import.pyi index 230bcfd8f4..d3779413fd 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_import.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_import.pyi @@ -19,9 +19,7 @@ from .. import fixer_base from ..pytree import Node def traverse_imports(names) -> Generator[str, None, None]: - """ - Walks over all the names imported in a dotted_as_names node. - """ + """Walks over all the names imported in a dotted_as_names node.""" class FixImport(fixer_base.BaseFix): BM_compatible: ClassVar[Literal[True]] diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_itertools.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_itertools.pyi index a409e444d0..bfdcfe13b8 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_itertools.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_itertools.pyi @@ -1,11 +1,11 @@ """ Fixer for itertools.(imap|ifilter|izip) --> (map|filter|zip) and - itertools.ifilterfalse --> itertools.filterfalse (bugs 2360-2363) + itertools.ifilterfalse --> itertools.filterfalse (bugs 2360-2363) - imports from itertools are fixed in fix_itertools_import.py + imports from itertools are fixed in fix_itertools_import.py - If itertools is imported as something else (ie: import itertools as it; - it.izip(spam, eggs)) method calls will not get fixed. + If itertools is imported as something else (ie: import itertools as it; + it.izip(spam, eggs)) method calls will not get fixed. """ from typing import ClassVar, Literal diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_metaclass.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_metaclass.pyi index 7a793702c7..24aab4a020 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_metaclass.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_metaclass.pyi @@ -23,22 +23,19 @@ from .. import fixer_base from ..pytree import Base def has_metaclass(parent): - """ - we have to check the cls_node without changing it. + """we have to check the cls_node without changing it. There are two possibilities: 1) clsdef => suite => simple_stmt => expr_stmt => Leaf('__meta') 2) clsdef => simple_stmt => expr_stmt => Leaf('__meta') """ def fixup_parse_tree(cls_node) -> None: - """ - one-line classes don't get a suite in the parse tree so we add + """one-line classes don't get a suite in the parse tree so we add one to normalize the tree """ def fixup_simple_stmt(parent, i, stmt_node) -> None: - """ - if there is a semi-colon all the parts count as part of the same + """if there is a semi-colon all the parts count as part of the same simple_stmt. We just want the __metaclass__ part so we move everything after the semi-colon into its own simple_stmt node """ @@ -46,8 +43,7 @@ def fixup_simple_stmt(parent, i, stmt_node) -> None: def remove_trailing_newline(node) -> None: ... def find_metas(cls_node) -> Generator[tuple[Base, int, Base], None, None]: ... def fixup_indent(suite) -> None: - """ - If an INDENT is followed by a thing with a prefix then nuke the prefix + """If an INDENT is followed by a thing with a prefix then nuke the prefix Otherwise we get in trouble when removing __metaclass__ at suite start """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_set_literal.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_set_literal.pyi index eb550907de..abe1b5b534 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_set_literal.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_set_literal.pyi @@ -1,4 +1,5 @@ """ + Optional fixer to transform set() calls to set literals. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_urllib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_urllib.pyi index b5a8f14d27..f789cd3c8f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_urllib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_urllib.pyi @@ -16,22 +16,18 @@ def build_pattern() -> Generator[str, None, None]: ... class FixUrllib(FixImports): def build_pattern(self): ... def transform_import(self, node, results) -> None: - """ - Transform for the basic import case. Replaces the old + """Transform for the basic import case. Replaces the old import name with a comma separated list of its replacements. """ def transform_member(self, node, results): - """ - Transform for imports of specific module elements. Replaces + """Transform for imports of specific module elements. Replaces the module to be imported from with the appropriate new module. """ def transform_dot(self, node, results) -> None: - """ - Transform for calls to module members in code. - """ + """Transform for calls to module members in code.""" def transform(self, node, results) -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_zip.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_zip.pyi index 06a30dd1be..aae26e74c5 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_zip.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/fixes/fix_zip.pyi @@ -1,4 +1,5 @@ """ + Fixer that changes zip(seq0, seq1, ...) into list(zip(seq0, seq1, ...) unless there exists a 'from future_builtins import zip' statement in the top-level namespace. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/main.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/main.pyi index 2f5830285e..85e700e854 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/main.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/main.pyi @@ -1,4 +1,5 @@ """ + Main program for 2to3. """ @@ -10,13 +11,10 @@ from typing import AnyStr, Literal from . import refactor as refactor def diff_texts(a: str, b: str, filename: str) -> Iterator[str]: - """ - Return a unified diff of two strings. - """ + """Return a unified diff of two strings.""" class StdoutRefactoringTool(refactor.MultiprocessRefactoringTool): - """ - A refactoring tool that can avoid overwriting its input files. + """A refactoring tool that can avoid overwriting its input files. Prints output to stdout. Output files can optionally be written to a different directory and or @@ -37,23 +35,22 @@ class StdoutRefactoringTool(refactor.MultiprocessRefactoringTool): output_dir: str = "", append_suffix: str = "", ) -> None: - """ - Args: - fixers: A list of fixers to import. - options: A dict with RefactoringTool configuration. - explicit: A list of fixers to run even if they are explicit. - nobackups: If true no backup '.bak' files will be created for those - files that are being refactored. - show_diffs: Should diffs of the refactoring be printed to stdout? - input_base_dir: The base directory for all input files. This class - will strip this path prefix off of filenames before substituting - it with output_dir. Only meaningful if output_dir is supplied. - All files processed by refactor() must start with this path. - output_dir: If supplied, all converted files will be written into - this directory tree instead of input_base_dir. - append_suffix: If supplied, all files output by this tool will have - this appended to their filename. Useful for changing .py to - .py3 for example by passing append_suffix='3'. + """Args: + fixers: A list of fixers to import. + options: A dict with RefactoringTool configuration. + explicit: A list of fixers to run even if they are explicit. + nobackups: If true no backup '.bak' files will be created for those + files that are being refactored. + show_diffs: Should diffs of the refactoring be printed to stdout? + input_base_dir: The base directory for all input files. This class + will strip this path prefix off of filenames before substituting + it with output_dir. Only meaningful if output_dir is supplied. + All files processed by refactor() must start with this path. + output_dir: If supplied, all converted files will be written into + this directory tree instead of input_base_dir. + append_suffix: If supplied, all files output by this tool will have + this appended to their filename. Useful for changing .py to + .py3 for example by passing append_suffix='3'. """ # Same as super.log_error and Logger.error def log_error( # type: ignore[override] @@ -74,8 +71,7 @@ class StdoutRefactoringTool(refactor.MultiprocessRefactoringTool): def warn(msg: object) -> None: ... def main(fixer_pkg: str, args: Sequence[AnyStr] | None = None) -> Literal[0, 1, 2]: - """ - Main program. + """Main program. Args: fixer_pkg: the name of a package where the fixers are located. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pgen2/driver.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pgen2/driver.pyi index 5b88db2d6b..c5dbc14feb 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pgen2/driver.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pgen2/driver.pyi @@ -21,33 +21,21 @@ class Driver: convert: _Convert def __init__(self, grammar: Grammar, convert: _Convert | None = None, logger: Logger | None = None) -> None: ... def parse_tokens(self, tokens: Iterable[tuple[int, str, tuple[int, int], tuple[int, int], str]], debug: bool = False) -> _NL: - """ - Parse a series of tokens and return the syntax tree. - """ + """Parse a series of tokens and return the syntax tree.""" def parse_stream_raw(self, stream: IO[str], debug: bool = False) -> _NL: - """ - Parse a stream and return the syntax tree. - """ + """Parse a stream and return the syntax tree.""" def parse_stream(self, stream: IO[str], debug: bool = False) -> _NL: - """ - Parse a stream and return the syntax tree. - """ + """Parse a stream and return the syntax tree.""" def parse_file(self, filename: StrPath, encoding: str | None = None, debug: bool = False) -> _NL: - """ - Parse a file and return the syntax tree. - """ + """Parse a file and return the syntax tree.""" def parse_string(self, text: str, debug: bool = False) -> _NL: - """ - Parse a string and return the syntax tree. - """ + """Parse a string and return the syntax tree.""" def load_grammar( gt: str = "Grammar.txt", gp: str | None = None, save: bool = True, force: bool = False, logger: Logger | None = None ) -> Grammar: - """ - Load the grammar (maybe from a pickle). - """ + """Load the grammar (maybe from a pickle).""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pgen2/grammar.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pgen2/grammar.pyi index 143bb8b70b..dbe2313e1e 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pgen2/grammar.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pgen2/grammar.pyi @@ -17,8 +17,7 @@ _DFA: TypeAlias = list[list[tuple[int, int]]] _DFAS: TypeAlias = tuple[_DFA, dict[int, int]] class Grammar: - """ - Pgen parsing tables conversion class. + """Pgen parsing tables conversion class. Once initialized, this class supplies the grammar tables for the parsing engine implemented by parse.py. The parsing engine @@ -80,24 +79,16 @@ class Grammar: symbol2label: dict[str, int] start: int def dump(self, filename: StrPath) -> None: - """ - Dump the grammar tables to a pickle file. - """ + """Dump the grammar tables to a pickle file.""" def load(self, filename: StrPath) -> None: - """ - Load the grammar tables from a pickle file. - """ + """Load the grammar tables from a pickle file.""" def copy(self) -> Self: - """ - Copy the grammar. - """ + """Copy the grammar.""" def report(self) -> None: - """ - Dump the grammar tables to standard output, for debugging. - """ + """Dump the grammar tables to standard output, for debugging.""" opmap_raw: str opmap: dict[str, str] diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pgen2/parse.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pgen2/parse.pyi index 23c2a9f34e..86c131ec50 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pgen2/parse.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pgen2/parse.pyi @@ -18,9 +18,7 @@ from .grammar import _DFAS, Grammar _Context: TypeAlias = Sequence[Incomplete] class ParseError(Exception): - """ - Exception to signal the parser is stuck. - """ + """Exception to signal the parser is stuck.""" msg: str type: int @@ -29,8 +27,7 @@ class ParseError(Exception): def __init__(self, msg: str, type: int, value: str | None, context: _Context) -> None: ... class Parser: - """ - Parser engine. + """Parser engine. The proper usage sequence is: @@ -64,8 +61,7 @@ class Parser: rootnode: _NL | None used_names: set[str] def __init__(self, grammar: Grammar, convert: _Convert | None = None) -> None: - """ - Constructor. + """Constructor. The grammar argument is a grammar.Grammar instance; see the grammar module for more information. @@ -94,8 +90,7 @@ class Parser: """ def setup(self, start: int | None = None) -> None: - """ - Prepare for parsing. + """Prepare for parsing. This *must* be called before starting to parse. @@ -108,26 +103,16 @@ class Parser: """ def addtoken(self, type: int, value: str | None, context: _Context) -> bool: - """ - Add a token; return True iff this is the end of the program. - """ + """Add a token; return True iff this is the end of the program.""" def classify(self, type: int, value: str | None, context: _Context) -> int: - """ - Turn a token into a label. (Internal) - """ + """Turn a token into a label. (Internal)""" def shift(self, type: int, value: str | None, newstate: int, context: _Context) -> None: - """ - Shift a token. (Internal) - """ + """Shift a token. (Internal)""" def push(self, type: int, newdfa: _DFAS, newstate: int, context: _Context) -> None: - """ - Push a nonterminal. (Internal) - """ + """Push a nonterminal. (Internal)""" def pop(self) -> None: - """ - Pop a nonterminal. (Internal) - """ + """Pop a nonterminal. (Internal)""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi index b6ad48a965..d6447fd872 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi @@ -109,8 +109,7 @@ class TokenError(Exception): ... class StopTokenizing(Exception): ... def tokenize(readline: Callable[[], str], tokeneater: _TokenEater = ...) -> None: - """ - The tokenize() function accepts two parameters: one representing the + """The tokenize() function accepts two parameters: one representing the input stream, and one providing an output mechanism for tokenize(). The first parameter, readline, must be a callable object which provides @@ -131,8 +130,7 @@ class Untokenizer: def compat(self, token: tuple[int, str], iterable: Iterable[_TokenInfo]) -> None: ... def untokenize(iterable: Iterable[_TokenInfo]) -> str: - """ - Transform tokens back into Python source code. + """Transform tokens back into Python source code. Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If @@ -151,8 +149,7 @@ def untokenize(iterable: Iterable[_TokenInfo]) -> str: """ def generate_tokens(readline: Callable[[], str]) -> Iterator[_TokenInfo]: - """ - The generate_tokens() generator requires one argument, readline, which + """The generate_tokens() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. Alternately, readline diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pygram.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pygram.pyi index 48f9c2c509..d0724c2237 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pygram.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pygram.pyi @@ -6,8 +6,7 @@ from .pgen2.grammar import Grammar class Symbols: def __init__(self, grammar: Grammar) -> None: - """ - Initializer. + """Initializer. Creates an attribute for each grammar symbol (nonterminal), whose value is the symbol's type (an int >= 256). diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pytree.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pytree.pyi index b9e9cdda70..1d1482fa25 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pytree.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/pytree.pyi @@ -1,4 +1,5 @@ """ + Python parse tree definitions. This is a very concrete parse tree; we need to keep every token and @@ -26,8 +27,7 @@ HUGE: Final = 0x7FFFFFFF def type_repr(type_num: int) -> str | int: ... class Base: - """ - Abstract base class for Node and Leaf. + """Abstract base class for Node and Leaf. This provides some default functionality and boilerplate using the template pattern. @@ -42,16 +42,14 @@ class Base: was_changed: bool was_checked: bool def __eq__(self, other: object) -> bool: - """ - Compare two nodes for equality. + """Compare two nodes for equality. This calls the method _eq(). """ __hash__: ClassVar[None] # type: ignore[assignment] @abstractmethod def _eq(self, other: Base) -> bool: - """ - Compare two nodes for equality. + """Compare two nodes for equality. This is called by __eq__ and __ne__. It is only called if the two nodes have the same type. This must be implemented by the concrete subclass. @@ -61,71 +59,58 @@ class Base: @abstractmethod def clone(self) -> Self: - """ - Return a cloned (deep) copy of self. + """Return a cloned (deep) copy of self. This must be implemented by the concrete subclass. """ @abstractmethod def post_order(self) -> Iterator[Self]: - """ - Return a post-order iterator for the tree. + """Return a post-order iterator for the tree. This must be implemented by the concrete subclass. """ @abstractmethod def pre_order(self) -> Iterator[Self]: - """ - Return a pre-order iterator for the tree. + """Return a pre-order iterator for the tree. This must be implemented by the concrete subclass. """ def replace(self, new: _NL | list[_NL]) -> None: - """ - Replace this node with a new one in the parent. - """ + """Replace this node with a new one in the parent.""" def get_lineno(self) -> int: - """ - Return the line number which generated the invocant node. - """ + """Return the line number which generated the invocant node.""" def changed(self) -> None: ... def remove(self) -> int | None: - """ - Remove the node from the tree. Returns the position of the node in its + """Remove the node from the tree. Returns the position of the node in its parent's children before it was removed. """ @property def next_sibling(self) -> _NL | None: - """ - The node immediately following the invocant in their parent's children + """The node immediately following the invocant in their parent's children list. If the invocant does not have a next sibling, it is None """ @property def prev_sibling(self) -> _NL | None: - """ - The node immediately preceding the invocant in their parent's children + """The node immediately preceding the invocant in their parent's children list. If the invocant does not have a previous sibling, it is None. """ def leaves(self) -> Iterator[Leaf]: ... def depth(self) -> int: ... def get_suffix(self) -> str: - """ - Return the string immediately following the invocant node. This is + """Return the string immediately following the invocant node. This is effectively equivalent to node.next_sibling.prefix """ class Node(Base): - """ - Concrete implementation for interior nodes. - """ + """Concrete implementation for interior nodes.""" fixers_applied: MutableSequence[BaseFix] | None # Is Unbound until set in refactor.RefactoringTool @@ -140,8 +125,7 @@ class Node(Base): prefix: str | None = None, fixers_applied: MutableSequence[BaseFix] | None = None, ) -> None: - """ - Initializer. + """Initializer. Takes a type constant (a symbol number >= 256), a sequence of child nodes, and an optional context keyword argument. @@ -150,54 +134,40 @@ class Node(Base): """ def _eq(self, other: Base) -> bool: - """ - Compare two nodes for equality. - """ + """Compare two nodes for equality.""" def clone(self) -> Node: - """ - Return a cloned (deep) copy of self. - """ + """Return a cloned (deep) copy of self.""" def post_order(self) -> Iterator[Self]: - """ - Return a post-order iterator for the tree. - """ + """Return a post-order iterator for the tree.""" def pre_order(self) -> Iterator[Self]: - """ - Return a pre-order iterator for the tree. - """ + """Return a pre-order iterator for the tree.""" def set_child(self, i: int, child: _NL) -> None: - """ - Equivalent to 'node.children[i] = child'. This method also sets the + """Equivalent to 'node.children[i] = child'. This method also sets the child's parent attribute appropriately. """ def insert_child(self, i: int, child: _NL) -> None: - """ - Equivalent to 'node.children.insert(i, child)'. This method also sets + """Equivalent to 'node.children.insert(i, child)'. This method also sets the child's parent attribute appropriately. """ def append_child(self, child: _NL) -> None: - """ - Equivalent to 'node.children.append(child)'. This method also sets the + """Equivalent to 'node.children.append(child)'. This method also sets the child's parent attribute appropriately. """ def __unicode__(self) -> str: - """ - Return a pretty string representation. + """Return a pretty string representation. This reproduces the input source exactly. """ class Leaf(Base): - """ - Concrete implementation for leaf nodes. - """ + """Concrete implementation for leaf nodes.""" lineno: int column: int @@ -211,43 +181,32 @@ class Leaf(Base): prefix: str | None = None, fixers_applied: MutableSequence[BaseFix] = [], ) -> None: - """ - Initializer. + """Initializer. Takes a type constant (a token number < 256), a string value, and an optional context keyword argument. """ def _eq(self, other: Base) -> bool: - """ - Compare two nodes for equality. - """ + """Compare two nodes for equality.""" def clone(self) -> Leaf: - """ - Return a cloned (deep) copy of self. - """ + """Return a cloned (deep) copy of self.""" def post_order(self) -> Iterator[Self]: - """ - Return a post-order iterator for the tree. - """ + """Return a post-order iterator for the tree.""" def pre_order(self) -> Iterator[Self]: - """ - Return a pre-order iterator for the tree. - """ + """Return a pre-order iterator for the tree.""" def __unicode__(self) -> str: - """ - Return a pretty string representation. + """Return a pretty string representation. This reproduces the input source exactly. """ def convert(gr: Grammar, raw_node: _RawNode) -> _NL: - """ - Convert raw node information to a Node or Leaf instance. + """Convert raw node information to a Node or Leaf instance. This is passed to the parser driver which calls it whenever a reduction of a grammar rule produces a new complete node, so that the tree is build @@ -255,8 +214,7 @@ def convert(gr: Grammar, raw_node: _RawNode) -> _NL: """ class BasePattern: - """ - A pattern is a tree matching pattern. + """A pattern is a tree matching pattern. It looks for a specific node type (token or symbol), and optionally for a specific content. @@ -273,15 +231,13 @@ class BasePattern: content: str | None name: str | None def optimize(self) -> BasePattern: # sic, subclasses are free to optimize themselves into different patterns - """ - A subclass can define this as a hook for optimizations. + """A subclass can define this as a hook for optimizations. Returns either self or another node with the same effect. """ def match(self, node: _NL, results: _Results | None = None) -> bool: - """ - Does this pattern exactly match a node? + """Does this pattern exactly match a node? Returns True if it matches, False if not. @@ -292,23 +248,20 @@ class BasePattern: """ def match_seq(self, nodes: SupportsLenAndGetItem[_NL], results: _Results | None = None) -> bool: - """ - Does this pattern exactly match a sequence of nodes? + """Does this pattern exactly match a sequence of nodes? Default implementation for non-wildcard patterns. """ def generate_matches(self, nodes: SupportsGetItem[int, _NL]) -> Iterator[tuple[int, _Results]]: - """ - Generator yielding all matches for this pattern. + """Generator yielding all matches for this pattern. Default implementation for non-wildcard patterns. """ class LeafPattern(BasePattern): def __init__(self, type: int | None = None, content: str | None = None, name: str | None = None) -> None: - """ - Initializer. Takes optional type, content, and name. + """Initializer. Takes optional type, content, and name. The type, if given must be a token type (< 256). If not given, this matches any *leaf* node; the content may still be required. @@ -322,8 +275,7 @@ class LeafPattern(BasePattern): class NodePattern(BasePattern): wildcards: bool def __init__(self, type: int | None = None, content: str | None = None, name: str | None = None) -> None: - """ - Initializer. Takes optional type, content, and name. + """Initializer. Takes optional type, content, and name. The type, if given, must be a symbol type (>= 256). If the type is None this matches *any* single node (leaf or not), @@ -339,8 +291,7 @@ class NodePattern(BasePattern): """ class WildcardPattern(BasePattern): - """ - A wildcard pattern can match zero or more nodes. + """A wildcard pattern can match zero or more nodes. This has all the flexibility needed to implement patterns like: @@ -354,8 +305,7 @@ class WildcardPattern(BasePattern): min: int max: int def __init__(self, content: str | None = None, min: int = 0, max: int = 0x7FFFFFFF, name: str | None = None) -> None: - """ - Initializer. + """Initializer. Args: content: optional sequence of subsequences of patterns; @@ -379,8 +329,7 @@ class WildcardPattern(BasePattern): class NegatedPattern(BasePattern): def __init__(self, content: str | None = None) -> None: - """ - Initializer. + """Initializer. The argument is either a pattern or None. If it is None, this only matches an empty sequence (effectively '$' in regex @@ -391,8 +340,7 @@ class NegatedPattern(BasePattern): def generate_matches( patterns: SupportsGetItem[int | slice, BasePattern] | None, nodes: SupportsGetItem[int | slice, _NL] ) -> Iterator[tuple[int, _Results]]: - """ - Generator yielding matches for a sequence of patterns and nodes. + """Generator yielding matches for a sequence of patterns and nodes. Args: patterns: a sequence of patterns diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/refactor.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/refactor.pyi index d2bae62ff8..8fc075912f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/refactor.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lib2to3/refactor.pyi @@ -20,19 +20,13 @@ from .pgen2.grammar import Grammar from .pytree import Node def get_all_fix_names(fixer_pkg: str, remove_prefix: bool = True) -> list[str]: - """ - Return a sorted list of all available fix names in the given package. - """ + """Return a sorted list of all available fix names in the given package.""" def get_fixers_from_package(pkg_name: str) -> list[str]: - """ - Return the fully qualified names for fixers in the package pkg_name. - """ + """Return the fully qualified names for fixers in the package pkg_name.""" class FixerError(Exception): - """ - A fixer could not be loaded. - """ + """A fixer could not be loaded.""" class RefactoringTool: CLASS_PREFIX: ClassVar[str] @@ -56,8 +50,7 @@ class RefactoringTool: def __init__( self, fixer_names: Iterable[str], options: Mapping[str, object] | None = None, explicit: Container[str] | None = None ) -> None: - """ - Initializer. + """Initializer. Args: fixer_names: a list of fixers to import @@ -66,8 +59,7 @@ class RefactoringTool: """ def get_fixers(self) -> tuple[list[BaseFix], list[BaseFix]]: - """ - Inspects the options to load the requested patterns and handlers. + """Inspects the options to load the requested patterns and handlers. Returns: (pre_order, post_order), where pre_order is the list of fixers that @@ -76,15 +68,11 @@ class RefactoringTool: """ def log_error(self, msg: str, *args: Iterable[str], **kwargs: _ExcInfoType) -> NoReturn: - """ - Called when an error occurs. - """ + """Called when an error occurs.""" @overload def log_message(self, msg: object) -> None: - """ - Hook to log a message. - """ + """Hook to log a message.""" @overload def log_message(self, msg: str, *args: object) -> None: ... @@ -93,19 +81,15 @@ class RefactoringTool: @overload def log_debug(self, msg: str, *args: object) -> None: ... def print_output(self, old_text: str, new_text: str, filename: StrPath, equal: bool) -> None: - """ - Called with the old version, new version, and filename of a + """Called with the old version, new version, and filename of a refactored file. """ def refactor(self, items: Iterable[str], write: bool = False, doctests_only: bool = False) -> None: - """ - Refactor a list of files and directories. - """ + """Refactor a list of files and directories.""" def refactor_dir(self, dir_name: str, write: bool = False, doctests_only: bool = False) -> None: - """ - Descends down a directory and refactor every Python file found. + """Descends down a directory and refactor every Python file found. Python files are assumed to have a .py extension. @@ -113,18 +97,13 @@ class RefactoringTool: """ def _read_python_source(self, filename: FileDescriptorOrPath) -> tuple[str, str]: - """ - Do our best to decode a Python source file correctly. - """ + """Do our best to decode a Python source file correctly.""" def refactor_file(self, filename: StrPath, write: bool = False, doctests_only: bool = False) -> None: - """ - Refactors a file. - """ + """Refactors a file.""" def refactor_string(self, data: str, name: str) -> Node | None: - """ - Refactor a given input string. + """Refactor a given input string. Args: data: a string holding the code to be refactored. @@ -137,8 +116,7 @@ class RefactoringTool: def refactor_stdin(self, doctests_only: bool = False) -> None: ... def refactor_tree(self, tree: Node, name: str) -> bool: - """ - Refactors a parse tree (modifying the tree in place). + """Refactors a parse tree (modifying the tree in place). For compatible patterns the bottom matcher module is used. Otherwise the tree is traversed node-to-node for @@ -154,8 +132,7 @@ class RefactoringTool: """ def traverse_by(self, fixers: SupportsGetItem[int, Iterable[BaseFix]] | None, traversal: Iterable[Node]) -> None: - """ - Traverse an AST, applying a set of fixers to each node. + """Traverse an AST, applying a set of fixers to each node. This is a helper method for refactor_tree(). @@ -170,13 +147,10 @@ class RefactoringTool: def processed_file( self, new_text: str, filename: StrPath, old_text: str | None = None, write: bool = False, encoding: str | None = None ) -> None: - """ - Called when a file has been refactored and there may be changes. - """ + """Called when a file has been refactored and there may be changes.""" def write_file(self, new_text: str, filename: FileDescriptorOrPath, old_text: str, encoding: str | None = None) -> None: - """ - Writes a string to a file. + """Writes a string to a file. It first shows a unified diff between the old text and the new text, and then rewrites the file; the latter is only done if the write option is @@ -185,8 +159,7 @@ class RefactoringTool: PS1: Final = ">>> " PS2: Final = "... " def refactor_docstring(self, input: str, filename: StrPath) -> str: - """ - Refactors a docstring, looking for doctests. + """Refactors a docstring, looking for doctests. This returns a modified version of the input string. It looks for doctests, which start with a ">>>" prompt, and may be @@ -199,8 +172,7 @@ class RefactoringTool: """ def refactor_doctest(self, block: list[str], lineno: int, indent: int, filename: StrPath) -> list[str]: - """ - Refactors one doctest. + """Refactors one doctest. A doctest is given as a block of lines, the first of which starts with ">>>" (possibly indented), while the remaining lines start @@ -209,8 +181,7 @@ class RefactoringTool: def summarize(self) -> None: ... def parse_block(self, block: Iterable[str], lineno: int, indent: int) -> Node: - """ - Parses a block into a tree. + """Parses a block into a tree. This is necessary to get correct line number / offset information in the parser diagnostics and embedded into the parse tree. @@ -219,13 +190,10 @@ class RefactoringTool: def wrap_toks( self, block: Iterable[str], lineno: int, indent: int ) -> Generator[tuple[int, str, tuple[int, int], tuple[int, int], str], None, None]: - """ - Wraps a tokenize stream to systematically modify start/end. - """ + """Wraps a tokenize stream to systematically modify start/end.""" def gen_lines(self, block: Iterable[str], indent: int) -> Generator[str, None, None]: - """ - Generates lines as expected by tokenize from a list of lines. + """Generates lines as expected by tokenize from a list of lines. This strips the first len(indent + self.PS1) characters off each line. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/linecache.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/linecache.pyi index 504f28e399..e8790e1eab 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/linecache.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/linecache.pyi @@ -20,38 +20,31 @@ _SourceLoader: TypeAlias = tuple[Callable[[], str | None]] cache: dict[str, _SourceLoader | _ModuleMetadata] # undocumented def getline(filename: str, lineno: int, module_globals: _ModuleGlobals | None = None) -> str: - """ - Get a line for a Python source file from the cache. + """Get a line for a Python source file from the cache. Update the cache if it doesn't contain an entry for this file already. """ def clearcache() -> None: - """ - Clear the cache entirely. - """ + """Clear the cache entirely.""" def getlines(filename: str, module_globals: _ModuleGlobals | None = None) -> list[str]: - """ - Get the lines for a Python source file from the cache. + """Get the lines for a Python source file from the cache. Update the cache if it doesn't contain an entry for this file already. """ def checkcache(filename: str | None = None) -> None: - """ - Discard cache entries that are out of date. + """Discard cache entries that are out of date. (This is not checked upon each call!) """ def updatecache(filename: str, module_globals: _ModuleGlobals | None = None) -> list[str]: - """ - Update a cache entry and return its list of lines. + """Update a cache entry and return its list of lines. If something's wrong, print a message, discard the cache entry, and return an empty list. """ def lazycache(filename: str, module_globals: _ModuleGlobals) -> bool: - """ - Seed the cache for filename with module_globals. + """Seed the cache for filename with module_globals. The module loader will be asked for the source only when getlines is called, not immediately. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/locale.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/locale.pyi index 1b56def040..82adc4546b 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/locale.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/locale.pyi @@ -141,8 +141,7 @@ if sys.platform != "win32": class Error(Exception): ... def getdefaultlocale(envvars: tuple[_str, ...] = ("LC_ALL", "LC_CTYPE", "LANG", "LANGUAGE")) -> tuple[_str | None, _str | None]: - """ - Tries to determine the default locale settings and returns + """Tries to determine the default locale settings and returns them as tuple (language code, encoding). According to POSIX, a program which has not called @@ -164,8 +163,7 @@ def getdefaultlocale(envvars: tuple[_str, ...] = ("LC_ALL", "LC_CTYPE", "LANG", """ def getlocale(category: int = ...) -> tuple[_str | None, _str | None]: - """ - Returns the current setting for the given locale category as + """Returns the current setting for the given locale category as tuple (language code, encoding). category may be one of the LC_* value except LC_ALL. It @@ -177,8 +175,7 @@ def getlocale(category: int = ...) -> tuple[_str | None, _str | None]: """ def setlocale(category: int, locale: _str | Iterable[_str | None] | None = None) -> _str: - """ - Set the locale for the given category. The locale can be + """Set the locale for the given category. The locale can be a string, an iterable of two strings (language code and encoding), or None. @@ -189,14 +186,12 @@ def setlocale(category: int, locale: _str | Iterable[_str | None] | None = None) """ def getpreferredencoding(do_setlocale: bool = True) -> _str: - """ - Return the charset that the user is likely using, + """Return the charset that the user is likely using, according to the system configuration. """ def normalize(localename: _str) -> _str: - """ - Returns a normalized locale code for the given locale + """Returns a normalized locale code for the given locale name. The returned locale code is formatted for use with @@ -212,8 +207,7 @@ def normalize(localename: _str) -> _str: if sys.version_info < (3, 13): def resetlocale(category: int = ...) -> None: - """ - Sets the locale for category to the default setting. + """Sets the locale for category to the default setting. The default setting is determined by calling getdefaultlocale(). category defaults to LC_ALL. @@ -221,13 +215,10 @@ if sys.version_info < (3, 13): if sys.version_info < (3, 12): def format(percent: _str, value: float | Decimal, grouping: bool = False, monetary: bool = False, *additional: Any) -> _str: - """ - Deprecated, use format_string instead. - """ + """Deprecated, use format_string instead.""" def format_string(f: _str, val: Any, grouping: bool = False, monetary: bool = False) -> _str: - """ - Formats a string in the same way that the % formatting would use, + """Formats a string in the same way that the % formatting would use, but takes the current locale into account. Grouping is applied if the third parameter is true. @@ -236,30 +227,21 @@ def format_string(f: _str, val: Any, grouping: bool = False, monetary: bool = Fa """ def currency(val: float | Decimal, symbol: bool = True, grouping: bool = False, international: bool = False) -> _str: - """ - Formats val according to the currency settings + """Formats val according to the currency settings in the current locale. """ def delocalize(string: _str) -> _str: - """ - Parses a string as a normalized number according to the locale settings. - """ + """Parses a string as a normalized number according to the locale settings.""" def atof(string: _str, func: Callable[[_str], float] = ...) -> float: - """ - Parses a string as a float according to the locale settings. - """ + """Parses a string as a float according to the locale settings.""" def atoi(string: _str) -> int: - """ - Converts a string to an integer according to the locale settings. - """ + """Converts a string to an integer according to the locale settings.""" def str(val: float) -> _str: - """ - Convert float to string, taking the locale into account. - """ + """Convert float to string, taking the locale into account.""" locale_alias: dict[_str, _str] # undocumented locale_encoding_alias: dict[_str, _str] # undocumented diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/logging/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/logging/__init__.pyi index 278e0fd708..ba20f2dbf0 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/logging/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/logging/__init__.pyi @@ -1,4 +1,5 @@ """ + Logging package for Python. Based on PEP 282 and comments thereto in comp.lang.python. @@ -98,25 +99,19 @@ _levelToName: dict[int, str] _nameToLevel: dict[str, int] class Filterer: - """ - A base class for loggers and handlers which allows them to share + """A base class for loggers and handlers which allows them to share common code. """ filters: list[_FilterType] def addFilter(self, filter: _FilterType) -> None: - """ - Add the specified filter to this handler. - """ + """Add the specified filter to this handler.""" def removeFilter(self, filter: _FilterType) -> None: - """ - Remove the specified filter from this handler. - """ + """Remove the specified filter from this handler.""" if sys.version_info >= (3, 12): def filter(self, record: LogRecord) -> bool | LogRecord: - """ - Determine if a record is loggable by consulting all the filters. + """Determine if a record is loggable by consulting all the filters. The default is to allow the record to be logged; any filter can veto this by returning a false value. @@ -141,8 +136,7 @@ class Filterer: """ else: def filter(self, record: LogRecord) -> bool: - """ - Determine if a record is loggable by consulting all the filters. + """Determine if a record is loggable by consulting all the filters. The default is to allow the record to be logged; any filter can veto this by returning a false value. @@ -167,8 +161,7 @@ class Filterer: """ class Manager: # undocumented - """ - There is [under normal circumstances] just one Manager instance, which + """There is [under normal circumstances] just one Manager instance, which holds the hierarchy of loggers. """ @@ -179,13 +172,10 @@ class Manager: # undocumented loggerClass: type[Logger] | None logRecordFactory: Callable[..., LogRecord] | None def __init__(self, rootnode: RootLogger) -> None: - """ - Initialize the manager with the root node of the logger hierarchy. - """ + """Initialize the manager with the root node of the logger hierarchy.""" def getLogger(self, name: str) -> Logger: - """ - Get a logger with the specified name (channel name), creating it + """Get a logger with the specified name (channel name), creating it if it doesn't yet exist. This name is a dot-separated hierarchical name, such as "a", "a.b", "a.b.c" or similar. @@ -196,19 +186,15 @@ class Manager: # undocumented """ def setLoggerClass(self, klass: type[Logger]) -> None: - """ - Set the class to be used when instantiating a logger with this Manager. - """ + """Set the class to be used when instantiating a logger with this Manager.""" def setLogRecordFactory(self, factory: Callable[..., LogRecord]) -> None: - """ - Set the factory to be used when instantiating a log record with this + """Set the factory to be used when instantiating a log record with this Manager. """ class Logger(Filterer): - """ - Instances of the Logger class represent a single logging channel. A + """Instances of the Logger class represent a single logging channel. A "logging channel" indicates an area of an application. Exactly how an "area" is defined is up to the application developer. Since an application can have any number of areas, logging channels are identified @@ -231,31 +217,23 @@ class Logger(Filterer): root: ClassVar[RootLogger] # undocumented manager: Manager # undocumented def __init__(self, name: str, level: _Level = 0) -> None: - """ - Initialize the logger with a name and an optional level. - """ + """Initialize the logger with a name and an optional level.""" def setLevel(self, level: _Level) -> None: - """ - Set the logging level of this logger. level must be an int or a str. - """ + """Set the logging level of this logger. level must be an int or a str.""" def isEnabledFor(self, level: int) -> bool: - """ - Is this logger enabled for level 'level'? - """ + """Is this logger enabled for level 'level'?""" def getEffectiveLevel(self) -> int: - """ - Get the effective level for this logger. + """Get the effective level for this logger. Loop through this logger and its parents in the logger hierarchy, looking for a non-zero logging level. Return the first one found. """ def getChild(self, suffix: str) -> Self: # see python/typing#980 - """ - Get a logger which is a descendant to this one. + """Get a logger which is a descendant to this one. This is a convenience method, such that @@ -280,8 +258,7 @@ class Logger(Filterer): stacklevel: int = 1, extra: Mapping[str, object] | None = None, ) -> None: - """ - Log 'msg % args' with severity 'DEBUG'. + """Log 'msg % args' with severity 'DEBUG'. To pass exception information, use the keyword argument exc_info with a true value, e.g. @@ -298,8 +275,7 @@ class Logger(Filterer): stacklevel: int = 1, extra: Mapping[str, object] | None = None, ) -> None: - """ - Log 'msg % args' with severity 'INFO'. + """Log 'msg % args' with severity 'INFO'. To pass exception information, use the keyword argument exc_info with a true value, e.g. @@ -316,8 +292,7 @@ class Logger(Filterer): stacklevel: int = 1, extra: Mapping[str, object] | None = None, ) -> None: - """ - Log 'msg % args' with severity 'WARNING'. + """Log 'msg % args' with severity 'WARNING'. To pass exception information, use the keyword argument exc_info with a true value, e.g. @@ -344,8 +319,7 @@ class Logger(Filterer): stacklevel: int = 1, extra: Mapping[str, object] | None = None, ) -> None: - """ - Log 'msg % args' with severity 'ERROR'. + """Log 'msg % args' with severity 'ERROR'. To pass exception information, use the keyword argument exc_info with a true value, e.g. @@ -362,9 +336,7 @@ class Logger(Filterer): stacklevel: int = 1, extra: Mapping[str, object] | None = None, ) -> None: - """ - Convenience method for logging an ERROR with exception information. - """ + """Convenience method for logging an ERROR with exception information.""" def critical( self, @@ -375,8 +347,7 @@ class Logger(Filterer): stacklevel: int = 1, extra: Mapping[str, object] | None = None, ) -> None: - """ - Log 'msg % args' with severity 'CRITICAL'. + """Log 'msg % args' with severity 'CRITICAL'. To pass exception information, use the keyword argument exc_info with a true value, e.g. @@ -394,8 +365,7 @@ class Logger(Filterer): stacklevel: int = 1, extra: Mapping[str, object] | None = None, ) -> None: - """ - Log 'msg % args' with the integer severity 'level'. + """Log 'msg % args' with the integer severity 'level'. To pass exception information, use the keyword argument exc_info with a true value, e.g. @@ -413,30 +383,23 @@ class Logger(Filterer): stack_info: bool = False, stacklevel: int = 1, ) -> None: # undocumented - """ - Low-level logging routine which creates a LogRecord and then calls + """Low-level logging routine which creates a LogRecord and then calls all the handlers of this logger to handle the record. """ fatal = critical def addHandler(self, hdlr: Handler) -> None: - """ - Add the specified handler to this logger. - """ + """Add the specified handler to this logger.""" def removeHandler(self, hdlr: Handler) -> None: - """ - Remove the specified handler from this logger. - """ + """Remove the specified handler from this logger.""" def findCaller(self, stack_info: bool = False, stacklevel: int = 1) -> tuple[str, int, str, str | None]: - """ - Find the stack frame of the caller so that we can note the source + """Find the stack frame of the caller so that we can note the source file name, line number and function name. """ def handle(self, record: LogRecord) -> None: - """ - Call the handlers for the specified record. + """Call the handlers for the specified record. This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied. @@ -455,14 +418,12 @@ class Logger(Filterer): extra: Mapping[str, object] | None = None, sinfo: str | None = None, ) -> LogRecord: - """ - A factory method which can be overridden in subclasses to create + """A factory method which can be overridden in subclasses to create specialized LogRecords. """ def hasHandlers(self) -> bool: - """ - See if this logger has any handlers configured. + """See if this logger has any handlers configured. Loop through all handlers for this logger and its parents in the logger hierarchy. Return True if a handler was found, else False. @@ -472,8 +433,7 @@ class Logger(Filterer): """ def callHandlers(self, record: LogRecord) -> None: # undocumented - """ - Pass a record to all relevant handlers. + """Pass a record to all relevant handlers. Loop through all handlers for this logger and its parents in the logger hierarchy. If no handler was found, output a one-off error @@ -492,8 +452,7 @@ DEBUG: Final = 10 NOTSET: Final = 0 class Handler(Filterer): - """ - Handler instances dispatch logging events to specific destinations. + """Handler instances dispatch logging events to specific destinations. The base handler class. Acts as a placeholder which defines the Handler interface. Handlers can optionally use Formatter instances to format @@ -506,49 +465,36 @@ class Handler(Filterer): lock: threading.Lock | None # undocumented name: str | None # undocumented def __init__(self, level: _Level = 0) -> None: - """ - Initializes the instance - basically setting the formatter to None + """Initializes the instance - basically setting the formatter to None and the filter list to empty. """ def get_name(self) -> str: ... # undocumented def set_name(self, name: str) -> None: ... # undocumented def createLock(self) -> None: - """ - Acquire a thread lock for serializing access to the underlying I/O. - """ + """Acquire a thread lock for serializing access to the underlying I/O.""" def acquire(self) -> None: - """ - Acquire the I/O thread lock. - """ + """Acquire the I/O thread lock.""" def release(self) -> None: - """ - Release the I/O thread lock. - """ + """Release the I/O thread lock.""" def setLevel(self, level: _Level) -> None: - """ - Set the logging level of this handler. level must be an int or a str. - """ + """Set the logging level of this handler. level must be an int or a str.""" def setFormatter(self, fmt: Formatter | None) -> None: - """ - Set the formatter for this handler. - """ + """Set the formatter for this handler.""" def flush(self) -> None: - """ - Ensure all logging output has been flushed. + """Ensure all logging output has been flushed. This version does nothing and is intended to be implemented by subclasses. """ def close(self) -> None: - """ - Tidy up any resources used by the handler. + """Tidy up any resources used by the handler. This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses @@ -557,8 +503,7 @@ class Handler(Filterer): """ def handle(self, record: LogRecord) -> bool: - """ - Conditionally emit the specified logging record. + """Conditionally emit the specified logging record. Emission depends on filters which may have been added to the handler. Wrap the actual emission of the record with acquisition/release of @@ -569,8 +514,7 @@ class Handler(Filterer): """ def handleError(self, record: LogRecord) -> None: - """ - Handle errors which occur during an emit() call. + """Handle errors which occur during an emit() call. This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, @@ -582,16 +526,14 @@ class Handler(Filterer): """ def format(self, record: LogRecord) -> str: - """ - Format the specified record. + """Format the specified record. If a formatter is set, use it. Otherwise, use the default formatter for the module. """ def emit(self, record: LogRecord) -> None: - """ - Do whatever it takes to actually log the specified logging record. + """Do whatever it takes to actually log the specified logging record. This version is intended to be implemented by subclasses and so raises a NotImplementedError. @@ -599,19 +541,15 @@ class Handler(Filterer): if sys.version_info >= (3, 12): def getHandlerByName(name: str) -> Handler | None: - """ - Get a handler with the specified *name*, or None if there isn't one with + """Get a handler with the specified *name*, or None if there isn't one with that name. """ def getHandlerNames() -> frozenset[str]: - """ - Return all known handler names as an immutable set. - """ + """Return all known handler names as an immutable set.""" class Formatter: - """ - Formatter instances are used to convert a LogRecord to text. + """Formatter instances are used to convert a LogRecord to text. Formatters need to know how a LogRecord is constructed. They are responsible for converting a LogRecord to (usually) a string which can @@ -671,8 +609,7 @@ class Formatter: *, defaults: Mapping[str, Any] | None = None, ) -> None: - """ - Initialize the formatter with specified format strings. + """Initialize the formatter with specified format strings. Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with @@ -690,8 +627,7 @@ class Formatter: def __init__( self, fmt: str | None = None, datefmt: str | None = None, style: _FormatStyle = "%", validate: bool = True ) -> None: - """ - Initialize the formatter with specified format strings. + """Initialize the formatter with specified format strings. Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with @@ -707,8 +643,7 @@ class Formatter: """ def format(self, record: LogRecord) -> str: - """ - Format the specified record as text. + """Format the specified record as text. The record's attribute dictionary is used as the operand to a string formatting operation which yields the returned string. @@ -721,8 +656,7 @@ class Formatter: """ def formatTime(self, record: LogRecord, datefmt: str | None = None) -> str: - """ - Return the creation time of the specified LogRecord as formatted text. + """Return the creation time of the specified LogRecord as formatted text. This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden @@ -740,8 +674,7 @@ class Formatter: """ def formatException(self, ei: _SysExcInfoType) -> str: - """ - Format and return the specified exception information as a string. + """Format and return the specified exception information as a string. This default implementation just uses traceback.print_exception() @@ -749,8 +682,7 @@ class Formatter: def formatMessage(self, record: LogRecord) -> str: ... # undocumented def formatStack(self, stack_info: str) -> str: - """ - This method is provided as an extension point for specialized + """This method is provided as an extension point for specialized formatting of stack information. The input data is a string as returned from a call to @@ -761,40 +693,28 @@ class Formatter: """ def usesTime(self) -> bool: # undocumented - """ - Check if the format uses the creation time of the record. - """ + """Check if the format uses the creation time of the record.""" class BufferingFormatter: - """ - A formatter suitable for formatting a number of records. - """ + """A formatter suitable for formatting a number of records.""" linefmt: Formatter def __init__(self, linefmt: Formatter | None = None) -> None: - """ - Optionally specify a formatter which will be used to format each + """Optionally specify a formatter which will be used to format each individual record. """ def formatHeader(self, records: Sequence[LogRecord]) -> str: - """ - Return the header string for the specified records. - """ + """Return the header string for the specified records.""" def formatFooter(self, records: Sequence[LogRecord]) -> str: - """ - Return the footer string for the specified records. - """ + """Return the footer string for the specified records.""" def format(self, records: Sequence[LogRecord]) -> str: - """ - Format the specified records and return the result as a string. - """ + """Format the specified records and return the result as a string.""" class Filter: - """ - Filter instances are used to perform arbitrary filtering of LogRecords. + """Filter instances are used to perform arbitrary filtering of LogRecords. Loggers and Handlers can optionally use Filter instances to filter records as desired. The base filter class only allows events which are @@ -807,8 +727,7 @@ class Filter: name: str # undocumented nlen: int # undocumented def __init__(self, name: str = "") -> None: - """ - Initialize a filter. + """Initialize a filter. Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no @@ -816,24 +735,21 @@ class Filter: """ if sys.version_info >= (3, 12): def filter(self, record: LogRecord) -> bool | LogRecord: - """ - Determine if the specified record is to be logged. + """Determine if the specified record is to be logged. Returns True if the record should be logged, or False otherwise. If deemed appropriate, the record may be modified in-place. """ else: def filter(self, record: LogRecord) -> bool: - """ - Determine if the specified record is to be logged. + """Determine if the specified record is to be logged. Returns True if the record should be logged, or False otherwise. If deemed appropriate, the record may be modified in-place. """ class LogRecord: - """ - A LogRecord instance represents an event being logged. + """A LogRecord instance represents an event being logged. LogRecord instances are created every time something is logged. They contain all the information pertinent to the event being logged. The @@ -884,13 +800,10 @@ class LogRecord: func: str | None = None, sinfo: str | None = None, ) -> None: - """ - Initialize a logging record with interesting information. - """ + """Initialize a logging record with interesting information.""" def getMessage(self) -> str: - """ - Return the message for this LogRecord. + """Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message. @@ -901,8 +814,7 @@ class LogRecord: _L = TypeVar("_L", bound=Logger | LoggerAdapter[Any]) class LoggerAdapter(Generic[_L]): - """ - An adapter for loggers which makes it easier to specify contextual + """An adapter for loggers which makes it easier to specify contextual information in logging output. """ @@ -911,8 +823,7 @@ class LoggerAdapter(Generic[_L]): if sys.version_info >= (3, 13): def __init__(self, logger: _L, extra: Mapping[str, object] | None = None, merge_extra: bool = False) -> None: - """ - Initialize the adapter with a logger and a dict-like object which + """Initialize the adapter with a logger and a dict-like object which provides contextual information. This constructor signature allows easy stacking of LoggerAdapters, if so desired. @@ -933,8 +844,7 @@ class LoggerAdapter(Generic[_L]): """ elif sys.version_info >= (3, 10): def __init__(self, logger: _L, extra: Mapping[str, object] | None = None) -> None: - """ - Initialize the adapter with a logger and a dict-like object which + """Initialize the adapter with a logger and a dict-like object which provides contextual information. This constructor signature allows easy stacking of LoggerAdapters, if so desired. @@ -955,8 +865,7 @@ class LoggerAdapter(Generic[_L]): """ else: def __init__(self, logger: _L, extra: Mapping[str, object]) -> None: - """ - Initialize the adapter with a logger and a dict-like object which + """Initialize the adapter with a logger and a dict-like object which provides contextual information. This constructor signature allows easy stacking of LoggerAdapters, if so desired. @@ -984,8 +893,7 @@ class LoggerAdapter(Generic[_L]): merge_extra: bool def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> tuple[Any, MutableMapping[str, Any]]: - """ - Process the logging message and keyword arguments passed in to + """Process the logging message and keyword arguments passed in to a logging call to insert contextual information. You can either manipulate the message itself, the keyword args or both. Return the message and kwargs modified (or not) to suit your needs. @@ -1004,9 +912,7 @@ class LoggerAdapter(Generic[_L]): extra: Mapping[str, object] | None = None, **kwargs: object, ) -> None: - """ - Delegate a debug call to the underlying logger. - """ + """Delegate a debug call to the underlying logger.""" def info( self, @@ -1018,9 +924,7 @@ class LoggerAdapter(Generic[_L]): extra: Mapping[str, object] | None = None, **kwargs: object, ) -> None: - """ - Delegate an info call to the underlying logger. - """ + """Delegate an info call to the underlying logger.""" def warning( self, @@ -1032,9 +936,7 @@ class LoggerAdapter(Generic[_L]): extra: Mapping[str, object] | None = None, **kwargs: object, ) -> None: - """ - Delegate a warning call to the underlying logger. - """ + """Delegate a warning call to the underlying logger.""" @deprecated("Deprecated; use warning() instead.") def warn( @@ -1057,9 +959,7 @@ class LoggerAdapter(Generic[_L]): extra: Mapping[str, object] | None = None, **kwargs: object, ) -> None: - """ - Delegate an error call to the underlying logger. - """ + """Delegate an error call to the underlying logger.""" def exception( self, @@ -1071,9 +971,7 @@ class LoggerAdapter(Generic[_L]): extra: Mapping[str, object] | None = None, **kwargs: object, ) -> None: - """ - Delegate an exception call to the underlying logger. - """ + """Delegate an exception call to the underlying logger.""" def critical( self, @@ -1085,9 +983,7 @@ class LoggerAdapter(Generic[_L]): extra: Mapping[str, object] | None = None, **kwargs: object, ) -> None: - """ - Delegate a critical call to the underlying logger. - """ + """Delegate a critical call to the underlying logger.""" def log( self, @@ -1100,30 +996,21 @@ class LoggerAdapter(Generic[_L]): extra: Mapping[str, object] | None = None, **kwargs: object, ) -> None: - """ - Delegate a log call to the underlying logger, after adding + """Delegate a log call to the underlying logger, after adding contextual information from this adapter instance. """ def isEnabledFor(self, level: int) -> bool: - """ - Is this logger enabled for level 'level'? - """ + """Is this logger enabled for level 'level'?""" def getEffectiveLevel(self) -> int: - """ - Get the effective level for the underlying logger. - """ + """Get the effective level for the underlying logger.""" def setLevel(self, level: _Level) -> None: - """ - Set the specified level on the underlying logger. - """ + """Set the specified level on the underlying logger.""" def hasHandlers(self) -> bool: - """ - See if the underlying logger has any handlers. - """ + """See if the underlying logger has any handlers.""" if sys.version_info >= (3, 11): def _log( self, @@ -1135,9 +1022,7 @@ class LoggerAdapter(Generic[_L]): extra: Mapping[str, object] | None = None, stack_info: bool = False, ) -> None: # undocumented - """ - Low-level log implementation, proxied to allow nested logger adapters. - """ + """Low-level log implementation, proxied to allow nested logger adapters.""" else: def _log( self, @@ -1148,36 +1033,28 @@ class LoggerAdapter(Generic[_L]): extra: Mapping[str, object] | None = None, stack_info: bool = False, ) -> None: # undocumented - """ - Low-level log implementation, proxied to allow nested logger adapters. - """ + """Low-level log implementation, proxied to allow nested logger adapters.""" @property def name(self) -> str: ... # undocumented if sys.version_info >= (3, 11): def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ def getLogger(name: str | None = None) -> Logger: - """ - Return a logger with the specified name, creating it if necessary. + """Return a logger with the specified name, creating it if necessary. If no name is specified, return the root logger. """ def getLoggerClass() -> type[Logger]: - """ - Return the class to be used when instantiating a logger. - """ + """Return the class to be used when instantiating a logger.""" def getLogRecordFactory() -> Callable[..., LogRecord]: - """ - Return the factory to be used when instantiating a log record. - """ + """Return the factory to be used when instantiating a log record.""" def debug( msg: object, @@ -1187,8 +1064,7 @@ def debug( stacklevel: int = 1, extra: Mapping[str, object] | None = None, ) -> None: - """ - Log a message with severity 'DEBUG' on the root logger. If the logger has + """Log a message with severity 'DEBUG' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ @@ -1201,8 +1077,7 @@ def info( stacklevel: int = 1, extra: Mapping[str, object] | None = None, ) -> None: - """ - Log a message with severity 'INFO' on the root logger. If the logger has + """Log a message with severity 'INFO' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ @@ -1215,8 +1090,7 @@ def warning( stacklevel: int = 1, extra: Mapping[str, object] | None = None, ) -> None: - """ - Log a message with severity 'WARNING' on the root logger. If the logger has + """Log a message with severity 'WARNING' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ @@ -1238,8 +1112,7 @@ def error( stacklevel: int = 1, extra: Mapping[str, object] | None = None, ) -> None: - """ - Log a message with severity 'ERROR' on the root logger. If the logger has + """Log a message with severity 'ERROR' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ @@ -1252,8 +1125,7 @@ def critical( stacklevel: int = 1, extra: Mapping[str, object] | None = None, ) -> None: - """ - Log a message with severity 'CRITICAL' on the root logger. If the logger + """Log a message with severity 'CRITICAL' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ @@ -1266,8 +1138,7 @@ def exception( stacklevel: int = 1, extra: Mapping[str, object] | None = None, ) -> None: - """ - Log a message with severity 'ERROR' on the root logger, with exception + """Log a message with severity 'ERROR' on the root logger, with exception information. If the logger has no handlers, basicConfig() is called to add a console handler with a pre-defined format. """ @@ -1281,8 +1152,7 @@ def log( stacklevel: int = 1, extra: Mapping[str, object] | None = None, ) -> None: - """ - Log 'msg % args' with the integer severity 'level' on the root logger. If + """Log 'msg % args' with the integer severity 'level' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ @@ -1290,21 +1160,17 @@ def log( fatal = critical def disable(level: int = 50) -> None: - """ - Disable all logging calls of severity 'level' and below. - """ + """Disable all logging calls of severity 'level' and below.""" def addLevelName(level: int, levelName: str) -> None: - """ - Associate 'levelName' with 'level'. + """Associate 'levelName' with 'level'. This is used when converting levels to text during message formatting. """ @overload def getLevelName(level: int) -> str: - """ - Return the textual or numeric representation of logging level 'level'. + """Return the textual or numeric representation of logging level 'level'. If the level is one of the predefined levels (CRITICAL, ERROR, WARNING, INFO, DEBUG) then you get the corresponding string. If you have @@ -1329,8 +1195,7 @@ if sys.version_info >= (3, 11): def getLevelNamesMapping() -> dict[str, int]: ... def makeLogRecord(dict: Mapping[str, object]) -> LogRecord: - """ - Make a LogRecord whose attributes are defined by the specified dictionary, + """Make a LogRecord whose attributes are defined by the specified dictionary, This function is useful for converting a logging event received over a socket connection (which is sent as a dictionary) into a LogRecord instance. @@ -1350,8 +1215,7 @@ def basicConfig( encoding: str | None = ..., errors: str | None = ..., ) -> None: - """ - Do basic configuration for the logging system. + """Do basic configuration for the logging system. This function does nothing if the root logger already has handlers configured, unless the keyword argument *force* is set to ``True``. @@ -1419,30 +1283,26 @@ def basicConfig( """ def shutdown(handlerList: Sequence[Any] = ...) -> None: # handlerList is undocumented - """ - Perform any cleanup actions in the logging system (e.g. flushing + """Perform any cleanup actions in the logging system (e.g. flushing buffers). Should be called at application exit. """ def setLoggerClass(klass: type[Logger]) -> None: - """ - Set the class to be used when instantiating a logger. The class should + """Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__() """ def captureWarnings(capture: bool) -> None: - """ - If capture is true, redirect all warnings to the logging package. + """If capture is true, redirect all warnings to the logging package. If capture is False, ensure that warnings are not redirected to logging but to their original destinations. """ def setLogRecordFactory(factory: Callable[..., LogRecord]) -> None: - """ - Set the factory to be used when instantiating a log record. + """Set the factory to be used when instantiating a log record. :param factory: A callable which will be called to instantiate a log record. @@ -1453,8 +1313,7 @@ lastResort: Handler | None _StreamT = TypeVar("_StreamT", bound=SupportsWrite[str]) class StreamHandler(Handler, Generic[_StreamT]): - """ - A handler class which writes logging records, appropriately formatted, + """A handler class which writes logging records, appropriately formatted, to a stream. Note that this class does not close the stream, as sys.stdout or sys.stderr may be used. """ @@ -1463,8 +1322,7 @@ class StreamHandler(Handler, Generic[_StreamT]): terminator: str @overload def __init__(self: StreamHandler[TextIO], stream: None = None) -> None: - """ - Initialize the handler. + """Initialize the handler. If stream is not specified, sys.stderr is used. """ @@ -1472,8 +1330,7 @@ class StreamHandler(Handler, Generic[_StreamT]): @overload def __init__(self: StreamHandler[_StreamT], stream: _StreamT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 def setStream(self, stream: _StreamT) -> _StreamT | None: - """ - Sets the StreamHandler's stream to the specified value, + """Sets the StreamHandler's stream to the specified value, if it is different. Returns the old stream, if the stream was changed, or None @@ -1481,16 +1338,13 @@ class StreamHandler(Handler, Generic[_StreamT]): """ if sys.version_info >= (3, 11): def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ class FileHandler(StreamHandler[TextIOWrapper]): - """ - A handler class which writes formatted logging records to disk files. - """ + """A handler class which writes formatted logging records to disk files.""" baseFilename: str # undocumented mode: str # undocumented @@ -1500,19 +1354,15 @@ class FileHandler(StreamHandler[TextIOWrapper]): def __init__( self, filename: StrPath, mode: str = "a", encoding: str | None = None, delay: bool = False, errors: str | None = None ) -> None: - """ - Open the specified file and use it as the stream for logging. - """ + """Open the specified file and use it as the stream for logging.""" def _open(self) -> TextIOWrapper: # undocumented - """ - Open the current base file with the (original) mode and encoding. + """Open the current base file with the (original) mode and encoding. Return the resulting stream. """ class NullHandler(Handler): - """ - This handler does nothing. It's intended to be used to avoid the + """This handler does nothing. It's intended to be used to avoid the "No handlers could be found for logger XXX" one-off warning. This is important for library code, which may contain code to log events. If a user of the library does not configure logging, the one-off warning might be @@ -1522,36 +1372,28 @@ class NullHandler(Handler): """ class PlaceHolder: # undocumented - """ - PlaceHolder instances are used in the Manager logger hierarchy to take + """PlaceHolder instances are used in the Manager logger hierarchy to take the place of nodes for which no loggers have been defined. This class is intended for internal use only and not as part of the public API. """ loggerMap: dict[Logger, None] def __init__(self, alogger: Logger) -> None: - """ - Initialize with the specified logger being a child of this placeholder. - """ + """Initialize with the specified logger being a child of this placeholder.""" def append(self, alogger: Logger) -> None: - """ - Add the specified logger as a child of this placeholder. - """ + """Add the specified logger as a child of this placeholder.""" # Below aren't in module docs but still visible class RootLogger(Logger): - """ - A root logger is not that different to any other logger, except that + """A root logger is not that different to any other logger, except that it must have a logging level and there is only one instance of it in the hierarchy. """ def __init__(self, level: int) -> None: - """ - Initialize the logger with the name "root". - """ + """Initialize the logger with the name "root".""" root: RootLogger @@ -1568,9 +1410,7 @@ class PercentStyle: # undocumented def usesTime(self) -> bool: ... def validate(self) -> None: - """ - Validate the input format, ensure it matches the correct style - """ + """Validate the input format, ensure it matches the correct style""" def format(self, record: Any) -> str: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/logging/config.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/logging/config.pyi index 240e8f5775..a077d1de8a 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/logging/config.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/logging/config.pyi @@ -1,4 +1,5 @@ """ + Configuration functions for the logging package for Python. The core package is based on PEP 282 and comments thereto in comp.lang.python, and influenced by Apache's log4j system. @@ -74,9 +75,7 @@ class _DictConfigArgs(TypedDict, total=False): # Also accept a TypedDict type, to allow callers to use TypedDict # types, and for somewhat stricter type checking of dict literals. def dictConfig(config: _DictConfigArgs | dict[str, Any]) -> None: - """ - Configure logging using a dictionary. - """ + """Configure logging using a dictionary.""" if sys.version_info >= (3, 10): def fileConfig( @@ -85,8 +84,7 @@ if sys.version_info >= (3, 10): disable_existing_loggers: bool = True, encoding: str | None = None, ) -> None: - """ - Read the logging configuration from a ConfigParser-format file. + """Read the logging configuration from a ConfigParser-format file. This can be called several times from an application, allowing an end user the ability to select from various pre-canned configurations (if the @@ -100,8 +98,7 @@ else: defaults: Mapping[str, str] | None = None, disable_existing_loggers: bool = True, ) -> None: - """ - Read the logging configuration from a ConfigParser-format file. + """Read the logging configuration from a ConfigParser-format file. This can be called several times from an application, allowing an end user the ability to select from various pre-canned configurations (if the @@ -111,8 +108,7 @@ else: def valid_ident(s: str) -> Literal[True]: ... # undocumented def listen(port: int = 9030, verify: Callable[[bytes], bytes | None] | None = None) -> Thread: - """ - Start up a socket server on the specified port, and listen for new + """Start up a socket server on the specified port, and listen for new configurations. These will be sent as a file suitable for processing by fileConfig(). @@ -131,31 +127,23 @@ def listen(port: int = 9030, verify: Callable[[bytes], bytes | None] | None = No """ def stopListening() -> None: - """ - Stop the listening server which was created with a call to listen(). - """ + """Stop the listening server which was created with a call to listen().""" class ConvertingMixin: # undocumented - """ - For ConvertingXXX's, this mixin class provides common functions - """ + """For ConvertingXXX's, this mixin class provides common functions""" def convert_with_key(self, key: Any, value: Any, replace: bool = True) -> Any: ... def convert(self, value: Any) -> Any: ... class ConvertingDict(dict[Hashable, Any], ConvertingMixin): # undocumented - """ - A converting dictionary wrapper. - """ + """A converting dictionary wrapper.""" def __getitem__(self, key: Hashable) -> Any: ... def get(self, key: Hashable, default: Any = None) -> Any: ... def pop(self, key: Hashable, default: Any = None) -> Any: ... class ConvertingList(list[Any], ConvertingMixin): # undocumented - """ - A converting list wrapper. - """ + """A converting list wrapper.""" @overload def __getitem__(self, key: SupportsIndex) -> Any: ... @@ -164,9 +152,7 @@ class ConvertingList(list[Any], ConvertingMixin): # undocumented def pop(self, idx: SupportsIndex = -1) -> Any: ... class ConvertingTuple(tuple[Any, ...], ConvertingMixin): # undocumented - """ - A converting tuple wrapper. - """ + """A converting tuple wrapper.""" @overload def __getitem__(self, key: SupportsIndex) -> Any: ... @@ -174,9 +160,7 @@ class ConvertingTuple(tuple[Any, ...], ConvertingMixin): # undocumented def __getitem__(self, key: slice) -> Any: ... class BaseConfigurator: # undocumented - """ - The configurator base class which defines some useful defaults. - """ + """The configurator base class which defines some useful defaults.""" CONVERT_PATTERN: Pattern[str] WORD_PATTERN: Pattern[str] @@ -188,89 +172,60 @@ class BaseConfigurator: # undocumented def __init__(self, config: _DictConfigArgs | dict[str, Any]) -> None: ... def resolve(self, s: str) -> Any: - """ - Resolve strings to objects using standard import and attribute + """Resolve strings to objects using standard import and attribute syntax. """ def ext_convert(self, value: str) -> Any: - """ - Default converter for the ext:// protocol. - """ + """Default converter for the ext:// protocol.""" def cfg_convert(self, value: str) -> Any: - """ - Default converter for the cfg:// protocol. - """ + """Default converter for the cfg:// protocol.""" def convert(self, value: Any) -> Any: - """ - Convert values to an appropriate type. dicts, lists and tuples are + """Convert values to an appropriate type. dicts, lists and tuples are replaced by their converting alternatives. Strings are checked to see if they have a conversion format and are converted if they do. """ def configure_custom(self, config: dict[str, Any]) -> Any: - """ - Configure an object with a user-supplied factory. - """ + """Configure an object with a user-supplied factory.""" def as_tuple(self, value: list[Any] | tuple[Any, ...]) -> tuple[Any, ...]: - """ - Utility function which converts lists to tuples. - """ + """Utility function which converts lists to tuples.""" class DictConfigurator(BaseConfigurator): - """ - Configure logging using a dictionary-like object to describe the + """Configure logging using a dictionary-like object to describe the configuration. """ def configure(self) -> None: # undocumented - """ - Do the configuration. - """ + """Do the configuration.""" def configure_formatter(self, config: _FormatterConfiguration) -> Formatter | Any: # undocumented - """ - Configure a formatter from a dictionary. - """ + """Configure a formatter from a dictionary.""" def configure_filter(self, config: _FilterConfiguration) -> Filter | Any: # undocumented - """ - Configure a filter from a dictionary. - """ + """Configure a filter from a dictionary.""" def add_filters(self, filterer: Filterer, filters: Iterable[_FilterType]) -> None: # undocumented - """ - Add filters to a filterer from a list of names. - """ + """Add filters to a filterer from a list of names.""" def configure_handler(self, config: _HandlerConfiguration) -> Handler | Any: # undocumented - """ - Configure a handler from a dictionary. - """ + """Configure a handler from a dictionary.""" def add_handlers(self, logger: Logger, handlers: Iterable[str]) -> None: # undocumented - """ - Add handlers to a logger from a list of names. - """ + """Add handlers to a logger from a list of names.""" def common_logger_config( self, logger: Logger, config: _LoggerConfiguration, incremental: bool = False ) -> None: # undocumented - """ - Perform configuration which is common to root and non-root loggers. - """ + """Perform configuration which is common to root and non-root loggers.""" def configure_logger(self, name: str, config: _LoggerConfiguration, incremental: bool = False) -> None: # undocumented - """ - Configure a non-root logger from a dictionary. - """ + """Configure a non-root logger from a dictionary.""" def configure_root(self, config: _LoggerConfiguration, incremental: bool = False) -> None: # undocumented - """ - Configure a root logger from a dictionary. - """ + """Configure a root logger from a dictionary.""" dictConfigClass = DictConfigurator diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/logging/handlers.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/logging/handlers.pyi index 3f63166da6..27b39c7ac5 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/logging/handlers.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/logging/handlers.pyi @@ -1,4 +1,5 @@ """ + Additional handlers for the logging package for Python. The core package is based on PEP 282 and comments thereto in comp.lang.python. @@ -31,8 +32,7 @@ SYSLOG_UDP_PORT: Final[int] SYSLOG_TCP_PORT: Final[int] class WatchedFileHandler(FileHandler): - """ - A handler for logging to a file, which watches the file + """A handler for logging to a file, which watches the file to see if it has changed while in use. This can happen because of usage of programs such as newsyslog and logrotate which perform log file rotation. This handler, intended for use under Unix, @@ -57,8 +57,7 @@ class WatchedFileHandler(FileHandler): ) -> None: ... def _statstream(self) -> None: ... # undocumented def reopenIfNeeded(self) -> None: - """ - Reopen log file if needed. + """Reopen log file if needed. Checks if the underlying file has changed, and if it has, close the old stream and reopen the file to get the @@ -66,8 +65,7 @@ class WatchedFileHandler(FileHandler): """ class BaseRotatingHandler(FileHandler): - """ - Base class for handlers that rotate log files at a certain point. + """Base class for handlers that rotate log files at a certain point. Not meant to be instantiated directly. Instead, use RotatingFileHandler or TimedRotatingFileHandler. """ @@ -77,13 +75,10 @@ class BaseRotatingHandler(FileHandler): def __init__( self, filename: StrPath, mode: str, encoding: str | None = None, delay: bool = False, errors: str | None = None ) -> None: - """ - Use the specified filename for streamed logging - """ + """Use the specified filename for streamed logging""" def rotation_filename(self, default_name: str) -> str: - """ - Modify the filename of a log file when rotating. + """Modify the filename of a log file when rotating. This is provided so that a custom filename can be provided. @@ -96,8 +91,7 @@ class BaseRotatingHandler(FileHandler): """ def rotate(self, source: str, dest: str) -> None: - """ - When rotating, rotate the current log. + """When rotating, rotate the current log. The default implementation calls the 'rotator' attribute of the handler, if it's callable, passing the source and dest arguments to @@ -111,8 +105,7 @@ class BaseRotatingHandler(FileHandler): """ class RotatingFileHandler(BaseRotatingHandler): - """ - Handler for logging to a set of files, which switches from one file + """Handler for logging to a set of files, which switches from one file to the next when the current file reaches a certain size. """ @@ -128,8 +121,7 @@ class RotatingFileHandler(BaseRotatingHandler): delay: bool = False, errors: str | None = None, ) -> None: - """ - Open the specified file and use it as the stream for logging. + """Open the specified file and use it as the stream for logging. By default, the file grows indefinitely. You can specify particular values of maxBytes and backupCount to allow the file to rollover at @@ -150,21 +142,17 @@ class RotatingFileHandler(BaseRotatingHandler): """ def doRollover(self) -> None: - """ - Do a rollover, as described in __init__(). - """ + """Do a rollover, as described in __init__().""" def shouldRollover(self, record: LogRecord) -> int: # undocumented - """ - Determine if rollover should occur. + """Determine if rollover should occur. Basically, see if the supplied record would cause the file to exceed the size limit we have. """ class TimedRotatingFileHandler(BaseRotatingHandler): - """ - Handler for logging to a file, rotating the log file at certain timed + """Handler for logging to a file, rotating the log file at certain timed intervals. If backupCount is > 0, when rollover is done, no more than backupCount @@ -193,8 +181,7 @@ class TimedRotatingFileHandler(BaseRotatingHandler): errors: str | None = None, ) -> None: ... def doRollover(self) -> None: - """ - do a rollover; in this case, a date/time stamp is appended to the filename + """do a rollover; in this case, a date/time stamp is appended to the filename when the rollover happens. However, you want the file to be named for the start of the interval, not the current time. If there is a backup count, then we have to get a list of matching filenames, sort them and remove @@ -202,28 +189,23 @@ class TimedRotatingFileHandler(BaseRotatingHandler): """ def shouldRollover(self, record: LogRecord) -> int: # undocumented - """ - Determine if rollover should occur. + """Determine if rollover should occur. record is not used, as we are just comparing times, but it is needed so the method signatures are the same """ def computeRollover(self, currentTime: int) -> int: # undocumented - """ - Work out the rollover time based on the specified time. - """ + """Work out the rollover time based on the specified time.""" def getFilesToDelete(self) -> list[str]: # undocumented - """ - Determine the files to delete when rolling over. + """Determine the files to delete when rolling over. More specific than the earlier method, which just used glob.glob(). """ class SocketHandler(Handler): - """ - A handler class which writes logging records, in pickle format, to + """A handler class which writes logging records, in pickle format, to a streaming socket. The socket is kept open across logging calls. If the peer resets it, an attempt is made to reconnect on the next call. The pickle which is sent is that of the LogRecord's attribute dictionary @@ -244,8 +226,7 @@ class SocketHandler(Handler): retryFactor: float # undocumented retryMax: float # undocumented def __init__(self, host: str, port: int | None) -> None: - """ - Initializes the handler with a specific host address and port. + """Initializes the handler with a specific host address and port. When the attribute *closeOnError* is set to True - if a socket error occurs, the socket is silently closed and then reopened on the next @@ -253,35 +234,30 @@ class SocketHandler(Handler): """ def makeSocket(self, timeout: float = 1) -> socket: # timeout is undocumented - """ - A factory method which allows subclasses to define the precise + """A factory method which allows subclasses to define the precise type of socket they want. """ def makePickle(self, record: LogRecord) -> bytes: - """ - Pickles the record in binary format with a length prefix, and + """Pickles the record in binary format with a length prefix, and returns it ready for transmission across the socket. """ def send(self, s: ReadableBuffer) -> None: - """ - Send a pickled string to the socket. + """Send a pickled string to the socket. This function allows for partial sends which can happen when the network is busy. """ def createSocket(self) -> None: - """ - Try to create a socket, using an exponential backoff with + """Try to create a socket, using an exponential backoff with a max retry time. Thanks to Robert Olson for the original patch (SF #815911) which has been slightly refactored. """ class DatagramHandler(SocketHandler): - """ - A handler class which writes logging records, in pickle format, to + """A handler class which writes logging records, in pickle format, to a datagram socket. The pickle which is sent is that of the LogRecord's attribute dictionary (__dict__), so that the receiver does not need to have the logging module installed in order to process the logging event. @@ -291,14 +267,12 @@ class DatagramHandler(SocketHandler): """ def makeSocket(self) -> socket: # type: ignore[override] - """ - The factory method of SocketHandler is here overridden to create + """The factory method of SocketHandler is here overridden to create a UDP socket (SOCK_DGRAM). """ class SysLogHandler(Handler): - """ - A handler class which sends formatted logging records to a syslog + """A handler class which sends formatted logging records to a syslog server. Based on Sam Rushing's syslog module: http://www.nightmare.com/squirl/python-ext/misc/syslog.py Contributed by Nicolas Untz (after which minor refactoring changes @@ -356,8 +330,7 @@ class SysLogHandler(Handler): socktype: SocketKind | None = None, timeout: float | None = None, ) -> None: - """ - Initialize a handler. + """Initialize a handler. If address is specified as a string, a UNIX socket is used. To log to a local syslogd, "SysLogHandler(address="/dev/log")" can be used. @@ -371,8 +344,7 @@ class SysLogHandler(Handler): def __init__( self, address: tuple[str, int] | str = ("localhost", 514), facility: str | int = 1, socktype: SocketKind | None = None ) -> None: - """ - Initialize a handler. + """Initialize a handler. If address is specified as a string, a UNIX socket is used. To log to a local syslogd, "SysLogHandler(address="/dev/log")" can be used. @@ -384,8 +356,7 @@ class SysLogHandler(Handler): """ if sys.version_info >= (3, 11): def createSocket(self) -> None: - """ - Try to create a socket and, if it's not a datagram socket, connect it + """Try to create a socket and, if it's not a datagram socket, connect it to the other end. This method is called during handler initialization, but it's not regarded as an error if the other end isn't listening yet --- the method will be called again when emitting an event, @@ -393,16 +364,14 @@ class SysLogHandler(Handler): """ def encodePriority(self, facility: int | str, priority: int | str) -> int: - """ - Encode the facility and priority. You can pass in strings or + """Encode the facility and priority. You can pass in strings or integers - if strings are passed, the facility_names and priority_names mapping dictionaries are used to convert them to integers. """ def mapPriority(self, levelName: str) -> str: - """ - Map a logging level name to a key in the priority_names map. + """Map a logging level name to a key in the priority_names map. This is useful in two scenarios: when custom levels are being used, and in the case where you can't do a straightforward mapping by lowercasing the logging level name because of locale- @@ -410,8 +379,7 @@ class SysLogHandler(Handler): """ class NTEventLogHandler(Handler): - """ - A handler class which sends events to the NT Event Log. Adds a + """A handler class which sends events to the NT Event Log. Adds a registry entry for the specified application name. If no dllname is provided, win32service.pyd (which contains some basic message placeholders) is used. Note that use of these placeholders will make @@ -422,16 +390,14 @@ class NTEventLogHandler(Handler): def __init__(self, appname: str, dllname: str | None = None, logtype: str = "Application") -> None: ... def getEventCategory(self, record: LogRecord) -> int: - """ - Return the event category for the record. + """Return the event category for the record. Override this if you want to specify your own categories. This version returns 0. """ # TODO: correct return value? def getEventType(self, record: LogRecord) -> int: - """ - Return the event type for the record. + """Return the event type for the record. Override this if you want to specify your own types. This version does a mapping using the handler's typemap attribute, which is set up in @@ -442,8 +408,7 @@ class NTEventLogHandler(Handler): """ def getMessageID(self, record: LogRecord) -> int: - """ - Return the message ID for the event record. If you are using your + """Return the message ID for the event record. If you are using your own messages, you could do this by having the msg passed to the logger being an ID rather than a formatting string. Then, in here, you could use a dictionary lookup to get the message ID. This @@ -451,9 +416,7 @@ class NTEventLogHandler(Handler): """ class SMTPHandler(Handler): - """ - A handler class which sends an SMTP email for each logging event. - """ + """A handler class which sends an SMTP email for each logging event.""" mailhost: str # undocumented mailport: int | None # undocumented @@ -475,8 +438,7 @@ class SMTPHandler(Handler): secure: tuple[()] | tuple[str] | tuple[str, str] | None = None, timeout: float = 5.0, ) -> None: - """ - Initialize the handler. + """Initialize the handler. Initialize the instance with the from and to addresses and subject line of the email. To specify a non-standard SMTP port, use the @@ -494,16 +456,14 @@ class SMTPHandler(Handler): """ def getSubject(self, record: LogRecord) -> str: - """ - Determine the subject for the email. + """Determine the subject for the email. If you want to specify a subject line which is record-dependent, override this method. """ class BufferingHandler(Handler): - """ - A handler class which buffers logging records in memory. Whenever each + """A handler class which buffers logging records in memory. Whenever each record is added to the buffer, a check is made to see if the buffer should be flushed. If it should, then flush() is expected to do what's needed. """ @@ -511,21 +471,17 @@ class BufferingHandler(Handler): capacity: int # undocumented buffer: list[LogRecord] # undocumented def __init__(self, capacity: int) -> None: - """ - Initialize the handler with the buffer size. - """ + """Initialize the handler with the buffer size.""" def shouldFlush(self, record: LogRecord) -> bool: - """ - Should the handler flush its buffer? + """Should the handler flush its buffer? Returns true if the buffer is up to capacity. This method can be overridden to implement custom flushing strategies. """ class MemoryHandler(BufferingHandler): - """ - A handler class which buffers logging records in memory, periodically + """A handler class which buffers logging records in memory, periodically flushing them to a target handler. Flushing occurs whenever the buffer is full, or when an event of a certain severity or greater is seen. """ @@ -534,8 +490,7 @@ class MemoryHandler(BufferingHandler): target: Handler | None # undocumented flushOnClose: bool # undocumented def __init__(self, capacity: int, flushLevel: int = 40, target: Handler | None = None, flushOnClose: bool = True) -> None: - """ - Initialize the handler with the buffer size, the level at which + """Initialize the handler with the buffer size, the level at which flushing should occur and an optional target. Note that without a target being set either here or via setTarget(), @@ -548,13 +503,10 @@ class MemoryHandler(BufferingHandler): """ def setTarget(self, target: Handler | None) -> None: - """ - Set the target handler for this handler. - """ + """Set the target handler for this handler.""" class HTTPHandler(Handler): - """ - A class which sends records to a web server, using either GET or + """A class which sends records to a web server, using either GET or POST semantics. """ @@ -573,21 +525,18 @@ class HTTPHandler(Handler): credentials: tuple[str, str] | None = None, context: ssl.SSLContext | None = None, ) -> None: - """ - Initialize the instance with the host, the request URL, and the method + """Initialize the instance with the host, the request URL, and the method ("GET" or "POST") """ def mapLogRecord(self, record: LogRecord) -> dict[str, Any]: - """ - Default implementation of mapping the log record into a dict + """Default implementation of mapping the log record into a dict that is sent as the CGI data. Overwrite in your class. Contributed by Franz Glasner. """ def getConnection(self, host: str, secure: bool) -> http.client.HTTPConnection: # undocumented - """ - get a HTTP[S]Connection. + """get a HTTP[S]Connection. Override when a custom connection is required, for example if there is a proxy. @@ -598,8 +547,7 @@ class _QueueLike(Protocol[_T]): def put_nowait(self, item: _T, /) -> None: ... class QueueHandler(Handler): - """ - This handler sends events to a queue. Typically, it would be used together + """This handler sends events to a queue. Typically, it would be used together with a multiprocessing Queue to centralise logging to file in one process (in a multi-process application), so as to avoid file write contention between processes. @@ -610,13 +558,10 @@ class QueueHandler(Handler): queue: _QueueLike[Any] def __init__(self, queue: _QueueLike[Any]) -> None: - """ - Initialise an instance, using the passed queue. - """ + """Initialise an instance, using the passed queue.""" def prepare(self, record: LogRecord) -> Any: - """ - Prepare a record for queuing. The object returned by this method is + """Prepare a record for queuing. The object returned by this method is enqueued. The base implementation formats the record to merge the message and @@ -632,8 +577,7 @@ class QueueHandler(Handler): """ def enqueue(self, record: LogRecord) -> None: - """ - Enqueue a record. + """Enqueue a record. The base implementation uses put_nowait. You may want to override this method if you want to use blocking, timeouts or custom queue @@ -643,8 +587,7 @@ class QueueHandler(Handler): listener: QueueListener | None class QueueListener: - """ - This class implements an internal threaded listener which watches for + """This class implements an internal threaded listener which watches for LogRecords being added to a queue, removes them and passes them to a list of handlers for processing. """ @@ -654,22 +597,19 @@ class QueueListener: queue: _QueueLike[Any] # undocumented _thread: Thread | None # undocumented def __init__(self, queue: _QueueLike[Any], *handlers: Handler, respect_handler_level: bool = False) -> None: - """ - Initialise an instance with the specified queue and + """Initialise an instance with the specified queue and handlers. """ def dequeue(self, block: bool) -> LogRecord: - """ - Dequeue a record and return it, optionally blocking. + """Dequeue a record and return it, optionally blocking. The base implementation uses get. You may want to override this method if you want to use timeouts or work with custom queue implementations. """ def prepare(self, record: LogRecord) -> Any: - """ - Prepare a record for handling. + """Prepare a record for handling. This method just returns the passed-in record. You may want to override this method if you need to do any custom marshalling or @@ -677,16 +617,14 @@ class QueueListener: """ def start(self) -> None: - """ - Start the listener. + """Start the listener. This starts up a background thread to monitor the queue for LogRecords to process. """ def stop(self) -> None: - """ - Stop the listener. + """Stop the listener. This asks the thread to terminate, and then waits for it to do so. Note that if you don't call this before your application exits, there @@ -694,8 +632,7 @@ class QueueListener: """ def enqueue_sentinel(self) -> None: - """ - This is used to enqueue the sentinel record. + """This is used to enqueue the sentinel record. The base implementation uses put_nowait. You may want to override this method if you want to use timeouts or work with custom queue @@ -703,21 +640,16 @@ class QueueListener: """ def handle(self, record: LogRecord) -> None: - """ - Handle a record. + """Handle a record. This just loops through the handlers offering them the record to handle. """ if sys.version_info >= (3, 14): def __enter__(self) -> Self: - """ - For use as a context manager. Starts the listener. - """ + """For use as a context manager. Starts the listener.""" def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None ) -> None: - """ - For use as a context manager. Stops the listener. - """ + """For use as a context manager. Stops the listener.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/lzma.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/lzma.pyi index 4c7ed3b200..1b2586366d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/lzma.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/lzma.pyi @@ -100,8 +100,7 @@ _OpenTextWritingMode: TypeAlias = Literal["wt", "xt", "at"] _PathOrFile: TypeAlias = StrOrBytesPath | IO[bytes] class LZMAFile(BaseStream, IO[bytes]): # type: ignore[misc] # incompatible definitions of writelines in the base classes - """ - A file object providing transparent LZMA (de)compression. + """A file object providing transparent LZMA (de)compression. An LZMAFile can act as a wrapper for an existing file object, or refer directly to a named file on disk. @@ -120,8 +119,7 @@ class LZMAFile(BaseStream, IO[bytes]): # type: ignore[misc] # incompatible def preset: int | None = None, filters: _FilterChain | None = None, ) -> None: - """ - Open an LZMA-compressed file in binary mode. + """Open an LZMA-compressed file in binary mode. filename can be either an actual file name (given as a str, bytes, or PathLike object), in which case the named file is @@ -166,24 +164,21 @@ class LZMAFile(BaseStream, IO[bytes]): # type: ignore[misc] # incompatible def def __enter__(self) -> Self: ... def peek(self, size: int = -1) -> bytes: - """ - Return buffered data without advancing the file position. + """Return buffered data without advancing the file position. Always returns at least one byte of data, unless at EOF. The exact number of bytes returned is unspecified. """ def read(self, size: int | None = -1) -> bytes: - """ - Read up to size uncompressed bytes from the file. + """Read up to size uncompressed bytes from the file. If size is negative or omitted, read until EOF is reached. Returns b"" if the file is already at EOF. """ def read1(self, size: int = -1) -> bytes: - """ - Read up to size uncompressed bytes, while trying to avoid + """Read up to size uncompressed bytes, while trying to avoid making multiple reads from the underlying stream. Reads up to a buffer's worth of data if size is negative. @@ -191,8 +186,7 @@ class LZMAFile(BaseStream, IO[bytes]): # type: ignore[misc] # incompatible def """ def readline(self, size: int | None = -1) -> bytes: - """ - Read a line of uncompressed bytes from the file. + """Read a line of uncompressed bytes from the file. The terminating newline (if present) is retained. If size is non-negative, no more than size bytes will be read (in which @@ -200,8 +194,7 @@ class LZMAFile(BaseStream, IO[bytes]): # type: ignore[misc] # incompatible def """ def write(self, data: ReadableBuffer) -> int: - """ - Write a bytes object to the file. + """Write a bytes object to the file. Returns the number of uncompressed bytes written, which is always the length of data in bytes. Note that due to buffering, @@ -210,8 +203,7 @@ class LZMAFile(BaseStream, IO[bytes]): # type: ignore[misc] # incompatible def """ def seek(self, offset: int, whence: int = 0) -> int: - """ - Change the file position. + """Change the file position. The new position is specified by offset, relative to the position indicated by whence. Possible values for whence are: @@ -239,8 +231,7 @@ def open( errors: None = None, newline: None = None, ) -> LZMAFile: - """ - Open an LZMA-compressed file in binary or text mode. + """Open an LZMA-compressed file in binary or text mode. filename can be either an actual file name (given as a str, bytes, or PathLike object), in which case the named file is opened, or it @@ -318,8 +309,7 @@ def open( def compress( data: ReadableBuffer, format: int = 1, check: int = -1, preset: int | None = None, filters: _FilterChain | None = None ) -> bytes: - """ - Compress a block of data. + """Compress a block of data. Refer to LZMACompressor's docstring for a description of the optional arguments *format*, *check*, *preset* and *filters*. @@ -328,8 +318,7 @@ def compress( """ def decompress(data: ReadableBuffer, format: int = 0, memlimit: int | None = None, filters: _FilterChain | None = None) -> bytes: - """ - Decompress a block of data. + """Decompress a block of data. Refer to LZMADecompressor's docstring for a description of the optional arguments *format*, *check* and *filters*. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/mailbox.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/mailbox.pyi index 1dad2e2774..98312ce3c4 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/mailbox.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/mailbox.pyi @@ -48,66 +48,47 @@ class _HasItems(Protocol): linesep: bytes class Mailbox(Generic[_MessageT]): - """ - A group of messages in a particular place. - """ + """A group of messages in a particular place.""" _path: str # undocumented _factory: Callable[[IO[Any]], _MessageT] | None # undocumented @overload def __init__(self, path: StrPath, factory: Callable[[IO[Any]], _MessageT], create: bool = True) -> None: - """ - Initialize a Mailbox instance. - """ + """Initialize a Mailbox instance.""" @overload def __init__(self, path: StrPath, factory: None = None, create: bool = True) -> None: ... @abstractmethod def add(self, message: _MessageData) -> str: - """ - Add message and return assigned key. - """ + """Add message and return assigned key.""" @abstractmethod def remove(self, key: str) -> None: - """ - Remove the keyed message; raise KeyError if it doesn't exist. - """ + """Remove the keyed message; raise KeyError if it doesn't exist.""" def __delitem__(self, key: str) -> None: ... def discard(self, key: str) -> None: - """ - If the keyed message exists, remove it. - """ + """If the keyed message exists, remove it.""" @abstractmethod def __setitem__(self, key: str, message: _MessageData) -> None: - """ - Replace the keyed message; raise KeyError if it doesn't exist. - """ + """Replace the keyed message; raise KeyError if it doesn't exist.""" @overload def get(self, key: str, default: None = None) -> _MessageT | None: - """ - Return the keyed message, or default if it doesn't exist. - """ + """Return the keyed message, or default if it doesn't exist.""" @overload def get(self, key: str, default: _T) -> _MessageT | _T: ... def __getitem__(self, key: str) -> _MessageT: - """ - Return the keyed message; raise KeyError if it doesn't exist. - """ + """Return the keyed message; raise KeyError if it doesn't exist.""" @abstractmethod def get_message(self, key: str) -> _MessageT: - """ - Return a Message representation or raise a KeyError. - """ + """Return a Message representation or raise a KeyError.""" def get_string(self, key: str) -> str: - """ - Return a string representation or raise a KeyError. + """Return a string representation or raise a KeyError. Uses email.message.Message to create a 7bit clean string representation of the message. @@ -115,719 +96,440 @@ class Mailbox(Generic[_MessageT]): @abstractmethod def get_bytes(self, key: str) -> bytes: - """ - Return a byte string representation or raise a KeyError. - """ + """Return a byte string representation or raise a KeyError.""" # As '_ProxyFile' doesn't implement the full IO spec, and BytesIO is incompatible with it, get_file return is Any here @abstractmethod def get_file(self, key: str) -> Any: - """ - Return a file-like representation or raise a KeyError. - """ + """Return a file-like representation or raise a KeyError.""" @abstractmethod def iterkeys(self) -> Iterator[str]: - """ - Return an iterator over keys. - """ + """Return an iterator over keys.""" def keys(self) -> list[str]: - """ - Return a list of keys. - """ + """Return a list of keys.""" def itervalues(self) -> Iterator[_MessageT]: - """ - Return an iterator over all messages. - """ + """Return an iterator over all messages.""" def __iter__(self) -> Iterator[_MessageT]: ... def values(self) -> list[_MessageT]: - """ - Return a list of messages. Memory intensive. - """ + """Return a list of messages. Memory intensive.""" def iteritems(self) -> Iterator[tuple[str, _MessageT]]: - """ - Return an iterator over (key, message) tuples. - """ + """Return an iterator over (key, message) tuples.""" def items(self) -> list[tuple[str, _MessageT]]: - """ - Return a list of (key, message) tuples. Memory intensive. - """ + """Return a list of (key, message) tuples. Memory intensive.""" @abstractmethod def __contains__(self, key: str) -> bool: - """ - Return True if the keyed message exists, False otherwise. - """ + """Return True if the keyed message exists, False otherwise.""" @abstractmethod def __len__(self) -> int: - """ - Return a count of messages in the mailbox. - """ + """Return a count of messages in the mailbox.""" def clear(self) -> None: - """ - Delete all messages. - """ + """Delete all messages.""" @overload def pop(self, key: str, default: None = None) -> _MessageT | None: - """ - Delete the keyed message and return it, or default. - """ + """Delete the keyed message and return it, or default.""" @overload def pop(self, key: str, default: _T) -> _MessageT | _T: ... def popitem(self) -> tuple[str, _MessageT]: - """ - Delete an arbitrary (key, message) pair and return it. - """ + """Delete an arbitrary (key, message) pair and return it.""" def update(self, arg: _HasIteritems | _HasItems | Iterable[tuple[str, _MessageData]] | None = None) -> None: - """ - Change the messages that correspond to certain keys. - """ + """Change the messages that correspond to certain keys.""" @abstractmethod def flush(self) -> None: - """ - Write any pending changes to the disk. - """ + """Write any pending changes to the disk.""" @abstractmethod def lock(self) -> None: - """ - Lock the mailbox. - """ + """Lock the mailbox.""" @abstractmethod def unlock(self) -> None: - """ - Unlock the mailbox if it is locked. - """ + """Unlock the mailbox if it is locked.""" @abstractmethod def close(self) -> None: - """ - Flush and close the mailbox. - """ + """Flush and close the mailbox.""" def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ class Maildir(Mailbox[MaildirMessage]): - """ - A qmail-style Maildir mailbox. - """ + """A qmail-style Maildir mailbox.""" colon: str def __init__(self, dirname: StrPath, factory: Callable[[IO[Any]], MaildirMessage] | None = None, create: bool = True) -> None: - """ - Initialize a Maildir instance. - """ + """Initialize a Maildir instance.""" def add(self, message: _MessageData) -> str: - """ - Add message and return assigned key. - """ + """Add message and return assigned key.""" def remove(self, key: str) -> None: - """ - Remove the keyed message; raise KeyError if it doesn't exist. - """ + """Remove the keyed message; raise KeyError if it doesn't exist.""" def __setitem__(self, key: str, message: _MessageData) -> None: - """ - Replace the keyed message; raise KeyError if it doesn't exist. - """ + """Replace the keyed message; raise KeyError if it doesn't exist.""" def get_message(self, key: str) -> MaildirMessage: - """ - Return a Message representation or raise a KeyError. - """ + """Return a Message representation or raise a KeyError.""" def get_bytes(self, key: str) -> bytes: - """ - Return a bytes representation or raise a KeyError. - """ + """Return a bytes representation or raise a KeyError.""" def get_file(self, key: str) -> _ProxyFile[bytes]: - """ - Return a file-like representation or raise a KeyError. - """ + """Return a file-like representation or raise a KeyError.""" if sys.version_info >= (3, 13): def get_info(self, key: str) -> str: - """ - Get the keyed message's "info" as a string. - """ + """Get the keyed message's "info" as a string.""" def set_info(self, key: str, info: str) -> None: - """ - Set the keyed message's "info" string. - """ + """Set the keyed message's "info" string.""" def get_flags(self, key: str) -> str: - """ - Return as a string the standard flags that are set on the keyed message. - """ + """Return as a string the standard flags that are set on the keyed message.""" def set_flags(self, key: str, flags: str) -> None: - """ - Set the given flags and unset all others on the keyed message. - """ + """Set the given flags and unset all others on the keyed message.""" def add_flag(self, key: str, flag: str) -> None: - """ - Set the given flag(s) without changing others on the keyed message. - """ + """Set the given flag(s) without changing others on the keyed message.""" def remove_flag(self, key: str, flag: str) -> None: - """ - Unset the given string flag(s) without changing others on the keyed message. - """ + """Unset the given string flag(s) without changing others on the keyed message.""" def iterkeys(self) -> Iterator[str]: - """ - Return an iterator over keys. - """ + """Return an iterator over keys.""" def __contains__(self, key: str) -> bool: - """ - Return True if the keyed message exists, False otherwise. - """ + """Return True if the keyed message exists, False otherwise.""" def __len__(self) -> int: - """ - Return a count of messages in the mailbox. - """ + """Return a count of messages in the mailbox.""" def flush(self) -> None: - """ - Write any pending changes to disk. - """ + """Write any pending changes to disk.""" def lock(self) -> None: - """ - Lock the mailbox. - """ + """Lock the mailbox.""" def unlock(self) -> None: - """ - Unlock the mailbox if it is locked. - """ + """Unlock the mailbox if it is locked.""" def close(self) -> None: - """ - Flush and close the mailbox. - """ + """Flush and close the mailbox.""" def list_folders(self) -> list[str]: - """ - Return a list of folder names. - """ + """Return a list of folder names.""" def get_folder(self, folder: str) -> Maildir: - """ - Return a Maildir instance for the named folder. - """ + """Return a Maildir instance for the named folder.""" def add_folder(self, folder: str) -> Maildir: - """ - Create a folder and return a Maildir instance representing it. - """ + """Create a folder and return a Maildir instance representing it.""" def remove_folder(self, folder: str) -> None: - """ - Delete the named folder, which must be empty. - """ + """Delete the named folder, which must be empty.""" def clean(self) -> None: - """ - Delete old files in "tmp". - """ + """Delete old files in "tmp".""" def next(self) -> str | None: - """ - Return the next message in a one-time iteration. - """ + """Return the next message in a one-time iteration.""" class _singlefileMailbox(Mailbox[_MessageT], metaclass=ABCMeta): - """ - A single-file mailbox. - """ + """A single-file mailbox.""" def add(self, message: _MessageData) -> str: - """ - Add message and return assigned key. - """ + """Add message and return assigned key.""" def remove(self, key: str) -> None: - """ - Remove the keyed message; raise KeyError if it doesn't exist. - """ + """Remove the keyed message; raise KeyError if it doesn't exist.""" def __setitem__(self, key: str, message: _MessageData) -> None: - """ - Replace the keyed message; raise KeyError if it doesn't exist. - """ + """Replace the keyed message; raise KeyError if it doesn't exist.""" def iterkeys(self) -> Iterator[str]: - """ - Return an iterator over keys. - """ + """Return an iterator over keys.""" def __contains__(self, key: str) -> bool: - """ - Return True if the keyed message exists, False otherwise. - """ + """Return True if the keyed message exists, False otherwise.""" def __len__(self) -> int: - """ - Return a count of messages in the mailbox. - """ + """Return a count of messages in the mailbox.""" def lock(self) -> None: - """ - Lock the mailbox. - """ + """Lock the mailbox.""" def unlock(self) -> None: - """ - Unlock the mailbox if it is locked. - """ + """Unlock the mailbox if it is locked.""" def flush(self) -> None: - """ - Write any pending changes to disk. - """ + """Write any pending changes to disk.""" def close(self) -> None: - """ - Flush and close the mailbox. - """ + """Flush and close the mailbox.""" class _mboxMMDF(_singlefileMailbox[_MessageT]): - """ - An mbox or MMDF mailbox. - """ + """An mbox or MMDF mailbox.""" def get_message(self, key: str) -> _MessageT: - """ - Return a Message representation or raise a KeyError. - """ + """Return a Message representation or raise a KeyError.""" def get_file(self, key: str, from_: bool = False) -> _PartialFile[bytes]: - """ - Return a file-like representation or raise a KeyError. - """ + """Return a file-like representation or raise a KeyError.""" def get_bytes(self, key: str, from_: bool = False) -> bytes: - """ - Return a string representation or raise a KeyError. - """ + """Return a string representation or raise a KeyError.""" def get_string(self, key: str, from_: bool = False) -> str: - """ - Return a string representation or raise a KeyError. - """ + """Return a string representation or raise a KeyError.""" class mbox(_mboxMMDF[mboxMessage]): - """ - A classic mbox mailbox. - """ + """A classic mbox mailbox.""" def __init__(self, path: StrPath, factory: Callable[[IO[Any]], mboxMessage] | None = None, create: bool = True) -> None: - """ - Initialize an mbox mailbox. - """ + """Initialize an mbox mailbox.""" class MMDF(_mboxMMDF[MMDFMessage]): - """ - An MMDF mailbox. - """ + """An MMDF mailbox.""" def __init__(self, path: StrPath, factory: Callable[[IO[Any]], MMDFMessage] | None = None, create: bool = True) -> None: - """ - Initialize an MMDF mailbox. - """ + """Initialize an MMDF mailbox.""" class MH(Mailbox[MHMessage]): - """ - An MH mailbox. - """ + """An MH mailbox.""" def __init__(self, path: StrPath, factory: Callable[[IO[Any]], MHMessage] | None = None, create: bool = True) -> None: - """ - Initialize an MH instance. - """ + """Initialize an MH instance.""" def add(self, message: _MessageData) -> str: - """ - Add message and return assigned key. - """ + """Add message and return assigned key.""" def remove(self, key: str) -> None: - """ - Remove the keyed message; raise KeyError if it doesn't exist. - """ + """Remove the keyed message; raise KeyError if it doesn't exist.""" def __setitem__(self, key: str, message: _MessageData) -> None: - """ - Replace the keyed message; raise KeyError if it doesn't exist. - """ + """Replace the keyed message; raise KeyError if it doesn't exist.""" def get_message(self, key: str) -> MHMessage: - """ - Return a Message representation or raise a KeyError. - """ + """Return a Message representation or raise a KeyError.""" def get_bytes(self, key: str) -> bytes: - """ - Return a bytes representation or raise a KeyError. - """ + """Return a bytes representation or raise a KeyError.""" def get_file(self, key: str) -> _ProxyFile[bytes]: - """ - Return a file-like representation or raise a KeyError. - """ + """Return a file-like representation or raise a KeyError.""" def iterkeys(self) -> Iterator[str]: - """ - Return an iterator over keys. - """ + """Return an iterator over keys.""" def __contains__(self, key: str) -> bool: - """ - Return True if the keyed message exists, False otherwise. - """ + """Return True if the keyed message exists, False otherwise.""" def __len__(self) -> int: - """ - Return a count of messages in the mailbox. - """ + """Return a count of messages in the mailbox.""" def flush(self) -> None: - """ - Write any pending changes to the disk. - """ + """Write any pending changes to the disk.""" def lock(self) -> None: - """ - Lock the mailbox. - """ + """Lock the mailbox.""" def unlock(self) -> None: - """ - Unlock the mailbox if it is locked. - """ + """Unlock the mailbox if it is locked.""" def close(self) -> None: - """ - Flush and close the mailbox. - """ + """Flush and close the mailbox.""" def list_folders(self) -> list[str]: - """ - Return a list of folder names. - """ + """Return a list of folder names.""" def get_folder(self, folder: StrPath) -> MH: - """ - Return an MH instance for the named folder. - """ + """Return an MH instance for the named folder.""" def add_folder(self, folder: StrPath) -> MH: - """ - Create a folder and return an MH instance representing it. - """ + """Create a folder and return an MH instance representing it.""" def remove_folder(self, folder: StrPath) -> None: - """ - Delete the named folder, which must be empty. - """ + """Delete the named folder, which must be empty.""" def get_sequences(self) -> dict[str, list[int]]: - """ - Return a name-to-key-list dictionary to define each sequence. - """ + """Return a name-to-key-list dictionary to define each sequence.""" def set_sequences(self, sequences: Mapping[str, Sequence[int]]) -> None: - """ - Set sequences using the given name-to-key-list dictionary. - """ + """Set sequences using the given name-to-key-list dictionary.""" def pack(self) -> None: - """ - Re-name messages to eliminate numbering gaps. Invalidates keys. - """ + """Re-name messages to eliminate numbering gaps. Invalidates keys.""" class Babyl(_singlefileMailbox[BabylMessage]): - """ - An Rmail-style Babyl mailbox. - """ + """An Rmail-style Babyl mailbox.""" def __init__(self, path: StrPath, factory: Callable[[IO[Any]], BabylMessage] | None = None, create: bool = True) -> None: - """ - Initialize a Babyl mailbox. - """ + """Initialize a Babyl mailbox.""" def get_message(self, key: str) -> BabylMessage: - """ - Return a Message representation or raise a KeyError. - """ + """Return a Message representation or raise a KeyError.""" def get_bytes(self, key: str) -> bytes: - """ - Return a string representation or raise a KeyError. - """ + """Return a string representation or raise a KeyError.""" def get_file(self, key: str) -> IO[bytes]: - """ - Return a file-like representation or raise a KeyError. - """ + """Return a file-like representation or raise a KeyError.""" def get_labels(self) -> list[str]: - """ - Return a list of user-defined labels in the mailbox. - """ + """Return a list of user-defined labels in the mailbox.""" class Message(email.message.Message): - """ - Message with mailbox-format-specific properties. - """ + """Message with mailbox-format-specific properties.""" def __init__(self, message: _MessageData | None = None) -> None: - """ - Initialize a Message instance. - """ + """Initialize a Message instance.""" class MaildirMessage(Message): - """ - Message with Maildir-specific properties. - """ + """Message with Maildir-specific properties.""" def get_subdir(self) -> str: - """ - Return 'new' or 'cur'. - """ + """Return 'new' or 'cur'.""" def set_subdir(self, subdir: Literal["new", "cur"]) -> None: - """ - Set subdir to 'new' or 'cur'. - """ + """Set subdir to 'new' or 'cur'.""" def get_flags(self) -> str: - """ - Return as a string the flags that are set. - """ + """Return as a string the flags that are set.""" def set_flags(self, flags: Iterable[str]) -> None: - """ - Set the given flags and unset all others. - """ + """Set the given flags and unset all others.""" def add_flag(self, flag: str) -> None: - """ - Set the given flag(s) without changing others. - """ + """Set the given flag(s) without changing others.""" def remove_flag(self, flag: str) -> None: - """ - Unset the given string flag(s) without changing others. - """ + """Unset the given string flag(s) without changing others.""" def get_date(self) -> int: - """ - Return delivery date of message, in seconds since the epoch. - """ + """Return delivery date of message, in seconds since the epoch.""" def set_date(self, date: float) -> None: - """ - Set delivery date of message, in seconds since the epoch. - """ + """Set delivery date of message, in seconds since the epoch.""" def get_info(self) -> str: - """ - Get the message's "info" as a string. - """ + """Get the message's "info" as a string.""" def set_info(self, info: str) -> None: - """ - Set the message's "info" string. - """ + """Set the message's "info" string.""" class _mboxMMDFMessage(Message): - """ - Message with mbox- or MMDF-specific properties. - """ + """Message with mbox- or MMDF-specific properties.""" def get_from(self) -> str: - """ - Return contents of "From " line. - """ + """Return contents of "From " line.""" def set_from(self, from_: str, time_: bool | tuple[int, int, int, int, int, int, int, int, int] | None = None) -> None: - """ - Set "From " line, formatting and appending time_ if specified. - """ + """Set "From " line, formatting and appending time_ if specified.""" def get_flags(self) -> str: - """ - Return as a string the flags that are set. - """ + """Return as a string the flags that are set.""" def set_flags(self, flags: Iterable[str]) -> None: - """ - Set the given flags and unset all others. - """ + """Set the given flags and unset all others.""" def add_flag(self, flag: str) -> None: - """ - Set the given flag(s) without changing others. - """ + """Set the given flag(s) without changing others.""" def remove_flag(self, flag: str) -> None: - """ - Unset the given string flag(s) without changing others. - """ + """Unset the given string flag(s) without changing others.""" class mboxMessage(_mboxMMDFMessage): - """ - Message with mbox-specific properties. - """ + """Message with mbox-specific properties.""" class MHMessage(Message): - """ - Message with MH-specific properties. - """ + """Message with MH-specific properties.""" def get_sequences(self) -> list[str]: - """ - Return a list of sequences that include the message. - """ + """Return a list of sequences that include the message.""" def set_sequences(self, sequences: Iterable[str]) -> None: - """ - Set the list of sequences that include the message. - """ + """Set the list of sequences that include the message.""" def add_sequence(self, sequence: str) -> None: - """ - Add sequence to list of sequences including the message. - """ + """Add sequence to list of sequences including the message.""" def remove_sequence(self, sequence: str) -> None: - """ - Remove sequence from the list of sequences including the message. - """ + """Remove sequence from the list of sequences including the message.""" class BabylMessage(Message): - """ - Message with Babyl-specific properties. - """ + """Message with Babyl-specific properties.""" def get_labels(self) -> list[str]: - """ - Return a list of labels on the message. - """ + """Return a list of labels on the message.""" def set_labels(self, labels: Iterable[str]) -> None: - """ - Set the list of labels on the message. - """ + """Set the list of labels on the message.""" def add_label(self, label: str) -> None: - """ - Add label to list of labels on the message. - """ + """Add label to list of labels on the message.""" def remove_label(self, label: str) -> None: - """ - Remove label from the list of labels on the message. - """ + """Remove label from the list of labels on the message.""" def get_visible(self) -> Message: - """ - Return a Message representation of visible headers. - """ + """Return a Message representation of visible headers.""" def set_visible(self, visible: _MessageData) -> None: - """ - Set the Message representation of visible headers. - """ + """Set the Message representation of visible headers.""" def update_visible(self) -> None: - """ - Update and/or sensibly generate a set of visible headers. - """ + """Update and/or sensibly generate a set of visible headers.""" class MMDFMessage(_mboxMMDFMessage): - """ - Message with MMDF-specific properties. - """ + """Message with MMDF-specific properties.""" class _ProxyFile(Generic[AnyStr]): - """ - A read-only wrapper of a file. - """ + """A read-only wrapper of a file.""" def __init__(self, f: IO[AnyStr], pos: int | None = None) -> None: - """ - Initialize a _ProxyFile. - """ + """Initialize a _ProxyFile.""" def read(self, size: int | None = None) -> AnyStr: - """ - Read bytes. - """ + """Read bytes.""" def read1(self, size: int | None = None) -> AnyStr: - """ - Read bytes. - """ + """Read bytes.""" def readline(self, size: int | None = None) -> AnyStr: - """ - Read a line. - """ + """Read a line.""" def readlines(self, sizehint: int | None = None) -> list[AnyStr]: - """ - Read multiple lines. - """ + """Read multiple lines.""" def __iter__(self) -> Iterator[AnyStr]: - """ - Iterate over lines. - """ + """Iterate over lines.""" def tell(self) -> int: - """ - Return the position. - """ + """Return the position.""" def seek(self, offset: int, whence: int = 0) -> None: - """ - Change position. - """ + """Change position.""" def close(self) -> None: - """ - Close the file. - """ + """Close the file.""" def __enter__(self) -> Self: - """ - Context management protocol support. - """ + """Context management protocol support.""" def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... def readable(self) -> bool: ... @@ -837,43 +539,28 @@ class _ProxyFile(Generic[AnyStr]): @property def closed(self) -> bool: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ class _PartialFile(_ProxyFile[AnyStr]): - """ - A read-only wrapper of part of a file. - """ + """A read-only wrapper of part of a file.""" def __init__(self, f: IO[AnyStr], start: int | None = None, stop: int | None = None) -> None: - """ - Initialize a _PartialFile. - """ + """Initialize a _PartialFile.""" class Error(Exception): - """ - Raised for module-specific errors. - """ + """Raised for module-specific errors.""" class NoSuchMailboxError(Error): - """ - The specified mailbox does not exist and won't be created. - """ + """The specified mailbox does not exist and won't be created.""" class NotEmptyError(Error): - """ - The specified mailbox is not empty and deletion was requested. - """ + """The specified mailbox is not empty and deletion was requested.""" class ExternalClashError(Error): - """ - Another process caused an action to fail. - """ + """Another process caused an action to fail.""" class FormatError(Error): - """ - A file appears to have an invalid format. - """ + """A file appears to have an invalid format.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/mailcap.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/mailcap.pyi index 4c56e274da..107ee54559 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/mailcap.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/mailcap.pyi @@ -12,8 +12,7 @@ __all__ = ["getcaps", "findmatch"] def findmatch( caps: Mapping[str, list[_Cap]], MIMEtype: str, key: str = "view", filename: str = "/dev/null", plist: Sequence[str] = [] ) -> tuple[str | None, _Cap | None]: - """ - Find a match for a mailcap entry. + """Find a match for a mailcap entry. Return a tuple containing the command line, and the mailcap entry used; (None, None) if no match is found. This may invoke the @@ -22,8 +21,7 @@ def findmatch( """ def getcaps() -> dict[str, list[_Cap]]: - """ - Return a dictionary containing the mailcap database. + """Return a dictionary containing the mailcap database. The dictionary maps a MIME type (in all lowercase, e.g. 'text/plain') to a list of dictionaries corresponding to mailcap entries. The list diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/marshal.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/marshal.pyi index 5c21d6d645..03235042eb 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/marshal.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/marshal.pyi @@ -60,8 +60,7 @@ _Marshallable: TypeAlias = ( if sys.version_info >= (3, 14): def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 5, /, *, allow_code: bool = True) -> None: - """ - Write the value on the open file. + """Write the value on the open file. value Must be a supported type. @@ -78,8 +77,7 @@ if sys.version_info >= (3, 14): """ def dumps(value: _Marshallable, version: int = 5, /, *, allow_code: bool = True) -> bytes: - """ - Return the bytes object that would be written to a file by dump(value, file). + """Return the bytes object that would be written to a file by dump(value, file). value Must be a supported type. @@ -94,8 +92,7 @@ if sys.version_info >= (3, 14): elif sys.version_info >= (3, 13): def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 4, /, *, allow_code: bool = True) -> None: - """ - Write the value on the open file. + """Write the value on the open file. value Must be a supported type. @@ -112,8 +109,7 @@ elif sys.version_info >= (3, 13): """ def dumps(value: _Marshallable, version: int = 4, /, *, allow_code: bool = True) -> bytes: - """ - Return the bytes object that would be written to a file by dump(value, file). + """Return the bytes object that would be written to a file by dump(value, file). value Must be a supported type. @@ -128,8 +124,7 @@ elif sys.version_info >= (3, 13): else: def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 4, /) -> None: - """ - Write the value on the open file. + """Write the value on the open file. value Must be a supported type. @@ -144,8 +139,7 @@ else: """ def dumps(value: _Marshallable, version: int = 4, /) -> bytes: - """ - Return the bytes object that would be written to a file by dump(value, file). + """Return the bytes object that would be written to a file by dump(value, file). value Must be a supported type. @@ -158,8 +152,7 @@ else: if sys.version_info >= (3, 13): def load(file: SupportsRead[bytes], /, *, allow_code: bool = True) -> Any: - """ - Read one value from the open file and return it. + """Read one value from the open file and return it. file Must be readable binary file. @@ -175,8 +168,7 @@ if sys.version_info >= (3, 13): """ def loads(bytes: ReadableBuffer, /, *, allow_code: bool = True) -> Any: - """ - Convert the bytes-like object to a value. + """Convert the bytes-like object to a value. allow_code Allow to load code objects. @@ -187,8 +179,7 @@ if sys.version_info >= (3, 13): else: def load(file: SupportsRead[bytes], /) -> Any: - """ - Read one value from the open file and return it. + """Read one value from the open file and return it. file Must be readable binary file. @@ -202,8 +193,7 @@ else: """ def loads(bytes: ReadableBuffer, /) -> Any: - """ - Convert the bytes-like object to a value. + """Convert the bytes-like object to a value. If no valid value is found, raise EOFError, ValueError or TypeError. Extra bytes in the input are ignored. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/math.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/math.pyi index a5d702ad9c..2965976b62 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/math.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/math.pyi @@ -21,61 +21,48 @@ nan: Final[float] tau: Final[float] def acos(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the arc cosine (measured in radians) of x. + """Return the arc cosine (measured in radians) of x. The result is between 0 and pi. """ def acosh(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the inverse hyperbolic cosine of x. - """ + """Return the inverse hyperbolic cosine of x.""" def asin(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the arc sine (measured in radians) of x. + """Return the arc sine (measured in radians) of x. The result is between -pi/2 and pi/2. """ def asinh(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the inverse hyperbolic sine of x. - """ + """Return the inverse hyperbolic sine of x.""" def atan(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the arc tangent (measured in radians) of x. + """Return the arc tangent (measured in radians) of x. The result is between -pi/2 and pi/2. """ def atan2(y: _SupportsFloatOrIndex, x: _SupportsFloatOrIndex, /) -> float: - """ - Return the arc tangent (measured in radians) of y/x. + """Return the arc tangent (measured in radians) of y/x. Unlike atan(y/x), the signs of both x and y are considered. """ def atanh(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the inverse hyperbolic tangent of x. - """ + """Return the inverse hyperbolic tangent of x.""" if sys.version_info >= (3, 11): def cbrt(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the cube root of x. - """ + """Return the cube root of x.""" class _SupportsCeil(Protocol[_T_co]): def __ceil__(self) -> _T_co: ... @overload def ceil(x: _SupportsCeil[_T], /) -> _T: - """ - Return the ceiling of x as an Integral. + """Return the ceiling of x as an Integral. This is the smallest integer >= x. """ @@ -83,8 +70,7 @@ def ceil(x: _SupportsCeil[_T], /) -> _T: @overload def ceil(x: _SupportsFloatOrIndex, /) -> int: ... def comb(n: SupportsIndex, k: SupportsIndex, /) -> int: - """ - Number of ways to choose k items from n items without repetition and without order. + """Number of ways to choose k items from n items without repetition and without order. Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates to zero when k > n. @@ -98,31 +84,23 @@ def comb(n: SupportsIndex, k: SupportsIndex, /) -> int: """ def copysign(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: - """ - Return a float with the magnitude (absolute value) of x but the sign of y. + """Return a float with the magnitude (absolute value) of x but the sign of y. On platforms that support signed zeros, copysign(1.0, -0.0) returns -1.0. """ def cos(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the cosine of x (measured in radians). - """ + """Return the cosine of x (measured in radians).""" def cosh(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the hyperbolic cosine of x. - """ + """Return the hyperbolic cosine of x.""" def degrees(x: _SupportsFloatOrIndex, /) -> float: - """ - Convert angle x from radians to degrees. - """ + """Convert angle x from radians to degrees.""" def dist(p: Iterable[_SupportsFloatOrIndex], q: Iterable[_SupportsFloatOrIndex], /) -> float: - """ - Return the Euclidean distance between two points p and q. + """Return the Euclidean distance between two points p and q. The points should be specified as sequences (or iterables) of coordinates. Both inputs must have the same dimension. @@ -132,50 +110,36 @@ def dist(p: Iterable[_SupportsFloatOrIndex], q: Iterable[_SupportsFloatOrIndex], """ def erf(x: _SupportsFloatOrIndex, /) -> float: - """ - Error function at x. - """ + """Error function at x.""" def erfc(x: _SupportsFloatOrIndex, /) -> float: - """ - Complementary error function at x. - """ + """Complementary error function at x.""" def exp(x: _SupportsFloatOrIndex, /) -> float: - """ - Return e raised to the power of x. - """ + """Return e raised to the power of x.""" if sys.version_info >= (3, 11): def exp2(x: _SupportsFloatOrIndex, /) -> float: - """ - Return 2 raised to the power of x. - """ + """Return 2 raised to the power of x.""" def expm1(x: _SupportsFloatOrIndex, /) -> float: - """ - Return exp(x)-1. + """Return exp(x)-1. This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x. """ def fabs(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the absolute value of the float x. - """ + """Return the absolute value of the float x.""" def factorial(x: SupportsIndex, /) -> int: - """ - Find n!. - """ + """Find n!.""" class _SupportsFloor(Protocol[_T_co]): def __floor__(self) -> _T_co: ... @overload def floor(x: _SupportsFloor[_T], /) -> _T: - """ - Return the floor of x as an Integral. + """Return the floor of x as an Integral. This is the largest integer <= x. """ @@ -183,40 +147,32 @@ def floor(x: _SupportsFloor[_T], /) -> _T: @overload def floor(x: _SupportsFloatOrIndex, /) -> int: ... def fmod(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: - """ - Return fmod(x, y), according to platform C. + """Return fmod(x, y), according to platform C. x % y may differ. """ def frexp(x: _SupportsFloatOrIndex, /) -> tuple[float, int]: - """ - Return the mantissa and exponent of x, as pair (m, e). + """Return the mantissa and exponent of x, as pair (m, e). m is a float and e is an int, such that x = m * 2.**e. If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0. """ def fsum(seq: Iterable[_SupportsFloatOrIndex], /) -> float: - """ - Return an accurate floating-point sum of values in the iterable seq. + """Return an accurate floating-point sum of values in the iterable seq. Assumes IEEE-754 floating-point arithmetic. """ def gamma(x: _SupportsFloatOrIndex, /) -> float: - """ - Gamma function at x. - """ + """Gamma function at x.""" def gcd(*integers: SupportsIndex) -> int: - """ - Greatest Common Divisor. - """ + """Greatest Common Divisor.""" def hypot(*coordinates: _SupportsFloatOrIndex) -> float: - """ - Multidimensional Euclidean distance from the origin to a point. + """Multidimensional Euclidean distance from the origin to a point. Roughly equivalent to: sqrt(sum(x**2 for x in coordinates)) @@ -237,8 +193,7 @@ def isclose( rel_tol: _SupportsFloatOrIndex = 1e-09, abs_tol: _SupportsFloatOrIndex = 0.0, ) -> bool: - """ - Determine whether two floating-point numbers are close in value. + """Determine whether two floating-point numbers are close in value. rel_tol maximum difference for being considered "close", relative to the @@ -258,78 +213,57 @@ def isclose( """ def isinf(x: _SupportsFloatOrIndex, /) -> bool: - """ - Return True if x is a positive or negative infinity, and False otherwise. - """ + """Return True if x is a positive or negative infinity, and False otherwise.""" def isfinite(x: _SupportsFloatOrIndex, /) -> bool: - """ - Return True if x is neither an infinity nor a NaN, and False otherwise. - """ + """Return True if x is neither an infinity nor a NaN, and False otherwise.""" def isnan(x: _SupportsFloatOrIndex, /) -> bool: - """ - Return True if x is a NaN (not a number), and False otherwise. - """ + """Return True if x is a NaN (not a number), and False otherwise.""" def isqrt(n: SupportsIndex, /) -> int: - """ - Return the integer part of the square root of the input. - """ + """Return the integer part of the square root of the input.""" def lcm(*integers: SupportsIndex) -> int: - """ - Least Common Multiple. - """ + """Least Common Multiple.""" def ldexp(x: _SupportsFloatOrIndex, i: int, /) -> float: - """ - Return x * (2**i). + """Return x * (2**i). This is essentially the inverse of frexp(). """ def lgamma(x: _SupportsFloatOrIndex, /) -> float: - """ - Natural logarithm of absolute value of Gamma function at x. - """ + """Natural logarithm of absolute value of Gamma function at x.""" def log(x: _SupportsFloatOrIndex, base: _SupportsFloatOrIndex = ...) -> float: - """ - log(x, [base=math.e]) + """log(x, [base=math.e]) Return the logarithm of x to the given base. If the base is not specified, returns the natural logarithm (base e) of x. """ def log10(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the base 10 logarithm of x. - """ + """Return the base 10 logarithm of x.""" def log1p(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the natural logarithm of 1+x (base e). + """Return the natural logarithm of 1+x (base e). The result is computed in a way which is accurate for x near zero. """ def log2(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the base 2 logarithm of x. - """ + """Return the base 2 logarithm of x.""" def modf(x: _SupportsFloatOrIndex, /) -> tuple[float, float]: - """ - Return the fractional and integer parts of x. + """Return the fractional and integer parts of x. Both results carry the sign of x and are floats. """ if sys.version_info >= (3, 12): def nextafter(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /, *, steps: SupportsIndex | None = None) -> float: - """ - Return the floating-point value the given number of steps after x towards y. + """Return the floating-point value the given number of steps after x towards y. If steps is not specified or is None, it defaults to 1. @@ -339,13 +273,10 @@ if sys.version_info >= (3, 12): else: def nextafter(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: - """ - Return the next floating-point value after x towards y. - """ + """Return the next floating-point value after x towards y.""" def perm(n: SupportsIndex, k: SupportsIndex | None = None, /) -> int: - """ - Number of ways to choose k items from n items without repetition and with order. + """Number of ways to choose k items from n items without repetition and with order. Evaluates to n! / (n - k)! when k <= n and evaluates to zero when k > n. @@ -358,9 +289,7 @@ def perm(n: SupportsIndex, k: SupportsIndex | None = None, /) -> int: """ def pow(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: - """ - Return x**y (x to the power of y). - """ + """Return x**y (x to the power of y).""" _PositiveInteger: TypeAlias = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] _NegativeInteger: TypeAlias = Literal[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20] @@ -380,8 +309,7 @@ _SupportsProdNoDefaultT = TypeVar("_SupportsProdNoDefaultT", bound=_SupportsProd # Instead, just like `builtins.sum`, we explicitly handle several useful cases. @overload def prod(iterable: Iterable[bool | _LiteralInteger], /, *, start: int = 1) -> int: # type: ignore[overload-overlap] - """ - Calculate the product of all the elements in the input iterable. + """Calculate the product of all the elements in the input iterable. The default start value for the product is 1. @@ -395,13 +323,10 @@ def prod(iterable: Iterable[_SupportsProdNoDefaultT], /) -> _SupportsProdNoDefau @overload def prod(iterable: Iterable[_MultiplicableT1], /, *, start: _MultiplicableT2) -> _MultiplicableT1 | _MultiplicableT2: ... def radians(x: _SupportsFloatOrIndex, /) -> float: - """ - Convert angle x from degrees to radians. - """ + """Convert angle x from degrees to radians.""" def remainder(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: - """ - Difference between x and the closest integer multiple of y. + """Difference between x and the closest integer multiple of y. Return x - n*y where n*y is the closest integer multiple of y. In the case where x is exactly halfway between two multiples of @@ -409,19 +334,14 @@ def remainder(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: """ def sin(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the sine of x (measured in radians). - """ + """Return the sine of x (measured in radians).""" def sinh(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the hyperbolic sine of x. - """ + """Return the hyperbolic sine of x.""" if sys.version_info >= (3, 12): def sumprod(p: Iterable[float], q: Iterable[float], /) -> float: - """ - Return the sum of products of values from two iterables p and q. + """Return the sum of products of values from two iterables p and q. Roughly equivalent to: @@ -432,40 +352,30 @@ if sys.version_info >= (3, 12): """ def sqrt(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the square root of x. - """ + """Return the square root of x.""" def tan(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the tangent of x (measured in radians). - """ + """Return the tangent of x (measured in radians).""" def tanh(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the hyperbolic tangent of x. - """ + """Return the hyperbolic tangent of x.""" # Is different from `_typeshed.SupportsTrunc`, which is not generic class _SupportsTrunc(Protocol[_T_co]): def __trunc__(self) -> _T_co: ... def trunc(x: _SupportsTrunc[_T], /) -> _T: - """ - Truncates the Real x to the nearest Integral toward 0. + """Truncates the Real x to the nearest Integral toward 0. Uses the __trunc__ magic method. """ def ulp(x: _SupportsFloatOrIndex, /) -> float: - """ - Return the value of the least significant bit of the float x. - """ + """Return the value of the least significant bit of the float x.""" if sys.version_info >= (3, 13): def fma(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, z: _SupportsFloatOrIndex, /) -> float: - """ - Fused multiply-add operation. + """Fused multiply-add operation. Compute (x * y) + z with a single round. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/mimetypes.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/mimetypes.pyi index 9ee968bd42..6b7dd06db0 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/mimetypes.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/mimetypes.pyi @@ -49,8 +49,7 @@ if sys.version_info >= (3, 13): __all__ += ["guess_file_type"] def guess_type(url: StrPath, strict: bool = True) -> tuple[str | None, str | None]: - """ - Guess the type of a file based on its URL. + """Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string of the @@ -69,8 +68,7 @@ def guess_type(url: StrPath, strict: bool = True) -> tuple[str | None, str | Non """ def guess_all_extensions(type: str, strict: bool = True) -> list[str]: - """ - Guess the extensions for a file based on its MIME type. + """Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not @@ -84,8 +82,7 @@ def guess_all_extensions(type: str, strict: bool = True) -> list[str]: """ def guess_extension(type: str, strict: bool = True) -> str | None: - """ - Guess the extension for a file based on its MIME type. + """Guess the extension for a file based on its MIME type. Return value is a string giving a filename extension, including the leading dot ('.'). The extension is not guaranteed to have been @@ -100,8 +97,7 @@ def guess_extension(type: str, strict: bool = True) -> str | None: def init(files: Sequence[str] | None = None) -> None: ... def read_mime_types(file: str) -> dict[str, str] | None: ... def add_type(type: str, ext: str, strict: bool = True) -> None: - """ - Add a mapping between a type and an extension. + """Add a mapping between a type and an extension. When the extension is already known, the new type will replace the old one. When the type @@ -115,8 +111,7 @@ def add_type(type: str, ext: str, strict: bool = True) -> None: if sys.version_info >= (3, 13): def guess_file_type(path: StrPath, *, strict: bool = True) -> tuple[str | None, str | None]: - """ - Guess the type of a file based on its path. + """Guess the type of a file based on its path. Similar to guess_type(), but takes file path instead of URL. """ @@ -129,8 +124,7 @@ types_map: dict[str, str] common_types: dict[str, str] class MimeTypes: - """ - MIME-types datastore. + """MIME-types datastore. This datastore can handle information from mime.types-style files and supports basic determination of MIME type from a filename or @@ -143,8 +137,7 @@ class MimeTypes: types_map_inv: tuple[dict[str, str], dict[str, str]] def __init__(self, filenames: tuple[str, ...] = (), strict: bool = True) -> None: ... def add_type(self, type: str, ext: str, strict: bool = True) -> None: - """ - Add a mapping between a type and an extension. + """Add a mapping between a type and an extension. When the extension is already known, the new type will replace the old one. When the type @@ -159,8 +152,7 @@ class MimeTypes: """ def guess_extension(self, type: str, strict: bool = True) -> str | None: - """ - Guess the extension for a file based on its MIME type. + """Guess the extension for a file based on its MIME type. Return value is a string giving a filename extension, including the leading dot ('.'). The extension is not @@ -174,8 +166,7 @@ class MimeTypes: """ def guess_type(self, url: StrPath, strict: bool = True) -> tuple[str | None, str | None]: - """ - Guess the type of a file which is either a URL or a path-like object. + """Guess the type of a file which is either a URL or a path-like object. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string @@ -195,8 +186,7 @@ class MimeTypes: """ def guess_all_extensions(self, type: str, strict: bool = True) -> list[str]: - """ - Guess the extensions for a file based on its MIME type. + """Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not @@ -208,8 +198,7 @@ class MimeTypes: """ def read(self, filename: str, strict: bool = True) -> None: - """ - Read a single mime.types-format file, specified by pathname. + """Read a single mime.types-format file, specified by pathname. If strict is true, information will be added to list of standard types, else to the list of non-standard @@ -217,8 +206,7 @@ class MimeTypes: """ def readfp(self, fp: IO[str], strict: bool = True) -> None: - """ - Read a single mime.types-format file. + """Read a single mime.types-format file. If strict is true, information will be added to list of standard types, else to the list of non-standard @@ -226,8 +214,7 @@ class MimeTypes: """ def read_windows_registry(self, strict: bool = True) -> None: - """ - Load the MIME types database from Windows registry. + """Load the MIME types database from Windows registry. If strict is true, information will be added to list of standard types, else to the list of non-standard @@ -235,8 +222,7 @@ class MimeTypes: """ if sys.version_info >= (3, 13): def guess_file_type(self, path: StrPath, *, strict: bool = True) -> tuple[str | None, str | None]: - """ - Guess the type of a file based on its path. + """Guess the type of a file based on its path. Similar to guess_type(), but takes file path instead of URL. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/mmap.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/mmap.pyi index 457072cc76..38330010ce 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/mmap.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/mmap.pyi @@ -31,8 +31,7 @@ if sys.platform != "win32": PAGESIZE: int class mmap: - """ - Windows: mmap(fileno, length[, tagname[, access[, offset]]]) + """Windows: mmap(fileno, length[, tagname[, access[, offset]]]) Maps length bytes from the file specified by the file handle fileno, and returns a mmap object. If length is larger than the current size @@ -86,9 +85,7 @@ class mmap: def tell(self) -> int: ... def write_byte(self, byte: int) -> None: ... def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" closed: bool if sys.platform != "win32": def madvise(self, option: int, start: int = ..., length: int = ...) -> None: ... @@ -99,22 +96,16 @@ class mmap: def write(self, bytes: ReadableBuffer) -> int: ... @overload def __getitem__(self, key: int, /) -> int: - """ - Return self[key]. - """ + """Return self[key].""" @overload def __getitem__(self, key: slice, /) -> bytes: ... def __delitem__(self, key: int | slice, /) -> NoReturn: - """ - Delete self[key]. - """ + """Delete self[key].""" @overload def __setitem__(self, key: int, value: int, /) -> None: - """ - Set self[key] to value. - """ + """Set self[key] to value.""" @overload def __setitem__(self, key: slice, value: ReadableBuffer, /) -> None: ... @@ -127,14 +118,10 @@ class mmap: def __enter__(self) -> Self: ... def __exit__(self, *args: Unused) -> None: ... def __buffer__(self, flags: int, /) -> memoryview: - """ - Return a buffer object that exposes the underlying memory of the object. - """ + """Return a buffer object that exposes the underlying memory of the object.""" def __release_buffer__(self, buffer: memoryview, /) -> None: - """ - Release the buffer object that exposes the underlying memory of the object. - """ + """Release the buffer object that exposes the underlying memory of the object.""" if sys.version_info >= (3, 13): def seekable(self) -> Literal[True]: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/modulefinder.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/modulefinder.pyi index cb22f27e42..e7f733bbec 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/modulefinder.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/modulefinder.pyi @@ -65,21 +65,18 @@ class ModuleFinder: self, name: str, path: str | None, parent: Module | None = None ) -> tuple[IO[Any] | None, str | None, tuple[str, str, int]]: ... # undocumented def report(self) -> None: - """ - Print a report to stdout, listing the found modules with their + """Print a report to stdout, listing the found modules with their paths, as well as modules that are missing, or seem to be missing. """ def any_missing(self) -> list[str]: # undocumented - """ - Return a list of modules that appear to be missing. Use + """Return a list of modules that appear to be missing. Use any_missing_maybe() if you want to know which modules are certain to be missing, and which *may* be missing. """ def any_missing_maybe(self) -> tuple[list[str], list[str]]: # undocumented - """ - Return two lists, one with modules that are certainly missing + """Return two lists, one with modules that are certainly missing and one with modules that *may* be missing. The latter names could either be submodules *or* just global names in the package. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/msilib/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/msilib/__init__.pyi index 3e43cbc44f..fdf3e44dba 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/msilib/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/msilib/__init__.pyi @@ -37,7 +37,9 @@ if sys.platform == "win32": action: str, seqno: int | type[_Unspecified] = ..., cond: str | type[_Unspecified] = ..., - ) -> None: ... + ) -> None: + """Change the sequence number of an action in a sequence list""" + def add_data(db: _Database, table: str, values: Iterable[tuple[Any, ...]]) -> None: ... def add_stream(db: _Database, name: str, path: str) -> None: ... def init_database( @@ -80,7 +82,17 @@ if sys.platform == "win32": _logical: str, default: str, componentflags: int | None = None, - ) -> None: ... + ) -> None: + """Create a new directory in the Directory table. There is a current component + at each point in time for the directory, which is either explicitly created + through start_component, or implicitly when files are added for the first + time. Files are added into the current component, and into the cab file. + To create a directory, a base directory object needs to be specified (can be + None), the path to the physical directory, and a logical directory name. + Default specifies the DefaultDir slot in the directory table. componentflags + specifies the default flags that new components get. + """ + def start_component( self, component: str | None = None, @@ -88,11 +100,30 @@ if sys.platform == "win32": flags: int | None = None, keyfile: str | None = None, uuid: str | None = None, - ) -> None: ... + ) -> None: + """Add an entry to the Component table, and make this component the current for this + directory. If no component name is given, the directory name is used. If no feature + is given, the current feature is used. If no flags are given, the directory's default + flags are used. If no keyfile is given, the KeyPath is left null in the Component + table. + """ + def make_short(self, file: str) -> str: ... - def add_file(self, file: str, src: str | None = None, version: str | None = None, language: str | None = None) -> str: ... - def glob(self, pattern: str, exclude: Container[str] | None = None) -> list[str]: ... - def remove_pyc(self) -> None: ... + def add_file(self, file: str, src: str | None = None, version: str | None = None, language: str | None = None) -> str: + """Add a file to the current component of the directory, starting a new one + if there is no current component. By default, the file name in the source + and the file table will be identical. If the src file is specified, it is + interpreted relative to the current directory. Optionally, a version and a + language can be specified for the entry in the File table. + """ + + def glob(self, pattern: str, exclude: Container[str] | None = None) -> list[str]: + """Add a list of files to the current component as specified in the + glob pattern. Individual files can be excluded in the exclude list. + """ + + def remove_pyc(self) -> None: + """Remove .pyc files on uninstall""" class Binary: name: str diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/msvcrt.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/msvcrt.pyi index 403a5d9335..b630b4b80b 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/msvcrt.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/msvcrt.pyi @@ -13,20 +13,88 @@ if sys.platform == "win32": SEM_NOALIGNMENTFAULTEXCEPT: int SEM_NOGPFAULTERRORBOX: int SEM_NOOPENFILEERRORBOX: int - def locking(fd: int, mode: int, nbytes: int, /) -> None: ... - def setmode(fd: int, mode: int, /) -> int: ... - def open_osfhandle(handle: int, flags: int, /) -> int: ... - def get_osfhandle(fd: int, /) -> int: ... - def kbhit() -> bool: ... - def getch() -> bytes: ... - def getwch() -> str: ... - def getche() -> bytes: ... - def getwche() -> str: ... - def putch(char: bytes | bytearray, /) -> None: ... - def putwch(unicode_char: str, /) -> None: ... - def ungetch(char: bytes | bytearray, /) -> None: ... - def ungetwch(unicode_char: str, /) -> None: ... - def heapmin() -> None: ... - def SetErrorMode(mode: int, /) -> int: ... + def locking(fd: int, mode: int, nbytes: int, /) -> None: + """Lock part of a file based on file descriptor fd from the C runtime. + + Raises OSError on failure. The locked region of the file extends from + the current file position for nbytes bytes, and may continue beyond + the end of the file. mode must be one of the LK_* constants listed + below. Multiple regions in a file may be locked at the same time, but + may not overlap. Adjacent regions are not merged; they must be unlocked + individually. + """ + + def setmode(fd: int, mode: int, /) -> int: + """Set the line-end translation mode for the file descriptor fd. + + To set it to text mode, flags should be os.O_TEXT; for binary, it + should be os.O_BINARY. + + Return value is the previous mode. + """ + + def open_osfhandle(handle: int, flags: int, /) -> int: + """Create a C runtime file descriptor from the file handle handle. + + The flags parameter should be a bitwise OR of os.O_APPEND, os.O_RDONLY, + and os.O_TEXT. The returned file descriptor may be used as a parameter + to os.fdopen() to create a file object. + """ + + def get_osfhandle(fd: int, /) -> int: + """Return the file handle for the file descriptor fd. + + Raises OSError if fd is not recognized. + """ + + def kbhit() -> bool: + """Returns a nonzero value if a keypress is waiting to be read. Otherwise, return 0.""" + + def getch() -> bytes: + """Read a keypress and return the resulting character as a byte string. + + Nothing is echoed to the console. This call will block if a keypress is + not already available, but will not wait for Enter to be pressed. If the + pressed key was a special function key, this will return '\\000' or + '\\xe0'; the next call will return the keycode. The Control-C keypress + cannot be read with this function. + """ + + def getwch() -> str: + """Wide char variant of getch(), returning a Unicode value.""" + + def getche() -> bytes: + """Similar to getch(), but the keypress will be echoed if possible.""" + + def getwche() -> str: + """Wide char variant of getche(), returning a Unicode value.""" + + def putch(char: bytes | bytearray, /) -> None: + """Print the byte string char to the console without buffering.""" + + def putwch(unicode_char: str, /) -> None: + """Wide char variant of putch(), accepting a Unicode value.""" + + def ungetch(char: bytes | bytearray, /) -> None: + """Opposite of getch. + + Cause the byte string char to be "pushed back" into the + console buffer; it will be the next character read by + getch() or getche(). + """ + + def ungetwch(unicode_char: str, /) -> None: + """Wide char variant of ungetch(), accepting a Unicode value.""" + + def heapmin() -> None: + """Minimize the malloc() heap. + + Force the malloc() heap to clean itself up and return unused blocks + to the operating system. On failure, this raises OSError. + """ + + def SetErrorMode(mode: int, /) -> int: + """Wrapper around SetErrorMode.""" if sys.version_info >= (3, 10): - def GetErrorMode() -> int: ... # undocumented + def GetErrorMode() -> int: # undocumented + """Wrapper around GetErrorMode.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/connection.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/connection.pyi index ca552365ff..fc69783184 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/connection.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/connection.pyi @@ -19,62 +19,41 @@ class _ConnectionBase(Generic[_SendT_contra, _RecvT_co]): def __init__(self, handle: SupportsIndex, readable: bool = True, writable: bool = True) -> None: ... @property def closed(self) -> bool: # undocumented - """ - True if the connection is closed - """ + """True if the connection is closed""" @property def readable(self) -> bool: # undocumented - """ - True if the connection is readable - """ + """True if the connection is readable""" @property def writable(self) -> bool: # undocumented - """ - True if the connection is writable - """ + """True if the connection is writable""" def fileno(self) -> int: - """ - File descriptor or handle of the connection - """ + """File descriptor or handle of the connection""" def close(self) -> None: - """ - Close the connection - """ + """Close the connection""" def send_bytes(self, buf: ReadableBuffer, offset: int = 0, size: int | None = None) -> None: - """ - Send the bytes data from a bytes-like object - """ + """Send the bytes data from a bytes-like object""" def send(self, obj: _SendT_contra) -> None: - """ - Send a (picklable) object - """ + """Send a (picklable) object""" def recv_bytes(self, maxlength: int | None = None) -> bytes: - """ - Receive bytes data as a bytes object. - """ + """Receive bytes data as a bytes object.""" def recv_bytes_into(self, buf: Any, offset: int = 0) -> int: - """ - Receive bytes data into a writeable bytes-like object. + """Receive bytes data into a writeable bytes-like object. Return the number of bytes read. """ def recv(self) -> _RecvT_co: - """ - Receive a (picklable) object - """ + """Receive a (picklable) object""" def poll(self, timeout: float | None = 0.0) -> bool: - """ - Whether there is any input available to be read - """ + """Whether there is any input available to be read""" def __enter__(self) -> Self: ... def __exit__( @@ -83,17 +62,19 @@ class _ConnectionBase(Generic[_SendT_contra, _RecvT_co]): def __del__(self) -> None: ... class Connection(_ConnectionBase[_SendT_contra, _RecvT_co]): - """ - Connection class based on an arbitrary file descriptor (Unix only), or + """Connection class based on an arbitrary file descriptor (Unix only), or a socket handle (Windows). """ if sys.platform == "win32": - class PipeConnection(_ConnectionBase[_SendT_contra, _RecvT_co]): ... + class PipeConnection(_ConnectionBase[_SendT_contra, _RecvT_co]): + """Connection class based on a Windows named pipe. + Overlapped I/O is used, so the handles must have been created + with FILE_FLAG_OVERLAPPED. + """ class Listener: - """ - Returns a listener object. + """Returns a listener object. This is a wrapper for a bound socket which is 'listening' for connections, or for a Windows named pipe. @@ -103,16 +84,13 @@ class Listener: self, address: _Address | None = None, family: str | None = None, backlog: int = 1, authkey: bytes | None = None ) -> None: ... def accept(self) -> Connection[Incomplete, Incomplete]: - """ - Accept a connection on the bound socket or named pipe of `self`. + """Accept a connection on the bound socket or named pipe of `self`. Returns a `Connection` object. """ def close(self) -> None: - """ - Close the bound socket or named pipe of `self`. - """ + """Close the bound socket or named pipe of `self`.""" @property def address(self) -> _Address: ... @@ -134,16 +112,13 @@ def answer_challenge(connection: Connection[Any, Any], authkey: bytes) -> None: def wait( object_list: Iterable[Connection[_SendT_contra, _RecvT_co] | socket.socket | int], timeout: float | None = None ) -> list[Connection[_SendT_contra, _RecvT_co] | socket.socket | int]: - """ - Wait till an object in object_list is ready/readable. + """Wait till an object in object_list is ready/readable. Returns list of those objects in object_list which are ready/readable. """ def Client(address: _Address, family: str | None = None, authkey: bytes | None = None) -> Connection[Any, Any]: - """ - Returns a connection to the address of a `Listener` - """ + """Returns a connection to the address of a `Listener`""" # N.B. Keep this in sync with multiprocessing.context.BaseContext.Pipe. # _ConnectionBase is the common base class of Connection and PipeConnection @@ -153,9 +128,8 @@ def Client(address: _Address, family: str | None = None, authkey: bytes | None = # However, TypeVars scoped entirely within a return annotation is unspecified in the spec. if sys.platform != "win32": def Pipe(duplex: bool = True) -> tuple[Connection[Any, Any], Connection[Any, Any]]: - """ - Returns pair of connection objects at either end of a pipe - """ + """Returns pair of connection objects at either end of a pipe""" else: - def Pipe(duplex: bool = True) -> tuple[PipeConnection[Any, Any], PipeConnection[Any, Any]]: ... + def Pipe(duplex: bool = True) -> tuple[PipeConnection[Any, Any], PipeConnection[Any, Any]]: + """Returns pair of connection objects at either end of a pipe""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/context.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/context.pyi index 03d5c77e30..824798fef4 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/context.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/context.pyi @@ -38,30 +38,21 @@ class BaseContext: # multiprocessing.*, so the signatures should be identical (modulo self). @staticmethod def current_process() -> BaseProcess: - """ - Return process object representing the current process - """ + """Return process object representing the current process""" @staticmethod def parent_process() -> BaseProcess | None: - """ - Return process object representing the parent process - """ + """Return process object representing the parent process""" @staticmethod def active_children() -> list[BaseProcess]: - """ - Return list of process objects corresponding to live child processes - """ + """Return list of process objects corresponding to live child processes""" def cpu_count(self) -> int: - """ - Returns the number of CPUs in the system - """ + """Returns the number of CPUs in the system""" def Manager(self) -> SyncManager: - """ - Returns a manager associated with a running server process + """Returns a manager associated with a running server process The managers methods such as `Lock()`, `Condition()` and `Queue()` can be used to create shared objects. @@ -74,66 +65,42 @@ class BaseContext: # However, TypeVars scoped entirely within a return annotation is unspecified in the spec. if sys.platform != "win32": def Pipe(self, duplex: bool = True) -> tuple[Connection[Any, Any], Connection[Any, Any]]: - """ - Returns two connection object connected by a pipe - """ + """Returns two connection object connected by a pipe""" else: def Pipe(self, duplex: bool = True) -> tuple[PipeConnection[Any, Any], PipeConnection[Any, Any]]: - """ - Returns two connection object connected by a pipe - """ + """Returns two connection object connected by a pipe""" def Barrier( self, parties: int, action: Callable[..., object] | None = None, timeout: float | None = None ) -> synchronize.Barrier: - """ - Returns a barrier object - """ + """Returns a barrier object""" def BoundedSemaphore(self, value: int = 1) -> synchronize.BoundedSemaphore: - """ - Returns a bounded semaphore object - """ + """Returns a bounded semaphore object""" def Condition(self, lock: _LockLike | None = None) -> synchronize.Condition: - """ - Returns a condition object - """ + """Returns a condition object""" def Event(self) -> synchronize.Event: - """ - Returns an event object - """ + """Returns an event object""" def Lock(self) -> synchronize.Lock: - """ - Returns a non-recursive lock object - """ + """Returns a non-recursive lock object""" def RLock(self) -> synchronize.RLock: - """ - Returns a recursive lock object - """ + """Returns a recursive lock object""" def Semaphore(self, value: int = 1) -> synchronize.Semaphore: - """ - Returns a semaphore object - """ + """Returns a semaphore object""" def Queue(self, maxsize: int = 0) -> queues.Queue[Any]: - """ - Returns a queue object - """ + """Returns a queue object""" def JoinableQueue(self, maxsize: int = 0) -> queues.JoinableQueue[Any]: - """ - Returns a queue object - """ + """Returns a queue object""" def SimpleQueue(self) -> queues.SimpleQueue[Any]: - """ - Returns a queue object - """ + """Returns a queue object""" def Pool( self, @@ -142,23 +109,17 @@ class BaseContext: initargs: Iterable[Any] = (), maxtasksperchild: int | None = None, ) -> _Pool: - """ - Returns a process pool object - """ + """Returns a process pool object""" @overload def RawValue(self, typecode_or_type: type[_CT], *args: Any) -> _CT: - """ - Returns a shared object - """ + """Returns a shared object""" @overload def RawValue(self, typecode_or_type: str, *args: Any) -> Any: ... @overload def RawArray(self, typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: - """ - Returns a shared array - """ + """Returns a shared array""" @overload def RawArray(self, typecode_or_type: str, size_or_initializer: int | Sequence[Any]) -> Any: ... @@ -166,9 +127,7 @@ class BaseContext: def Value( self, typecode_or_type: type[_SimpleCData[_T]], *args: Any, lock: Literal[True] | _LockLike = True ) -> Synchronized[_T]: - """ - Returns a synchronized shared object - """ + """Returns a synchronized shared object""" @overload def Value(self, typecode_or_type: type[_CT], *args: Any, lock: Literal[False]) -> Synchronized[_CT]: ... @@ -182,9 +141,7 @@ class BaseContext: def Array( self, typecode_or_type: type[_SimpleCData[_T]], size_or_initializer: int | Sequence[Any], *, lock: Literal[False] ) -> SynchronizedArray[_T]: - """ - Returns a synchronized shared array - """ + """Returns a synchronized shared array""" @overload def Array( @@ -207,38 +164,31 @@ class BaseContext: self, typecode_or_type: str | type[_CData], size_or_initializer: int | Sequence[Any], *, lock: bool | _LockLike = True ) -> Any: ... def freeze_support(self) -> None: - """ - Check whether this is a fake forked process in a frozen executable. + """Check whether this is a fake forked process in a frozen executable. If so then run code specified by commandline and exit. """ def get_logger(self) -> Logger: - """ - Return package logger -- if it does not already exist then + """Return package logger -- if it does not already exist then it is created. """ def log_to_stderr(self, level: _LoggingLevel | None = None) -> Logger: - """ - Turn on logging and add a handler which prints to stderr - """ + """Turn on logging and add a handler which prints to stderr""" def allow_connection_pickling(self) -> None: - """ - Install support for sending connections and sockets + """Install support for sending connections and sockets between processes """ def set_executable(self, executable: str) -> None: - """ - Sets the path to a python.exe or pythonw.exe binary used to run + """Sets the path to a python.exe or pythonw.exe binary used to run child processes instead of sys.executable when using the 'spawn' start method. Useful for people embedding Python. """ def set_forkserver_preload(self, module_names: list[str]) -> None: - """ - Set list of module names to try to load in forkserver process. + """Set list of module names to try to load in forkserver process. This is really just a hint. """ if sys.platform != "win32": @@ -267,8 +217,7 @@ class BaseContext: def set_start_method(self, method: str | None, force: bool = False) -> None: ... @property def reducer(self) -> str: - """ - Controls how objects will be reduced to a form that can be + """Controls how objects will be reduced to a form that can be shared with other processes. """ @@ -286,9 +235,7 @@ class DefaultContext(BaseContext): def __init__(self, context: BaseContext) -> None: ... def get_start_method(self, allow_none: bool = False) -> str: ... def get_all_start_methods(self) -> list[str]: - """ - Returns a list of the supported start methods, default first. - """ + """Returns a list of the supported start methods, default first.""" _default_context: DefaultContext diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/forkserver.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/forkserver.pyi index b7c7f5daae..00208b1103 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/forkserver.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/forkserver.pyi @@ -11,21 +11,17 @@ SIGNED_STRUCT: Final[Struct] class ForkServer: def set_forkserver_preload(self, modules_names: list[str]) -> None: - """ - Set list of module names to try to load in forkserver process. - """ + """Set list of module names to try to load in forkserver process.""" def get_inherited_fds(self) -> list[int] | None: - """ - Return list of fds inherited from parent process. + """Return list of fds inherited from parent process. This returns None if the current process was not started by fork server. """ def connect_to_new_process(self, fds: Sequence[int]) -> tuple[int, int]: - """ - Request forkserver to create a child process. + """Request forkserver to create a child process. Returns a pair of fds (status_r, data_w). The calling process can read the child process's pid and (eventually) its returncode from status_r. @@ -34,8 +30,7 @@ class ForkServer: """ def ensure_running(self) -> None: - """ - Make sure that a fork server is running. + """Make sure that a fork server is running. This can be called from any process. Note that usually a child process will just reuse the forkserver started by its parent, so @@ -52,9 +47,7 @@ if sys.version_info >= (3, 14): *, authkey_r: int | None = None, ) -> None: - """ - Run forkserver. - """ + """Run forkserver.""" else: def main( @@ -64,9 +57,7 @@ else: main_path: str | None = None, sys_path: Unused = None, ) -> None: - """ - Run forkserver. - """ + """Run forkserver.""" def read_signed(fd: int) -> Any: ... def write_signed(fd: int, n: int) -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/heap.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/heap.pyi index dc1da4d251..83721c52f3 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/heap.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/heap.pyi @@ -8,9 +8,7 @@ from typing_extensions import TypeAlias __all__ = ["BufferWrapper"] class Arena: - """ - A shared memory area backed by a temporary file (POSIX). - """ + """A shared memory area backed by a temporary file (POSIX).""" size: int buffer: mmap diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/managers.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/managers.pyi index 0dd919d64a..852116d318 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/managers.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/managers.pyi @@ -38,9 +38,7 @@ class Namespace: _Namespace: TypeAlias = Namespace class Token: - """ - Type to uniquely identify a shared object - """ + """Type to uniquely identify a shared object""" typeid: str | bytes | None address: _Address | None @@ -50,9 +48,7 @@ class Token: def __setstate__(self, state: tuple[str | bytes | None, tuple[str | bytes, int], str | bytes | int | None]) -> None: ... class BaseProxy: - """ - A base for proxies of shared objects - """ + """A base for proxies of shared objects""" _address_to_local: dict[_Address, Any] _mutex: Any @@ -68,14 +64,10 @@ class BaseProxy: ) -> None: ... def __deepcopy__(self, memo: Any | None) -> Any: ... def _callmethod(self, methodname: str, args: tuple[Any, ...] = (), kwds: dict[Any, Any] = {}) -> None: - """ - Try to call a method of the referent and return a copy of the result - """ + """Try to call a method of the referent and return a copy of the result""" def _getvalue(self) -> Any: - """ - Get a copy of the value of the referent - """ + """Get a copy of the value of the referent""" def __reduce__(self) -> tuple[Any, tuple[Any, Any, str, dict[Any, Any]]]: ... @@ -84,8 +76,7 @@ class ValueProxy(BaseProxy, Generic[_T]): def set(self, value: _T) -> None: ... value: _T def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ @@ -117,8 +108,7 @@ if sys.version_info >= (3, 13): class DictProxy(_BaseDictProxy[_KT, _VT]): def __class_getitem__(cls, args: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ @@ -229,8 +219,7 @@ class ListProxy(BaseListProxy[_T]): def __imul__(self, value: SupportsIndex, /) -> Self: ... # type: ignore[override] if sys.version_info >= (3, 13): def __class_getitem__(cls, args: Any, /) -> Any: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ @@ -241,9 +230,7 @@ _ServerConnection: TypeAlias = Connection[tuple[str, Any], tuple[str, str, Itera # Returned by BaseManager.get_server() class Server: - """ - Server class which runs in a process controlled by a manager object - """ + """Server class which runs in a process controlled by a manager object""" address: _Address | None id_to_obj: dict[str, tuple[Any, set[str], dict[str, str]]] @@ -258,68 +245,46 @@ class Server: serializer: str, ) -> None: ... def serve_forever(self) -> None: - """ - Run the server forever - """ + """Run the server forever""" def accepter(self) -> None: ... if sys.version_info >= (3, 10): def handle_request(self, conn: _ServerConnection) -> None: - """ - Handle a new connection - """ + """Handle a new connection""" else: def handle_request(self, c: _ServerConnection) -> None: - """ - Handle a new connection - """ + """Handle a new connection""" def serve_client(self, conn: _ServerConnection) -> None: - """ - Handle requests from the proxies in a particular process/thread - """ + """Handle requests from the proxies in a particular process/thread""" def fallback_getvalue(self, conn: _ServerConnection, ident: str, obj: _T) -> _T: ... def fallback_str(self, conn: _ServerConnection, ident: str, obj: Any) -> str: ... def fallback_repr(self, conn: _ServerConnection, ident: str, obj: Any) -> str: ... def dummy(self, c: _ServerConnection) -> None: ... def debug_info(self, c: _ServerConnection) -> str: - """ - Return some info --- useful to spot problems with refcounting - """ + """Return some info --- useful to spot problems with refcounting""" def number_of_objects(self, c: _ServerConnection) -> int: - """ - Number of shared objects - """ + """Number of shared objects""" def shutdown(self, c: _ServerConnection) -> None: - """ - Shutdown this process - """ + """Shutdown this process""" def create(self, c: _ServerConnection, typeid: str, /, *args: Any, **kwds: Any) -> tuple[str, tuple[str, ...]]: - """ - Create a new shared object and return its id - """ + """Create a new shared object and return its id""" def get_methods(self, c: _ServerConnection, token: Token) -> set[str]: - """ - Return the methods of the shared object indicated by token - """ + """Return the methods of the shared object indicated by token""" def accept_connection(self, c: _ServerConnection, name: str) -> None: - """ - Spawn a new thread to serve this connection - """ + """Spawn a new thread to serve this connection""" def incref(self, c: _ServerConnection, ident: str) -> None: ... def decref(self, c: _ServerConnection, ident: str) -> None: ... class BaseManager: - """ - Base class for managers - """ + """Base class for managers""" if sys.version_info >= (3, 11): def __init__( @@ -341,24 +306,16 @@ class BaseManager: ) -> None: ... def get_server(self) -> Server: - """ - Return server object with serve_forever() method and address attribute - """ + """Return server object with serve_forever() method and address attribute""" def connect(self) -> None: - """ - Connect manager object to the server process - """ + """Connect manager object to the server process""" def start(self, initializer: Callable[..., object] | None = None, initargs: Iterable[Any] = ()) -> None: - """ - Spawn a server process for this manager object - """ + """Spawn a server process for this manager object""" shutdown: _Finalize # only available after start() was called def join(self, timeout: float | None = None) -> None: # undocumented - """ - Join the manager process (if it has been spawned) - """ + """Join the manager process (if it has been spawned)""" @property def address(self) -> _Address | None: ... @@ -372,9 +329,7 @@ class BaseManager: method_to_typeid: Mapping[str, str] | None = None, create_method: bool = True, ) -> None: - """ - Register a typeid with the manager type - """ + """Register a typeid with the manager type""" def __enter__(self) -> Self: ... def __exit__( @@ -382,8 +337,7 @@ class BaseManager: ) -> None: ... class SyncManager(BaseManager): - """ - Subclass of `BaseManager` which supports a number of shared object types. + """Subclass of `BaseManager` which supports a number of shared object types. The types registered are those intended for the synchronization of threads, plus `dict`, `list` and `Namespace`. @@ -445,25 +399,20 @@ class RemoteError(Exception): ... class SharedMemoryServer(Server): def track_segment(self, c: _ServerConnection, segment_name: str) -> None: - """ - Adds the supplied shared memory block name to Server's tracker. - """ + """Adds the supplied shared memory block name to Server's tracker.""" def release_segment(self, c: _ServerConnection, segment_name: str) -> None: - """ - Calls unlink() on the shared memory block with the supplied name + """Calls unlink() on the shared memory block with the supplied name and removes it from the tracker instance inside the Server. """ def list_segments(self, c: _ServerConnection) -> list[str]: - """ - Returns a list of names of shared memory blocks that the Server + """Returns a list of names of shared memory blocks that the Server is currently tracking. """ class SharedMemoryManager(BaseManager): - """ - Like SyncManager but uses SharedMemoryServer instead of Server. + """Like SyncManager but uses SharedMemoryServer instead of Server. It provides methods for creating and returning SharedMemory instances and for creating a list-like object (ShareableList) backed by shared @@ -473,19 +422,15 @@ class SharedMemoryManager(BaseManager): """ def get_server(self) -> SharedMemoryServer: - """ - Better than monkeypatching for now; merge into Server ultimately - """ + """Better than monkeypatching for now; merge into Server ultimately""" def SharedMemory(self, size: int) -> _SharedMemory: - """ - Returns a new SharedMemory instance with the specified size in + """Returns a new SharedMemory instance with the specified size in bytes, to be tracked by the manager. """ def ShareableList(self, sequence: Iterable[_SLT] | None) -> _ShareableList[_SLT]: - """ - Returns a new ShareableList instance populated with the values + """Returns a new ShareableList instance populated with the values from the input sequence, to be tracked by the manager. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/pool.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/pool.pyi index 40cbad8660..a228cee5f5 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/pool.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/pool.pyi @@ -18,8 +18,7 @@ class ApplyResult(Generic[_T]): def ready(self) -> bool: ... def successful(self) -> bool: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ @@ -46,9 +45,7 @@ class IMapIterator(Generic[_T]): class IMapUnorderedIterator(IMapIterator[_T]): ... class Pool: - """ - Class which supports an async version of applying functions to arguments. - """ + """Class which supports an async version of applying functions to arguments.""" def __init__( self, @@ -61,8 +58,7 @@ class Pool: @staticmethod def Process(ctx: DefaultContext, *args: Any, **kwds: Any) -> Process: ... def apply(self, func: Callable[..., _T], args: Iterable[Any] = (), kwds: Mapping[str, Any] = {}) -> _T: - """ - Equivalent of `func(*args, **kwds)`. + """Equivalent of `func(*args, **kwds)`. Pool must be running. """ @@ -74,13 +70,10 @@ class Pool: callback: Callable[[_T], object] | None = None, error_callback: Callable[[BaseException], object] | None = None, ) -> AsyncResult[_T]: - """ - Asynchronous version of `apply()` method. - """ + """Asynchronous version of `apply()` method.""" def map(self, func: Callable[[_S], _T], iterable: Iterable[_S], chunksize: int | None = None) -> list[_T]: - """ - Apply `func` to each element in `iterable`, collecting the results + """Apply `func` to each element in `iterable`, collecting the results in a list that is returned. """ @@ -92,23 +85,16 @@ class Pool: callback: Callable[[list[_T]], object] | None = None, error_callback: Callable[[BaseException], object] | None = None, ) -> MapResult[_T]: - """ - Asynchronous version of `map()` method. - """ + """Asynchronous version of `map()` method.""" def imap(self, func: Callable[[_S], _T], iterable: Iterable[_S], chunksize: int | None = 1) -> IMapIterator[_T]: - """ - Equivalent of `map()` -- can be MUCH slower than `Pool.map()`. - """ + """Equivalent of `map()` -- can be MUCH slower than `Pool.map()`.""" def imap_unordered(self, func: Callable[[_S], _T], iterable: Iterable[_S], chunksize: int | None = 1) -> IMapIterator[_T]: - """ - Like `imap()` method but ordering of results is arbitrary. - """ + """Like `imap()` method but ordering of results is arbitrary.""" def starmap(self, func: Callable[..., _T], iterable: Iterable[Iterable[Any]], chunksize: int | None = None) -> list[_T]: - """ - Like `map()` method but the elements of the `iterable` are expected to + """Like `map()` method but the elements of the `iterable` are expected to be iterables as well and will be unpacked as arguments. Hence `func` and (a, b) becomes func(a, b). """ @@ -121,9 +107,7 @@ class Pool: callback: Callable[[list[_T]], object] | None = None, error_callback: Callable[[BaseException], object] | None = None, ) -> AsyncResult[list[_T]]: - """ - Asynchronous version of `starmap()` method. - """ + """Asynchronous version of `starmap()` method.""" def close(self) -> None: ... def terminate(self) -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/popen_spawn_win32.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/popen_spawn_win32.pyi index 481b9eec5a..31ba0c6892 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/popen_spawn_win32.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/popen_spawn_win32.pyi @@ -13,6 +13,8 @@ if sys.platform == "win32": WINENV: Final[bool] class Popen: + """Start a subprocess to run the code of a process object""" + finalizer: Finalize method: ClassVar[str] pid: int diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/process.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/process.pyi index f740eb50c0..53b3acad26 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/process.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/process.pyi @@ -4,8 +4,7 @@ from typing import Any __all__ = ["BaseProcess", "current_process", "active_children", "parent_process"] class BaseProcess: - """ - Process objects represent activity that is run in a separate process + """Process objects represent activity that is run in a separate process The class is analogous to `threading.Thread` """ @@ -25,79 +24,53 @@ class BaseProcess: daemon: bool | None = None, ) -> None: ... def run(self) -> None: - """ - Method to be run in sub-process; can be overridden in sub-class - """ + """Method to be run in sub-process; can be overridden in sub-class""" def start(self) -> None: - """ - Start child process - """ + """Start child process""" def terminate(self) -> None: - """ - Terminate process; sends SIGTERM signal or uses TerminateProcess() - """ + """Terminate process; sends SIGTERM signal or uses TerminateProcess()""" def kill(self) -> None: - """ - Terminate process; sends SIGKILL signal or uses TerminateProcess() - """ + """Terminate process; sends SIGKILL signal or uses TerminateProcess()""" def close(self) -> None: - """ - Close the Process object. + """Close the Process object. This method releases resources held by the Process object. It is an error to call this method if the child process is still running. """ def join(self, timeout: float | None = None) -> None: - """ - Wait until child process terminates - """ + """Wait until child process terminates""" def is_alive(self) -> bool: - """ - Return whether process is alive - """ + """Return whether process is alive""" @property def exitcode(self) -> int | None: - """ - Return exit code of process or `None` if it has yet to stop - """ + """Return exit code of process or `None` if it has yet to stop""" @property def ident(self) -> int | None: - """ - Return identifier (PID) of process or `None` if it has yet to start - """ + """Return identifier (PID) of process or `None` if it has yet to start""" @property def pid(self) -> int | None: - """ - Return identifier (PID) of process or `None` if it has yet to start - """ + """Return identifier (PID) of process or `None` if it has yet to start""" @property def sentinel(self) -> int: - """ - Return a file descriptor (Unix) or handle (Windows) suitable for + """Return a file descriptor (Unix) or handle (Windows) suitable for waiting for process termination. """ def current_process() -> BaseProcess: - """ - Return process object representing the current process - """ + """Return process object representing the current process""" def active_children() -> list[BaseProcess]: - """ - Return list of process objects corresponding to live child processes - """ + """Return list of process objects corresponding to live child processes""" def parent_process() -> BaseProcess | None: - """ - Return process object representing the parent process - """ + """Return process object representing the parent process""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/queues.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/queues.pyi index 0bdb910e97..dfdeab7538 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/queues.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/queues.pyi @@ -22,8 +22,7 @@ class Queue(Generic[_T]): def cancel_join_thread(self) -> None: ... if sys.version_info >= (3, 12): def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ @@ -39,8 +38,7 @@ class SimpleQueue(Generic[_T]): def get(self) -> _T: ... def put(self, obj: _T) -> None: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/reduction.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/reduction.pyi index e843b09e9a..325d472f9a 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/reduction.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/reduction.pyi @@ -18,17 +18,13 @@ else: HAVE_SEND_HANDLE: Final[bool] class ForkingPickler(pickle.Pickler): - """ - Pickler subclass used by multiprocessing. - """ + """Pickler subclass used by multiprocessing.""" dispatch_table: _DispatchTableType def __init__(self, file: SupportsWrite[bytes], protocol: int | None = ...) -> None: ... @classmethod def register(cls, type: Type, reduce: Callable[[Any], _ReducedType]) -> None: - """ - Register a reduce function for a type. - """ + """Register a reduce function for a type.""" @classmethod def dumps(cls, obj: Any, protocol: int | None = None) -> memoryview: ... @@ -37,50 +33,48 @@ class ForkingPickler(pickle.Pickler): register = ForkingPickler.register def dump(obj: Any, file: SupportsWrite[bytes], protocol: int | None = None) -> None: - """ - Replacement for pickle.dump() using ForkingPickler. - """ + """Replacement for pickle.dump() using ForkingPickler.""" if sys.platform == "win32": def duplicate( handle: int, target_process: int | None = None, inheritable: bool = False, *, source_process: int | None = None - ) -> int: ... - def steal_handle(source_pid: int, handle: int) -> int: ... - def send_handle(conn: connection.PipeConnection[DupHandle, Any], handle: int, destination_pid: int) -> None: ... - def recv_handle(conn: connection.PipeConnection[Any, DupHandle]) -> int: ... + ) -> int: + """Duplicate a handle. (target_process is a handle not a pid!)""" + + def steal_handle(source_pid: int, handle: int) -> int: + """Steal a handle from process identified by source_pid.""" + + def send_handle(conn: connection.PipeConnection[DupHandle, Any], handle: int, destination_pid: int) -> None: + """Send a handle over a local connection.""" + + def recv_handle(conn: connection.PipeConnection[Any, DupHandle]) -> int: + """Receive a handle over a local connection.""" class DupHandle: + """Picklable wrapper for a handle.""" + def __init__(self, handle: int, access: int, pid: int | None = None) -> None: ... - def detach(self) -> int: ... + def detach(self) -> int: + """Get the handle. This should only be called once.""" else: if sys.version_info < (3, 14): ACKNOWLEDGE: Final[bool] def recvfds(sock: socket, size: int) -> list[int]: - """ - Receive an array of fds over an AF_UNIX socket. - """ + """Receive an array of fds over an AF_UNIX socket.""" def send_handle(conn: HasFileno, handle: int, destination_pid: Unused) -> None: - """ - Send a handle over a local connection. - """ + """Send a handle over a local connection.""" def recv_handle(conn: HasFileno) -> int: - """ - Receive a handle over a local connection. - """ + """Receive a handle over a local connection.""" def sendfds(sock: socket, fds: list[int]) -> None: - """ - Send an array of fds over an AF_UNIX socket. - """ + """Send an array of fds over an AF_UNIX socket.""" def DupFd(fd: int) -> Any: # Return type is really hard to get right - """ - Return a wrapper for an fd. - """ + """Return a wrapper for an fd.""" # These aliases are to work around pyright complaints. # Pyright doesn't like it when a class object is defined as an alias @@ -101,8 +95,7 @@ else: _DupFd = DupFd class AbstractReducer(metaclass=ABCMeta): - """ - Abstract base class for use in implementing a Reduction class + """Abstract base class for use in implementing a Reduction class suitable for use in replacing the standard reduction mechanism used in multiprocessing. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/resource_sharer.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/resource_sharer.pyi index dca0b25830..fd8a166e66 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/resource_sharer.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/resource_sharer.pyi @@ -7,24 +7,21 @@ if sys.platform == "win32": __all__ += ["DupSocket"] class DupSocket: + """Picklable wrapper for a socket.""" + def __init__(self, sock: socket) -> None: ... - def detach(self) -> socket: ... + def detach(self) -> socket: + """Get the socket. This should only be called once.""" else: __all__ += ["DupFd"] class DupFd: - """ - Wrapper for fd which can be used at any time. - """ + """Wrapper for fd which can be used at any time.""" def __init__(self, fd: int) -> None: ... def detach(self) -> int: - """ - Get the fd. This should only be called once. - """ + """Get the fd. This should only be called once.""" def stop(timeout: float | None = None) -> None: - """ - Stop the background thread and clear registered resources. - """ + """Stop the background thread and clear registered resources.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/resource_tracker.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/resource_tracker.pyi index d0fda1b23e..0f8cc7817d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/resource_tracker.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/resource_tracker.pyi @@ -7,22 +7,17 @@ __all__ = ["ensure_running", "register", "unregister"] class ResourceTracker: def getfd(self) -> int | None: ... def ensure_running(self) -> None: - """ - Make sure that resource tracker process is running. + """Make sure that resource tracker process is running. This can be run from any process. Usually a child process will use the resource created by its parent. """ def register(self, name: Sized, rtype: str) -> None: - """ - Register name of resource with resource tracker. - """ + """Register name of resource with resource tracker.""" def unregister(self, name: Sized, rtype: str) -> None: - """ - Unregister name of resource with resource tracker. - """ + """Unregister name of resource with resource tracker.""" if sys.version_info >= (3, 12): def __del__(self) -> None: ... @@ -33,6 +28,4 @@ unregister = _resource_tracker.unregister getfd = _resource_tracker.getfd def main(fd: FileDescriptorOrPath) -> None: - """ - Run resource tracker. - """ + """Run resource tracker.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/shared_memory.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/shared_memory.pyi index a8a3108fbf..470f48d39b 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/shared_memory.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/shared_memory.pyi @@ -16,8 +16,7 @@ __all__ = ["SharedMemory", "ShareableList"] _SLT = TypeVar("_SLT", int, float, bool, str, bytes, None) class SharedMemory: - """ - Creates a new shared memory block or attaches to an existing + """Creates a new shared memory block or attaches to an existing shared memory block. Every shared memory block is assigned a unique name. This enables @@ -40,31 +39,23 @@ class SharedMemory: @property def buf(self) -> memoryview: - """ - A memoryview of contents of the shared memory block. - """ + """A memoryview of contents of the shared memory block.""" @property def name(self) -> str: - """ - Unique name that identifies the shared memory block. - """ + """Unique name that identifies the shared memory block.""" @property def size(self) -> int: - """ - Size in bytes. - """ + """Size in bytes.""" def close(self) -> None: - """ - Closes access to the shared memory from this instance but does + """Closes access to the shared memory from this instance but does not destroy the shared memory block. """ def unlink(self) -> None: - """ - Requests that the underlying shared memory block be destroyed. + """Requests that the underlying shared memory block be destroyed. Unlink should be called once (and only once) across all handles which have access to the shared memory block, even if these @@ -80,8 +71,7 @@ class SharedMemory: def __del__(self) -> None: ... class ShareableList(Generic[_SLT]): - """ - Pattern for a mutable list-like object shareable via a shared + """Pattern for a mutable list-like object shareable via a shared memory block. It differs from the built-in list type in that these lists can not change their overall length (i.e. no append, insert, etc.) @@ -102,24 +92,18 @@ class ShareableList(Generic[_SLT]): def __len__(self) -> int: ... @property def format(self) -> str: - """ - The struct packing format used by all currently stored items. - """ + """The struct packing format used by all currently stored items.""" def count(self, value: _SLT) -> int: - """ - L.count(value) -> integer -- return number of occurrences of value. - """ + """L.count(value) -> integer -- return number of occurrences of value.""" def index(self, value: _SLT) -> int: - """ - L.index(value) -> integer -- return first index of value. + """L.index(value) -> integer -- return first index of value. Raises ValueError if the value is not present. """ def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/sharedctypes.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/sharedctypes.pyi index 9ebd2de2f9..7f437c7c24 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/sharedctypes.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/sharedctypes.pyi @@ -14,25 +14,19 @@ _CT = TypeVar("_CT", bound=_CData) @overload def RawValue(typecode_or_type: type[_CT], *args: Any) -> _CT: - """ - Returns a ctypes object allocated from shared memory - """ + """Returns a ctypes object allocated from shared memory""" @overload def RawValue(typecode_or_type: str, *args: Any) -> Any: ... @overload def RawArray(typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: - """ - Returns a ctypes array allocated from shared memory - """ + """Returns a ctypes array allocated from shared memory""" @overload def RawArray(typecode_or_type: str, size_or_initializer: int | Sequence[Any]) -> Any: ... @overload def Value(typecode_or_type: type[_CT], *args: Any, lock: Literal[False], ctx: BaseContext | None = None) -> _CT: - """ - Return a synchronization wrapper for a Value - """ + """Return a synchronization wrapper for a Value""" @overload def Value( @@ -50,9 +44,7 @@ def Value( def Array( typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False], ctx: BaseContext | None = None ) -> _CT: - """ - Return a synchronization wrapper for a RawArray - """ + """Return a synchronization wrapper for a RawArray""" @overload def Array( diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/spawn.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/spawn.pyi index 99f1fc3278..97d3cdb32c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/spawn.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/spawn.pyi @@ -18,40 +18,26 @@ WINSERVICE: Final[bool] def set_executable(exe: str) -> None: ... def get_executable() -> str: ... def is_forking(argv: Sequence[str]) -> bool: - """ - Return whether commandline indicates we are forking - """ + """Return whether commandline indicates we are forking""" def freeze_support() -> None: - """ - Run code for process object if this in not the main process - """ + """Run code for process object if this in not the main process""" def get_command_line(**kwds: Any) -> list[str]: - """ - Returns prefix of command line used for spawning a child process - """ + """Returns prefix of command line used for spawning a child process""" def spawn_main(pipe_handle: int, parent_pid: int | None = None, tracker_fd: int | None = None) -> None: - """ - Run code specified by data received over pipe - """ + """Run code specified by data received over pipe""" # undocumented def _main(fd: int, parent_sentinel: int) -> int: ... def get_preparation_data(name: str) -> dict[str, Any]: - """ - Return info about parent needed by child to unpickle process object - """ + """Return info about parent needed by child to unpickle process object""" old_main_modules: list[ModuleType] def prepare(data: Mapping[str, Any]) -> None: - """ - Try to get current process ready to unpickle process object - """ + """Try to get current process ready to unpickle process object""" def import_main_path(main_path: str) -> None: - """ - Set sys.modules['__main__'] to module at main_path - """ + """Set sys.modules['__main__'] to module at main_path""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/util.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/util.pyi index fefd35a607..3b4ccdc194 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/util.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/multiprocessing/util.pyi @@ -49,14 +49,10 @@ if sys.version_info >= (3, 14): def sub_warning(msg: object, *args: object) -> None: ... def get_logger() -> Logger: - """ - Returns logger used by multiprocessing - """ + """Returns logger used by multiprocessing""" def log_to_stderr(level: _LoggingLevel | None = None) -> Logger: - """ - Turn on logging and add a handler which prints to stderr - """ + """Turn on logging and add a handler which prints to stderr""" def is_abstract_socket_namespace(address: str | bytes | None) -> bool: ... @@ -66,9 +62,7 @@ def get_temp_dir() -> str: ... def register_after_fork(obj: _T, func: Callable[[_T], object]) -> None: ... class Finalize(Generic[_R_co]): - """ - Class which supports object finalization using weakrefs - """ + """Class which supports object finalization using weakrefs""" # "args" and "kwargs" are passed as arguments to "callback". @overload @@ -101,24 +95,16 @@ class Finalize(Generic[_R_co]): sub_debug: Callable[..., object] = ..., getpid: Callable[[], int] = ..., ) -> _R_co: - """ - Run the callback unless it has already been called or cancelled - """ + """Run the callback unless it has already been called or cancelled""" def cancel(self) -> None: - """ - Cancel finalization of the object - """ + """Cancel finalization of the object""" def still_active(self) -> bool: - """ - Return whether this finalizer is still waiting to invoke callback - """ + """Return whether this finalizer is still waiting to invoke callback""" def is_exiting() -> bool: - """ - Returns true if the process is shutting down - """ + """Returns true if the process is shutting down""" class ForkAwareThreadLock: acquire: Callable[[bool, float], bool] diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/netrc.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/netrc.pyi index ad4a68a6db..cd68e9a1ce 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/netrc.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/netrc.pyi @@ -9,9 +9,7 @@ from typing_extensions import TypeAlias __all__ = ["netrc", "NetrcParseError"] class NetrcParseError(Exception): - """ - Exception raised on syntax errors in the .netrc file. - """ + """Exception raised on syntax errors in the .netrc file.""" filename: str | None lineno: int | None @@ -29,6 +27,4 @@ class netrc: macros: dict[str, list[str]] def __init__(self, file: StrOrBytesPath | None = None) -> None: ... def authenticators(self, host: str) -> _NetrcTuple | None: - """ - Return a (user, account, password) tuple for given host. - """ + """Return a (user, account, password) tuple for given host.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/nis.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/nis.pyi index 10eef2336a..4b5882cb9d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/nis.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/nis.pyi @@ -1,9 +1,33 @@ +""" +This module contains functions for accessing NIS maps. +""" + import sys if sys.platform != "win32": - def cat(map: str, domain: str = ...) -> dict[str, str]: ... - def get_default_domain() -> str: ... - def maps(domain: str = ...) -> list[str]: ... - def match(key: str, map: str, domain: str = ...) -> str: ... + def cat(map: str, domain: str = ...) -> dict[str, str]: + """cat(map, domain = defaultdomain) + Returns the entire map as a dictionary. Optionally domain can be + specified but it defaults to the system default domain. + """ + + def get_default_domain() -> str: + """get_default_domain() -> str + Corresponds to the C library yp_get_default_domain() call, returning + the default NIS domain. + """ + + def maps(domain: str = ...) -> list[str]: + """maps(domain = defaultdomain) + Returns an array of all available NIS maps within a domain. If domain + is not specified it defaults to the system default domain. + """ + + def match(key: str, map: str, domain: str = ...) -> str: + """match(key, map, domain = defaultdomain) + Corresponds to the C library yp_match() call, returning the value of + key in the given map. Optionally domain can be specified but it + defaults to the system default domain. + """ class error(Exception): ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/nntplib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/nntplib.pyi index 897870a310..8987e40c3a 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/nntplib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/nntplib.pyi @@ -52,44 +52,30 @@ __all__ = [ _File: TypeAlias = IO[bytes] | bytes | str | None class NNTPError(Exception): - """ - Base class for all nntplib exceptions - """ + """Base class for all nntplib exceptions""" response: str class NNTPReplyError(NNTPError): - """ - Unexpected [123]xx reply - """ + """Unexpected [123]xx reply""" class NNTPTemporaryError(NNTPError): - """ - 4xx errors - """ + """4xx errors""" class NNTPPermanentError(NNTPError): - """ - 5xx errors - """ + """5xx errors""" class NNTPProtocolError(NNTPError): - """ - Response does not begin with [1-5] - """ + """Response does not begin with [1-5]""" class NNTPDataError(NNTPError): - """ - Error in response data - """ + """Error in response data""" NNTP_PORT: Final = 119 NNTP_SSL_PORT: Final = 563 class GroupInfo(NamedTuple): - """ - GroupInfo(group, last, first, flag) - """ + """GroupInfo(group, last, first, flag)""" group: str last: str @@ -97,17 +83,14 @@ class GroupInfo(NamedTuple): flag: str class ArticleInfo(NamedTuple): - """ - ArticleInfo(number, message_id, lines) - """ + """ArticleInfo(number, message_id, lines)""" number: int message_id: str lines: list[bytes] def decode_header(header_str: str) -> str: - """ - Takes a unicode string representing a munged header value + """Takes a unicode string representing a munged header value and decodes it as a (possibly non-ASCII) readable value. """ @@ -136,8 +119,7 @@ class NNTP: usenetrc: bool = False, timeout: float = ..., ) -> None: - """ - Initialize an instance. Arguments: + """Initialize an instance. Arguments: - host: hostname to connect to - port: port to connect to (default the standard NNTP port) - user: username to authenticate with @@ -158,39 +140,34 @@ class NNTP: def __enter__(self) -> Self: ... def __exit__(self, *args: Unused) -> None: ... def getwelcome(self) -> str: - """ - Get the welcome message from the server + """Get the welcome message from the server (this is read and squirreled away by __init__()). If the response code is 200, posting is allowed; if it 201, posting is not allowed. """ def getcapabilities(self) -> dict[str, _list[str]]: - """ - Get the server capabilities, as read by __init__(). + """Get the server capabilities, as read by __init__(). If the CAPABILITIES command is not supported, an empty dict is returned. """ def set_debuglevel(self, level: int) -> None: - """ - Set the debugging level. Argument 'level' means: + """Set the debugging level. Argument 'level' means: 0: no debugging output (default) 1: print commands and responses but not body text etc. 2: also print raw lines read and sent before stripping CR/LF """ def debug(self, level: int) -> None: - """ - Set the debugging level. Argument 'level' means: + """Set the debugging level. Argument 'level' means: 0: no debugging output (default) 1: print commands and responses but not body text etc. 2: also print raw lines read and sent before stripping CR/LF """ def capabilities(self) -> tuple[str, dict[str, _list[str]]]: - """ - Process a CAPABILITIES command. Not supported by all servers. + """Process a CAPABILITIES command. Not supported by all servers. Return: - resp: server response if successful - caps: a dictionary mapping capability names to lists of tokens @@ -198,8 +175,7 @@ class NNTP: """ def newgroups(self, date: datetime.date | datetime.datetime, *, file: _File = None) -> tuple[str, _list[str]]: - """ - Process a NEWGROUPS command. Arguments: + """Process a NEWGROUPS command. Arguments: - date: a date or datetime object Return: - resp: server response if successful @@ -207,8 +183,7 @@ class NNTP: """ def newnews(self, group: str, date: datetime.date | datetime.datetime, *, file: _File = None) -> tuple[str, _list[str]]: - """ - Process a NEWNEWS command. Arguments: + """Process a NEWNEWS command. Arguments: - group: group name or '*' - date: a date or datetime object Return: @@ -217,8 +192,7 @@ class NNTP: """ def list(self, group_pattern: str | None = None, *, file: _File = None) -> tuple[str, _list[str]]: - """ - Process a LIST or LIST ACTIVE command. Arguments: + """Process a LIST or LIST ACTIVE command. Arguments: - group_pattern: a pattern indicating which groups to query - file: Filename string or file object to store the result in Returns: @@ -227,8 +201,7 @@ class NNTP: """ def description(self, group: str) -> str: - """ - Get a description for a single group. If more than one + """Get a description for a single group. If more than one group matches ('group' is a pattern), return the first. If no group matches, return an empty string. @@ -241,13 +214,10 @@ class NNTP: """ def descriptions(self, group_pattern: str) -> tuple[str, dict[str, str]]: - """ - Get descriptions for a range of groups. - """ + """Get descriptions for a range of groups.""" def group(self, name: str) -> tuple[str, int, int, int, str]: - """ - Process a GROUP command. Argument: + """Process a GROUP command. Argument: - group: the group name Returns: - resp: server response if successful @@ -258,8 +228,7 @@ class NNTP: """ def help(self, *, file: _File = None) -> tuple[str, _list[str]]: - """ - Process a HELP command. Argument: + """Process a HELP command. Argument: - file: Filename string or file object to store the result in Returns: - resp: server response if successful @@ -268,8 +237,7 @@ class NNTP: """ def stat(self, message_spec: Any = None) -> tuple[str, int, str]: - """ - Process a STAT command. Argument: + """Process a STAT command. Argument: - message_spec: article number or message id (if not specified, the current article is selected) Returns: @@ -279,18 +247,13 @@ class NNTP: """ def next(self) -> tuple[str, int, str]: - """ - Process a NEXT command. No arguments. Return as for STAT. - """ + """Process a NEXT command. No arguments. Return as for STAT.""" def last(self) -> tuple[str, int, str]: - """ - Process a LAST command. No arguments. Return as for STAT. - """ + """Process a LAST command. No arguments. Return as for STAT.""" def head(self, message_spec: Any = None, *, file: _File = None) -> tuple[str, ArticleInfo]: - """ - Process a HEAD command. Argument: + """Process a HEAD command. Argument: - message_spec: article number or message id - file: filename string or file object to store the headers in Returns: @@ -299,8 +262,7 @@ class NNTP: """ def body(self, message_spec: Any = None, *, file: _File = None) -> tuple[str, ArticleInfo]: - """ - Process a BODY command. Argument: + """Process a BODY command. Argument: - message_spec: article number or message id - file: filename string or file object to store the body in Returns: @@ -309,8 +271,7 @@ class NNTP: """ def article(self, message_spec: Any = None, *, file: _File = None) -> tuple[str, ArticleInfo]: - """ - Process an ARTICLE command. Argument: + """Process an ARTICLE command. Argument: - message_spec: article number or message id - file: filename string or file object to store the article in Returns: @@ -319,14 +280,12 @@ class NNTP: """ def slave(self) -> str: - """ - Process a SLAVE command. Returns: + """Process a SLAVE command. Returns: - resp: server response if successful """ def xhdr(self, hdr: str, str: Any, *, file: _File = None) -> tuple[str, _list[str]]: - """ - Process an XHDR command (optional server extension). Arguments: + """Process an XHDR command (optional server extension). Arguments: - hdr: the header type (e.g. 'subject') - str: an article nr, a message id, or a range nr1-nr2 - file: Filename string or file object to store the result in @@ -336,8 +295,7 @@ class NNTP: """ def xover(self, start: int, end: int, *, file: _File = None) -> tuple[str, _list[tuple[int, dict[str, str]]]]: - """ - Process an XOVER command (optional server extension) Arguments: + """Process an XOVER command (optional server extension) Arguments: - start: start of range - end: end of range - file: Filename string or file object to store the result in @@ -349,8 +307,7 @@ class NNTP: def over( self, message_spec: None | str | _list[Any] | tuple[Any, ...], *, file: _File = None ) -> tuple[str, _list[tuple[int, dict[str, str]]]]: - """ - Process an OVER command. If the command isn't supported, fall + """Process an OVER command. If the command isn't supported, fall back to XOVER. Arguments: - message_spec: - either a message id, indicating the article to fetch @@ -368,24 +325,21 @@ class NNTP: """ def date(self) -> tuple[str, datetime.datetime]: - """ - Process the DATE command. + """Process the DATE command. Returns: - resp: server response if successful - date: datetime object """ def post(self, data: bytes | Iterable[bytes]) -> str: - """ - Process a POST command. Arguments: + """Process a POST command. Arguments: - data: bytes object, iterable or file containing the article Returns: - resp: server response if successful """ def ihave(self, message_id: Any, data: bytes | Iterable[bytes]) -> str: - """ - Process an IHAVE command. Arguments: + """Process an IHAVE command. Arguments: - message_id: message-id of the article - data: file containing the article Returns: @@ -394,15 +348,13 @@ class NNTP: """ def quit(self) -> str: - """ - Process a QUIT command and close the socket. Returns: + """Process a QUIT command and close the socket. Returns: - resp: server response if successful """ def login(self, user: str | None = None, password: str | None = None, usenetrc: bool = True) -> None: ... def starttls(self, context: ssl.SSLContext | None = None) -> None: - """ - Process a STARTTLS command. Arguments: + """Process a STARTTLS command. Arguments: - context: SSL context to use for the encrypted connection """ @@ -420,7 +372,6 @@ class NNTP_SSL(NNTP): usenetrc: bool = False, timeout: float = ..., ) -> None: - """ - This works identically to NNTP.__init__, except for the change + """This works identically to NNTP.__init__, except for the change in default port and the `ssl_context` argument for SSL connections. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/nt.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/nt.pyi index 3ed8f8af37..af6e62aabd 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/nt.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/nt.pyi @@ -1,3 +1,10 @@ +""" +This module provides access to operating system functionality that is +standardized by the C Standard and the POSIX standard (a thinly +disguised Unix interface). Refer to the library manual and +corresponding Unix manual entries for more information on calls. +""" + import sys if sys.platform == "win32": diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/ntpath.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/ntpath.pyi index 9d9b96b075..d308340865 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/ntpath.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/ntpath.pyi @@ -128,6 +128,4 @@ else: if sys.version_info >= (3, 13): def isreserved(path: StrOrBytesPath) -> bool: - """ - Return true if the pathname is reserved by the system. - """ + """Return true if the pathname is reserved by the system.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/nturl2path.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/nturl2path.pyi index 11a1cd3805..b954810abf 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/nturl2path.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/nturl2path.pyi @@ -11,27 +11,23 @@ from typing_extensions import deprecated if sys.version_info >= (3, 14): @deprecated("nturl2path module was deprecated since Python 3.14") def url2pathname(url: str) -> str: - """ - OS-specific conversion from a relative URL of the 'file' scheme + """OS-specific conversion from a relative URL of the 'file' scheme to a file system path; not recommended for general use. """ @deprecated("nturl2path module was deprecated since Python 3.14") def pathname2url(p: str) -> str: - """ - OS-specific conversion from a file system path to a relative URL + """OS-specific conversion from a file system path to a relative URL of the 'file' scheme; not recommended for general use. """ else: def url2pathname(url: str) -> str: - """ - OS-specific conversion from a relative URL of the 'file' scheme + """OS-specific conversion from a relative URL of the 'file' scheme to a file system path; not recommended for general use. """ def pathname2url(p: str) -> str: - """ - OS-specific conversion from a file system path to a relative URL + """OS-specific conversion from a file system path to a relative URL of the 'file' scheme; not recommended for general use. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/numbers.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/numbers.pyi index 990a2bbf49..fd89f33111 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/numbers.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/numbers.pyi @@ -64,8 +64,7 @@ class _IntegralLike(_RealLike, Protocol): ################# class Number(metaclass=ABCMeta): - """ - All numbers inherit from this class. + """All numbers inherit from this class. If you just want to check if an argument x is a number, without caring what kind, use isinstance(x, Number). @@ -73,15 +72,12 @@ class Number(metaclass=ABCMeta): @abstractmethod def __hash__(self) -> int: - """ - The type of the None singleton. - """ + """The type of the None singleton.""" # See comment at the top of the file # for why some of these return types are purposefully vague class Complex(Number, _ComplexLike): - """ - Complex defines the operations that work on the builtin complex type. + """Complex defines the operations that work on the builtin complex type. In short, those are: a conversion to complex, .real, .imag, +, -, *, /, **, abs(), .conjugate, ==, and !=. @@ -93,20 +89,15 @@ class Complex(Number, _ComplexLike): @abstractmethod def __complex__(self) -> complex: - """ - Return a builtin complex instance. Called for complex(self). - """ + """Return a builtin complex instance. Called for complex(self).""" def __bool__(self) -> bool: - """ - True if self != 0. Called for bool(self). - """ + """True if self != 0. Called for bool(self).""" @property @abstractmethod def real(self) -> _RealLike: - """ - Retrieve the real component of this number. + """Retrieve the real component of this number. This should subclass Real. """ @@ -114,106 +105,74 @@ class Complex(Number, _ComplexLike): @property @abstractmethod def imag(self) -> _RealLike: - """ - Retrieve the imaginary component of this number. + """Retrieve the imaginary component of this number. This should subclass Real. """ @abstractmethod def __add__(self, other) -> _ComplexLike: - """ - self + other - """ + """self + other""" @abstractmethod def __radd__(self, other) -> _ComplexLike: - """ - other + self - """ + """other + self""" @abstractmethod def __neg__(self) -> _ComplexLike: - """ - -self - """ + """-self""" @abstractmethod def __pos__(self) -> _ComplexLike: - """ - +self - """ + """+self""" def __sub__(self, other) -> _ComplexLike: - """ - self - other - """ + """self - other""" def __rsub__(self, other) -> _ComplexLike: - """ - other - self - """ + """other - self""" @abstractmethod def __mul__(self, other) -> _ComplexLike: - """ - self * other - """ + """self * other""" @abstractmethod def __rmul__(self, other) -> _ComplexLike: - """ - other * self - """ + """other * self""" @abstractmethod def __truediv__(self, other) -> _ComplexLike: - """ - self / other: Should promote to float when necessary. - """ + """self / other: Should promote to float when necessary.""" @abstractmethod def __rtruediv__(self, other) -> _ComplexLike: - """ - other / self - """ + """other / self""" @abstractmethod def __pow__(self, exponent) -> _ComplexLike: - """ - self ** exponent; should promote to float or complex when necessary. - """ + """self ** exponent; should promote to float or complex when necessary.""" @abstractmethod def __rpow__(self, base) -> _ComplexLike: - """ - base ** self - """ + """base ** self""" @abstractmethod def __abs__(self) -> _RealLike: - """ - Returns the Real distance from 0. Called for abs(self). - """ + """Returns the Real distance from 0. Called for abs(self).""" @abstractmethod def conjugate(self) -> _ComplexLike: - """ - (x+y*i).conjugate() returns (x-y*i). - """ + """(x+y*i).conjugate() returns (x-y*i).""" @abstractmethod def __eq__(self, other: object) -> bool: - """ - self == other - """ + """self == other""" __hash__: ClassVar[None] # type: ignore[assignment] # See comment at the top of the file # for why some of these return types are purposefully vague class Real(Complex, _RealLike): - """ - To Complex, Real adds the operations that work on real numbers. + """To Complex, Real adds the operations that work on real numbers. In short, those are: a conversion to float, trunc(), divmod, %, <, <=, >, and >=. @@ -223,16 +182,14 @@ class Real(Complex, _RealLike): @abstractmethod def __float__(self) -> float: - """ - Any Real can be converted to a native float object. + """Any Real can be converted to a native float object. Called for float(self). """ @abstractmethod def __trunc__(self) -> _IntegralLike: - """ - trunc(self): Truncates self to an Integral. + """trunc(self): Truncates self to an Integral. Returns an Integral i such that: * i > 0 iff self > 0; @@ -244,21 +201,16 @@ class Real(Complex, _RealLike): @abstractmethod def __floor__(self) -> _IntegralLike: - """ - Finds the greatest Integral <= self. - """ + """Finds the greatest Integral <= self.""" @abstractmethod def __ceil__(self) -> _IntegralLike: - """ - Finds the least Integral >= self. - """ + """Finds the least Integral >= self.""" @abstractmethod @overload def __round__(self, ndigits: None = None) -> _IntegralLike: - """ - Rounds self to ndigits decimal places, defaulting to 0. + """Rounds self to ndigits decimal places, defaulting to 0. If ndigits is omitted or None, returns an Integral, otherwise returns a Real. Rounds half toward even. @@ -268,16 +220,14 @@ class Real(Complex, _RealLike): @overload def __round__(self, ndigits: int) -> _RealLike: ... def __divmod__(self, other) -> tuple[_RealLike, _RealLike]: - """ - divmod(self, other): The pair (self // other, self % other). + """divmod(self, other): The pair (self // other, self % other). Sometimes this can be computed faster than the pair of operations. """ def __rdivmod__(self, other) -> tuple[_RealLike, _RealLike]: - """ - divmod(other, self): The pair (other // self, other % self). + """divmod(other, self): The pair (other // self, other % self). Sometimes this can be computed faster than the pair of operations. @@ -285,83 +235,58 @@ class Real(Complex, _RealLike): @abstractmethod def __floordiv__(self, other) -> _RealLike: - """ - self // other: The floor() of self/other. - """ + """self // other: The floor() of self/other.""" @abstractmethod def __rfloordiv__(self, other) -> _RealLike: - """ - other // self: The floor() of other/self. - """ + """other // self: The floor() of other/self.""" @abstractmethod def __mod__(self, other) -> _RealLike: - """ - self % other - """ + """self % other""" @abstractmethod def __rmod__(self, other) -> _RealLike: - """ - other % self - """ + """other % self""" @abstractmethod def __lt__(self, other) -> bool: - """ - self < other + """self < other < on Reals defines a total ordering, except perhaps for NaN. """ @abstractmethod def __le__(self, other) -> bool: - """ - self <= other - """ + """self <= other""" def __complex__(self) -> complex: - """ - complex(self) == complex(float(self), 0) - """ + """complex(self) == complex(float(self), 0)""" @property def real(self) -> _RealLike: - """ - Real numbers are their real component. - """ + """Real numbers are their real component.""" @property def imag(self) -> Literal[0]: - """ - Real numbers have no imaginary component. - """ + """Real numbers have no imaginary component.""" def conjugate(self) -> _RealLike: - """ - Conjugate is a no-op for Reals. - """ + """Conjugate is a no-op for Reals.""" # Not actually overridden at runtime, # but we override these in the stub to give them more precise return types: @abstractmethod def __pos__(self) -> _RealLike: - """ - +self - """ + """+self""" @abstractmethod def __neg__(self) -> _RealLike: - """ - -self - """ + """-self""" # See comment at the top of the file # for why some of these return types are purposefully vague class Rational(Real): - """ - .numerator and .denominator should be in lowest terms. - """ + """.numerator and .denominator should be in lowest terms.""" @property @abstractmethod @@ -370,8 +295,7 @@ class Rational(Real): @abstractmethod def denominator(self) -> _IntegralLike: ... def __float__(self) -> float: - """ - float(self) = self.numerator / self.denominator + """float(self) = self.numerator / self.denominator It's important that this conversion use the integer's "true" division rather than casting one side to float before dividing @@ -381,8 +305,7 @@ class Rational(Real): # See comment at the top of the file # for why some of these return types are purposefully vague class Integral(Rational, _IntegralLike): - """ - Integral adds methods that work on integral numbers. + """Integral adds methods that work on integral numbers. In short, these are conversion to int, pow with modulus, and the bit-string operations. @@ -390,19 +313,14 @@ class Integral(Rational, _IntegralLike): @abstractmethod def __int__(self) -> int: - """ - int(self) - """ + """int(self)""" def __index__(self) -> int: - """ - Called whenever an index is needed, such as in slicing - """ + """Called whenever an index is needed, such as in slicing""" @abstractmethod def __pow__(self, exponent, modulus=None) -> _IntegralLike: - """ - self ** exponent % modulus, but maybe faster. + """self ** exponent % modulus, but maybe faster. Accept the modulus argument if you want to support the 3-argument version of pow(). Raise a TypeError if exponent < 0 @@ -412,111 +330,76 @@ class Integral(Rational, _IntegralLike): @abstractmethod def __lshift__(self, other) -> _IntegralLike: - """ - self << other - """ + """self << other""" @abstractmethod def __rlshift__(self, other) -> _IntegralLike: - """ - other << self - """ + """other << self""" @abstractmethod def __rshift__(self, other) -> _IntegralLike: - """ - self >> other - """ + """self >> other""" @abstractmethod def __rrshift__(self, other) -> _IntegralLike: - """ - other >> self - """ + """other >> self""" @abstractmethod def __and__(self, other) -> _IntegralLike: - """ - self & other - """ + """self & other""" @abstractmethod def __rand__(self, other) -> _IntegralLike: - """ - other & self - """ + """other & self""" @abstractmethod def __xor__(self, other) -> _IntegralLike: - """ - self ^ other - """ + """self ^ other""" @abstractmethod def __rxor__(self, other) -> _IntegralLike: - """ - other ^ self - """ + """other ^ self""" @abstractmethod def __or__(self, other) -> _IntegralLike: - """ - self | other - """ + """self | other""" @abstractmethod def __ror__(self, other) -> _IntegralLike: - """ - other | self - """ + """other | self""" @abstractmethod def __invert__(self) -> _IntegralLike: - """ - ~self - """ + """~self""" def __float__(self) -> float: - """ - float(self) == float(int(self)) - """ + """float(self) == float(int(self))""" @property def numerator(self) -> _IntegralLike: - """ - Integers are their own numerators. - """ + """Integers are their own numerators.""" @property def denominator(self) -> Literal[1]: - """ - Integers have a denominator of 1. - """ + """Integers have a denominator of 1.""" # Not actually overridden at runtime, # but we override these in the stub to give them more precise return types: @abstractmethod def __pos__(self) -> _IntegralLike: - """ - +self - """ + """+self""" @abstractmethod def __neg__(self) -> _IntegralLike: - """ - -self - """ + """-self""" @abstractmethod def __abs__(self) -> _IntegralLike: - """ - Returns the Real distance from 0. Called for abs(self). - """ + """Returns the Real distance from 0. Called for abs(self).""" @abstractmethod @overload def __round__(self, ndigits: None = None) -> _IntegralLike: - """ - Rounds self to ndigits decimal places, defaulting to 0. + """Rounds self to ndigits decimal places, defaulting to 0. If ndigits is omitted or None, returns an Integral, otherwise returns a Real. Rounds half toward even. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/opcode.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/opcode.pyi index ac9468adfb..42a1c181a0 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/opcode.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/opcode.pyi @@ -1,4 +1,5 @@ """ + opcode module - potentially shared between dis and other modules which operate on bytecodes (e.g. peephole optimizers). """ @@ -50,6 +51,4 @@ HAVE_ARGUMENT: int EXTENDED_ARG: int def stack_effect(opcode: int, oparg: int | None = None, /, *, jump: bool | None = None) -> int: - """ - Compute the stack effect of the opcode. - """ + """Compute the stack effect of the opcode.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/operator.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/operator.pyi index c8de127a12..ad6b3bb9c3 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/operator.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/operator.pyi @@ -192,8 +192,7 @@ if sys.version_info >= (3, 11): # them here. @final class attrgetter(Generic[_T_co]): - """ - Return a callable object that fetches the given attribute(s) from its operand. + """Return a callable object that fetches the given attribute(s) from its operand. After f = attrgetter('name'), the call f(r) returns r.name. After g = attrgetter('name', 'date'), the call g(r) returns (r.name, r.date). After h = attrgetter('name.first', 'name.last'), the call h(r) returns @@ -211,14 +210,11 @@ class attrgetter(Generic[_T_co]): @overload def __new__(cls, attr: str, /, *attrs: str) -> attrgetter[tuple[Any, ...]]: ... def __call__(self, obj: Any, /) -> _T_co: - """ - Call self as a function. - """ + """Call self as a function.""" @final class itemgetter(Generic[_T_co]): - """ - Return a callable object that fetches the given item(s) from its operand. + """Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]) """ @@ -235,14 +231,11 @@ class itemgetter(Generic[_T_co]): # A suspected mypy issue prevents using [..., _T] instead of [..., Any] here. # https://github.com/python/mypy/issues/14032 def __call__(self, obj: SupportsGetItem[Any, Any]) -> Any: - """ - Call self as a function. - """ + """Call self as a function.""" @final class methodcaller: - """ - Return a callable object that calls the given method on its operand. + """Return a callable object that calls the given method on its operand. After f = methodcaller('name'), the call f(r) returns r.name(). After g = methodcaller('name', 'date', foo=1), the call g(r) returns r.name('date', foo=1). @@ -250,6 +243,4 @@ class methodcaller: def __new__(cls, name: str, /, *args: Any, **kwargs: Any) -> Self: ... def __call__(self, obj: Any) -> Any: - """ - Call self as a function. - """ + """Call self as a function.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/optparse.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/optparse.pyi index 019a5c1de4..7c7b46000c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/optparse.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/optparse.pyi @@ -62,24 +62,19 @@ class OptParseError(Exception): def __init__(self, msg: str) -> None: ... class BadOptionError(OptParseError): - """ - Raised if an invalid option is seen on the command line. - """ + """Raised if an invalid option is seen on the command line.""" opt_str: str def __init__(self, opt_str: str) -> None: ... class AmbiguousOptionError(BadOptionError): - """ - Raised if an ambiguous option is seen on the command line. - """ + """Raised if an ambiguous option is seen on the command line.""" possibilities: Iterable[str] def __init__(self, opt_str: str, possibilities: Sequence[str]) -> None: ... class OptionError(OptParseError): - """ - Raised if an Option instance is created with invalid or + """Raised if an Option instance is created with invalid or inconsistent arguments. """ @@ -87,19 +82,15 @@ class OptionError(OptParseError): def __init__(self, msg: str, option: Option) -> None: ... class OptionConflictError(OptionError): - """ - Raised if conflicting options are added to an OptionParser. - """ + """Raised if conflicting options are added to an OptionParser.""" class OptionValueError(OptParseError): - """ - Raised if an invalid option value is encountered on the command + """Raised if an invalid option value is encountered on the command line. """ class HelpFormatter: - """ - Abstract base class for formatting option help. OptionParser + """Abstract base class for formatting option help. OptionParser instances should use one of the HelpFormatter subclasses for formatting help; by default IndentedHelpFormatter is used. @@ -164,9 +155,7 @@ class HelpFormatter: def format_heading(self, heading: str) -> str: ... def format_option(self, option: Option) -> str: ... def format_option_strings(self, option: Option) -> str: - """ - Return a comma-separated list of option strings & metavariables. - """ + """Return a comma-separated list of option strings & metavariables.""" @abstractmethod def format_usage(self, usage: str) -> str: ... @@ -177,9 +166,7 @@ class HelpFormatter: def store_option_strings(self, parser: OptionParser) -> None: ... class IndentedHelpFormatter(HelpFormatter): - """ - Format help with indented section bodies. - """ + """Format help with indented section bodies.""" def __init__( self, @@ -192,9 +179,7 @@ class IndentedHelpFormatter(HelpFormatter): def format_usage(self, usage: str) -> str: ... class TitledHelpFormatter(HelpFormatter): - """ - Format help with underlined section headers. - """ + """Format help with underlined section headers.""" def __init__( self, @@ -207,23 +192,22 @@ class TitledHelpFormatter(HelpFormatter): def format_usage(self, usage: str) -> str: ... class Option: - """ - Instance attributes: - _short_opts : [string] - _long_opts : [string] + """Instance attributes: + _short_opts : [string] + _long_opts : [string] - action : string - type : string - dest : string - default : any - nargs : int - const : any - choices : [string] - callback : function - callback_args : (any*) - callback_kwargs : { string : any } - help : string - metavar : string + action : string + type : string + dest : string + default : any + nargs : int + const : any + choices : [string] + callback : function + callback_args : (any*) + callback_kwargs : { string : any } + help : string + metavar : string """ ACTIONS: tuple[str, ...] @@ -290,8 +274,7 @@ class Option: make_option = Option class OptionContainer: - """ - Abstract base class. + """Abstract base class. Class attributes: standard_option_list : [Option] @@ -333,8 +316,7 @@ class OptionContainer: def _share_option_mappings(self, parser: OptionParser) -> None: ... @overload def add_option(self, opt: Option, /) -> Option: - """ - add_option(Option) + """add_option(Option) add_option(opt_str, ..., kwarg=val, ...) """ @@ -360,9 +342,7 @@ class OptionContainer: ) -> Option: ... def add_options(self, option_list: Iterable[Option]) -> None: ... def destroy(self) -> None: - """ - see OptionParser.destroy(). - """ + """see OptionParser.destroy().""" def format_option_help(self, formatter: HelpFormatter) -> str: ... def format_description(self, formatter: HelpFormatter) -> str: ... @@ -386,16 +366,14 @@ class Values: def __init__(self, defaults: Mapping[str, object] | None = None) -> None: ... def _update(self, dict: Mapping[str, object], mode: Literal["careful", "loose"]) -> None: ... def _update_careful(self, dict: Mapping[str, object]) -> None: - """ - Update the option values from an arbitrary dictionary, but only + """Update the option values from an arbitrary dictionary, but only use keys from dict that already have a corresponding attribute in self. Any keys in dict without a corresponding attribute are silently ignored. """ def _update_loose(self, dict: Mapping[str, object]) -> None: - """ - Update the option values from an arbitrary dictionary, + """Update the option values from an arbitrary dictionary, using all keys from the dictionary regardless of whether they have a corresponding attribute in self or not. """ @@ -412,8 +390,7 @@ class Values: def __eq__(self, other: object) -> bool: ... class OptionParser(OptionContainer): - """ - Class attributes: + """Class attributes: standard_option_list : [Option] list of standard options that will be accepted by all instances of this parser class (intended to be overridden by subclasses). @@ -512,8 +489,7 @@ class OptionParser(OptionContainer): def _get_args(self, args: list[str] | None) -> list[str]: ... def _init_parsing_state(self) -> None: ... def _match_long_opt(self, opt: str) -> str: - """ - _match_long_opt(opt : string) -> string + """_match_long_opt(opt : string) -> string Determine which long option string 'opt' matches, ie. which one it is an unambiguous abbreviation for. Raises BadOptionError if @@ -522,8 +498,7 @@ class OptionParser(OptionContainer): def _populate_option_list(self, option_list: Iterable[Option] | None, add_help: bool = True) -> None: ... def _process_args(self, largs: list[str], rargs: list[str], values: Values) -> None: - """ - _process_args(largs : [string], + """_process_args(largs : [string], rargs : [string], values : Values) @@ -540,8 +515,7 @@ class OptionParser(OptionContainer): @overload def add_option_group(self, title: str, /, description: str | None = None) -> OptionGroup: ... def check_values(self, values: Values, args: list[str]) -> tuple[Values, list[str]]: - """ - check_values(values : Values, args : [string]) + """check_values(values : Values, args : [string]) -> (values : Values, args : [string]) Check that the supplied option values and leftover arguments are @@ -552,16 +526,14 @@ class OptionParser(OptionContainer): """ def disable_interspersed_args(self) -> None: - """ - Set parsing to stop on the first non-option. Use this if + """Set parsing to stop on the first non-option. Use this if you have a command processor which runs another command that has options of its own and you want to make sure these options don't get confused. """ def enable_interspersed_args(self) -> None: - """ - Set parsing to not stop on the first non-option, allowing + """Set parsing to not stop on the first non-option, allowing interspersing switches with command arguments. This is the default behavior. See also disable_interspersed_args() and the class documentation description of the attribute @@ -569,8 +541,7 @@ class OptionParser(OptionContainer): """ def error(self, msg: str) -> NoReturn: - """ - error(msg : string) + """error(msg : string) Print a usage message incorporating 'msg' to stderr and exit. If you override this in a subclass, it should not return -- it @@ -588,8 +559,7 @@ class OptionParser(OptionContainer): def get_usage(self) -> str: ... def get_version(self) -> str: ... def parse_args(self, args: list[str] | None = None, values: Values | None = None) -> tuple[Values, list[str]]: - """ - parse_args(args : [string] = sys.argv[1:], + """parse_args(args : [string] = sys.argv[1:], values : Values = None) -> (values : Values, args : [string]) @@ -603,8 +573,7 @@ class OptionParser(OptionContainer): """ def print_usage(self, file: SupportsWrite[str] | None = None) -> None: - """ - print_usage(file : file = stdout) + """print_usage(file : file = stdout) Print the usage message for the current program (self.usage) to 'file' (default stdout). Any occurrence of the string "%prog" in @@ -614,16 +583,14 @@ class OptionParser(OptionContainer): """ def print_help(self, file: SupportsWrite[str] | None = None) -> None: - """ - print_help(file : file = stdout) + """print_help(file : file = stdout) Print an extended help message, listing all options and any help text provided with them, to 'file' (default stdout). """ def print_version(self, file: SupportsWrite[str] | None = None) -> None: - """ - print_version(file : file = stdout) + """print_version(file : file = stdout) Print the version message for this program (self.version) to 'file' (default stdout). As with print_usage(), any occurrence diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/os/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/os/__init__.pyi index 6ce0f2273d..252792d7da 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/os/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/os/__init__.pyi @@ -798,8 +798,7 @@ TMP_MAX: int # Undocumented, but used by tempfile # ----- os classes (structures) ----- @final class stat_result(structseq[float], tuple[int, int, int, int, int, int, int, float, float, float]): - """ - stat_result: Result from stat, fstat, or lstat. + """stat_result: Result from stat, fstat, or lstat. This object may be accessed either as a tuple of (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) @@ -826,57 +825,39 @@ class stat_result(structseq[float], tuple[int, int, int, int, int, int, int, flo @property def st_mode(self) -> int: # protection bits, - """ - protection bits - """ + """protection bits""" @property def st_ino(self) -> int: # inode number, - """ - inode - """ + """inode""" @property def st_dev(self) -> int: # device, - """ - device - """ + """device""" @property def st_nlink(self) -> int: # number of hard links, - """ - number of hard links - """ + """number of hard links""" @property def st_uid(self) -> int: # user id of owner, - """ - user ID of owner - """ + """user ID of owner""" @property def st_gid(self) -> int: # group id of owner, - """ - group ID of owner - """ + """group ID of owner""" @property def st_size(self) -> int: # size of file, in bytes, - """ - total size, in bytes - """ + """total size, in bytes""" @property def st_atime(self) -> float: # time of most recent access, - """ - time of last access - """ + """time of last access""" @property def st_mtime(self) -> float: # time of most recent content modification, - """ - time of last modification - """ + """time of last modification""" # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) if sys.version_info >= (3, 12) and sys.platform == "win32": @property @@ -886,33 +867,23 @@ Use st_birthtime instead to retrieve the file creation time. \ In the future, this property will contain the last metadata change time.""" ) def st_ctime(self) -> float: - """ - time of last change - """ + """time of last change""" else: @property def st_ctime(self) -> float: - """ - time of last change - """ + """time of last change""" @property def st_atime_ns(self) -> int: # time of most recent access, in nanoseconds - """ - time of last access in nanoseconds - """ + """time of last access in nanoseconds""" @property def st_mtime_ns(self) -> int: # time of most recent content modification in nanoseconds - """ - time of last modification in nanoseconds - """ + """time of last modification in nanoseconds""" # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) in nanoseconds @property def st_ctime_ns(self) -> int: - """ - time of last change in nanoseconds - """ + """time of last change in nanoseconds""" if sys.platform == "win32": @property def st_file_attributes(self) -> int: ... @@ -926,21 +897,15 @@ In the future, this property will contain the last metadata change time.""" else: @property def st_blocks(self) -> int: # number of blocks allocated for file - """ - number of blocks allocated - """ + """number of blocks allocated""" @property def st_blksize(self) -> int: # filesystem blocksize - """ - blocksize for filesystem I/O - """ + """blocksize for filesystem I/O""" @property def st_rdev(self) -> int: # type of device if an inode device - """ - device type (if inode device) - """ + """device type (if inode device)""" if sys.platform != "linux": # These properties are available on MacOS, but not Ubuntu. # On other Unix systems (such as FreeBSD), the following attributes may be @@ -960,20 +925,15 @@ In the future, this property will contain the last metadata change time.""" # on the allowlist for use as a Protocol starting in 3.14. @runtime_checkable class PathLike(ABC, Protocol[AnyStr_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] - """ - Abstract base class for implementing the file system path protocol. - """ + """Abstract base class for implementing the file system path protocol.""" @abstractmethod def __fspath__(self) -> AnyStr_co: - """ - Return the file system path representation of the object. - """ + """Return the file system path representation of the object.""" @overload def listdir(path: StrPath | None = None) -> list[str]: - """ - Return a list containing the names of the files in the directory. + """Return a list containing the names of the files in the directory. path can be specified as either str, bytes, or a path-like object. If path is bytes, the filenames returned will also be bytes; in all other circumstances @@ -998,60 +958,39 @@ class DirEntry(Generic[AnyStr]): @property def name(self) -> AnyStr: - """ - the entry's base filename, relative to scandir() "path" argument - """ + """the entry's base filename, relative to scandir() "path" argument""" @property def path(self) -> AnyStr: - """ - the entry's full path name; equivalent to os.path.join(scandir_path, entry.name) - """ + """the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)""" def inode(self) -> int: - """ - Return inode of the entry; cached per entry. - """ + """Return inode of the entry; cached per entry.""" def is_dir(self, *, follow_symlinks: bool = True) -> bool: - """ - Return True if the entry is a directory; cached per entry. - """ + """Return True if the entry is a directory; cached per entry.""" def is_file(self, *, follow_symlinks: bool = True) -> bool: - """ - Return True if the entry is a file; cached per entry. - """ + """Return True if the entry is a file; cached per entry.""" def is_symlink(self) -> bool: - """ - Return True if the entry is a symbolic link; cached per entry. - """ + """Return True if the entry is a symbolic link; cached per entry.""" def stat(self, *, follow_symlinks: bool = True) -> stat_result: - """ - Return stat_result object for the entry; cached per entry. - """ + """Return stat_result object for the entry; cached per entry.""" def __fspath__(self) -> AnyStr: - """ - Returns the path for the entry. - """ + """Returns the path for the entry.""" def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" if sys.version_info >= (3, 12): def is_junction(self) -> bool: - """ - Return True if the entry is a junction; cached per entry. - """ + """Return True if the entry is a junction; cached per entry.""" @final class statvfs_result(structseq[int], tuple[int, int, int, int, int, int, int, int, int, int, int]): - """ - statvfs_result: Result from statvfs or fstatvfs. + """statvfs_result: Result from statvfs or fstatvfs. This object may be accessed either as a tuple of (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax), @@ -1099,16 +1038,14 @@ class statvfs_result(structseq[int], tuple[int, int, int, int, int, int, int, in # ----- os function stubs ----- def fsencode(filename: StrOrBytesPath) -> bytes: - """ - Encode filename (an os.PathLike, bytes, or str) to the filesystem + """Encode filename (an os.PathLike, bytes, or str) to the filesystem encoding with 'surrogateescape' error handler, return bytes unchanged. On Windows, use 'strict' error handler if the file system encoding is 'mbcs' (which is the default encoding). """ def fsdecode(filename: StrOrBytesPath) -> str: - """ - Decode filename (an os.PathLike, bytes, or str) from the filesystem + """Decode filename (an os.PathLike, bytes, or str) from the filesystem encoding with 'surrogateescape' error handler, return str unchanged. On Windows, use 'strict' error handler if the file system encoding is 'mbcs' (which is the default encoding). @@ -1116,8 +1053,7 @@ def fsdecode(filename: StrOrBytesPath) -> str: @overload def fspath(path: str) -> str: - """ - Return the file system path representation of the object. + """Return the file system path representation of the object. If the object is str or bytes, then allow it to pass through as-is. If the object defines __fspath__(), then return the result of that method. All other @@ -1129,8 +1065,7 @@ def fspath(path: bytes) -> bytes: ... @overload def fspath(path: PathLike[AnyStr]) -> AnyStr: ... def get_exec_path(env: Mapping[str, str] | None = None) -> list[str]: - """ - Returns the sequence of directories that will be searched for the + """Returns the sequence of directories that will be searched for the named executable (similar to a shell) when launching a process. *env* must be an environment variable dict or None. If *env* is None, @@ -1138,37 +1073,27 @@ def get_exec_path(env: Mapping[str, str] | None = None) -> list[str]: """ def getlogin() -> str: - """ - Return the actual login name. - """ + """Return the actual login name.""" def getpid() -> int: - """ - Return the current process id. - """ + """Return the current process id.""" def getppid() -> int: - """ - Return the parent's process id. + """Return the parent's process id. If the parent process has already exited, Windows machines will still return its id; others systems will return the id of the 'init' process (1). """ def strerror(code: int, /) -> str: - """ - Translate an error code to a message string. - """ + """Translate an error code to a message string.""" def umask(mask: int, /) -> int: - """ - Set the current numeric umask and return the previous umask. - """ + """Set the current numeric umask and return the previous umask.""" @final class uname_result(structseq[str], tuple[str, str, str, str, str]): - """ - uname_result: Result from os.uname(). + """uname_result: Result from os.uname(). This object may be accessed either as a tuple of (sysname, nodename, release, version, machine), @@ -1182,58 +1107,39 @@ class uname_result(structseq[str], tuple[str, str, str, str, str]): @property def sysname(self) -> str: - """ - operating system name - """ + """operating system name""" @property def nodename(self) -> str: - """ - name of machine on network (implementation-defined) - """ + """name of machine on network (implementation-defined)""" @property def release(self) -> str: - """ - operating system release - """ + """operating system release""" @property def version(self) -> str: - """ - operating system version - """ + """operating system version""" @property def machine(self) -> str: - """ - hardware identifier - """ + """hardware identifier""" if sys.platform != "win32": def ctermid() -> str: - """ - Return the name of the controlling terminal for this process. - """ + """Return the name of the controlling terminal for this process.""" def getegid() -> int: - """ - Return the current process's effective group id. - """ + """Return the current process's effective group id.""" def geteuid() -> int: - """ - Return the current process's effective user id. - """ + """Return the current process's effective user id.""" def getgid() -> int: - """ - Return the current process's group id. - """ + """Return the current process's group id.""" def getgrouplist(user: str, group: int, /) -> list[int]: - """ - Returns a list of groups to which a user belongs. + """Returns a list of groups to which a user belongs. user username to lookup @@ -1242,13 +1148,10 @@ if sys.platform != "win32": """ def getgroups() -> list[int]: # Unix only, behaves differently on Mac - """ - Return list of supplemental group IDs for the process. - """ + """Return list of supplemental group IDs for the process.""" def initgroups(username: str, gid: int, /) -> None: - """ - Initialize the group access list. + """Initialize the group access list. Call the system initgroups() to initialize the group access list with all of the groups of which the specified username is a member, plus the specified @@ -1256,108 +1159,67 @@ if sys.platform != "win32": """ def getpgid(pid: int) -> int: - """ - Call the system call getpgid(), and return the result. - """ + """Call the system call getpgid(), and return the result.""" def getpgrp() -> int: - """ - Return the current process group id. - """ + """Return the current process group id.""" def getpriority(which: int, who: int) -> int: - """ - Return program scheduling priority. - """ + """Return program scheduling priority.""" def setpriority(which: int, who: int, priority: int) -> None: - """ - Set program scheduling priority. - """ + """Set program scheduling priority.""" if sys.platform != "darwin": def getresuid() -> tuple[int, int, int]: - """ - Return a tuple of the current process's real, effective, and saved user ids. - """ + """Return a tuple of the current process's real, effective, and saved user ids.""" def getresgid() -> tuple[int, int, int]: - """ - Return a tuple of the current process's real, effective, and saved group ids. - """ + """Return a tuple of the current process's real, effective, and saved group ids.""" def getuid() -> int: - """ - Return the current process's user id. - """ + """Return the current process's user id.""" def setegid(egid: int, /) -> None: - """ - Set the current process's effective group id. - """ + """Set the current process's effective group id.""" def seteuid(euid: int, /) -> None: - """ - Set the current process's effective user id. - """ + """Set the current process's effective user id.""" def setgid(gid: int, /) -> None: - """ - Set the current process's group id. - """ + """Set the current process's group id.""" def setgroups(groups: Sequence[int], /) -> None: - """ - Set the groups of the current process to list. - """ + """Set the groups of the current process to list.""" def setpgrp() -> None: - """ - Make the current process the leader of its process group. - """ + """Make the current process the leader of its process group.""" def setpgid(pid: int, pgrp: int, /) -> None: - """ - Call the system call setpgid(pid, pgrp). - """ + """Call the system call setpgid(pid, pgrp).""" def setregid(rgid: int, egid: int, /) -> None: - """ - Set the current process's real and effective group ids. - """ + """Set the current process's real and effective group ids.""" if sys.platform != "darwin": def setresgid(rgid: int, egid: int, sgid: int, /) -> None: - """ - Set the current process's real, effective, and saved group ids. - """ + """Set the current process's real, effective, and saved group ids.""" def setresuid(ruid: int, euid: int, suid: int, /) -> None: - """ - Set the current process's real, effective, and saved user ids. - """ + """Set the current process's real, effective, and saved user ids.""" def setreuid(ruid: int, euid: int, /) -> None: - """ - Set the current process's real and effective user ids. - """ + """Set the current process's real and effective user ids.""" def getsid(pid: int, /) -> int: - """ - Call the system call getsid(pid) and return the result. - """ + """Call the system call getsid(pid) and return the result.""" def setsid() -> None: - """ - Call the system call setsid(). - """ + """Call the system call setsid().""" def setuid(uid: int, /) -> None: - """ - Set the current process's user id. - """ + """Set the current process's user id.""" def uname() -> uname_result: - """ - Return an object identifying the current operating system. + """Return an object identifying the current operating system. The object behaves like a named tuple with the following fields: (sysname, nodename, release, version, machine) @@ -1365,8 +1227,7 @@ if sys.platform != "win32": @overload def getenv(key: str) -> str | None: - """ - Get an environment variable, return None if it doesn't exist. + """Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default. key, default and the result are str. """ @@ -1377,8 +1238,7 @@ def getenv(key: str, default: _T) -> str | _T: ... if sys.platform != "win32": @overload def getenvb(key: bytes) -> bytes | None: - """ - Get an environment variable, return None if it doesn't exist. + """Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default. key, default and the result are bytes. """ @@ -1386,18 +1246,17 @@ if sys.platform != "win32": @overload def getenvb(key: bytes, default: _T) -> bytes | _T: ... def putenv(name: StrOrBytesPath, value: StrOrBytesPath, /) -> None: - """ - Change or add an environment variable. - """ + """Change or add an environment variable.""" def unsetenv(name: StrOrBytesPath, /) -> None: - """ - Delete an environment variable. - """ + """Delete an environment variable.""" else: - def putenv(name: str, value: str, /) -> None: ... - def unsetenv(name: str, /) -> None: ... + def putenv(name: str, value: str, /) -> None: + """Change or add an environment variable.""" + + def unsetenv(name: str, /) -> None: + """Delete an environment variable.""" _Opener: TypeAlias = Callable[[str, int], int] @@ -1479,54 +1338,39 @@ def fdopen( opener: _Opener | None = ..., ) -> IO[Any]: ... def close(fd: int) -> None: - """ - Close a file descriptor. - """ + """Close a file descriptor.""" def closerange(fd_low: int, fd_high: int, /) -> None: - """ - Closes all file descriptors in [fd_low, fd_high), ignoring errors. - """ + """Closes all file descriptors in [fd_low, fd_high), ignoring errors.""" def device_encoding(fd: int) -> str | None: - """ - Return a string describing the encoding of a terminal's file descriptor. + """Return a string describing the encoding of a terminal's file descriptor. The file descriptor must be attached to a terminal. If the device is not a terminal, return None. """ def dup(fd: int, /) -> int: - """ - Return a duplicate of a file descriptor. - """ + """Return a duplicate of a file descriptor.""" def dup2(fd: int, fd2: int, inheritable: bool = True) -> int: - """ - Duplicate file descriptor. - """ + """Duplicate file descriptor.""" def fstat(fd: int) -> stat_result: - """ - Perform a stat system call on the given file descriptor. + """Perform a stat system call on the given file descriptor. Like stat(), but for an open file descriptor. Equivalent to os.stat(fd). """ def ftruncate(fd: int, length: int, /) -> None: - """ - Truncate a file, specified by file descriptor, to a specific length. - """ + """Truncate a file, specified by file descriptor, to a specific length.""" def fsync(fd: FileDescriptorLike) -> None: - """ - Force write of fd to disk. - """ + """Force write of fd to disk.""" def isatty(fd: int, /) -> bool: - """ - Return True if the fd is connected to a terminal. + """Return True if the fd is connected to a terminal. Return True if the file descriptor is an open file descriptor connected to the slave end of a terminal. @@ -1534,8 +1378,7 @@ def isatty(fd: int, /) -> bool: if sys.platform != "win32" and sys.version_info >= (3, 11): def login_tty(fd: int, /) -> None: - """ - Prepare the tty of which fd is a file descriptor for a new login session. + """Prepare the tty of which fd is a file descriptor for a new login session. Make the calling process a session leader; make the tty the controlling tty, the stdin, the stdout, and the stderr of the @@ -1544,8 +1387,7 @@ if sys.platform != "win32" and sys.version_info >= (3, 11): if sys.version_info >= (3, 11): def lseek(fd: int, position: int, whence: int, /) -> int: - """ - Set the position of a file descriptor. Return the new position. + """Set the position of a file descriptor. Return the new position. fd An open file descriptor, as returned by os.open(). @@ -1562,16 +1404,14 @@ if sys.version_info >= (3, 11): else: def lseek(fd: int, position: int, how: int, /) -> int: - """ - Set the position of a file descriptor. Return the new position. + """Set the position of a file descriptor. Return the new position. Return the new cursor position in number of bytes relative to the beginning of the file. """ def open(path: StrOrBytesPath, flags: int, mode: int = 0o777, *, dir_fd: int | None = None) -> int: - """ - Open a file for low level IO. Returns a file descriptor (integer). + """Open a file for low level IO. Returns a file descriptor (integer). If dir_fd is not None, it should be a file descriptor open to a directory, and path should be relative; path will then be relative to that directory. @@ -1580,29 +1420,24 @@ def open(path: StrOrBytesPath, flags: int, mode: int = 0o777, *, dir_fd: int | N """ def pipe() -> tuple[int, int]: - """ - Create a pipe. + """Create a pipe. Returns a tuple of two file descriptors: (read_fd, write_fd) """ def read(fd: int, length: int, /) -> bytes: - """ - Read from a file descriptor. Returns a bytes object. - """ + """Read from a file descriptor. Returns a bytes object.""" if sys.version_info >= (3, 12) or sys.platform != "win32": def get_blocking(fd: int, /) -> bool: - """ - Get the blocking mode of the file descriptor. + """Get the blocking mode of the file descriptor. Return False if the O_NONBLOCK flag is set, True if the flag is cleared. """ def set_blocking(fd: int, blocking: bool, /) -> None: - """ - Set the blocking mode of the specified file descriptor. + """Set the blocking mode of the specified file descriptor. Set the O_NONBLOCK flag if blocking is False, clear the O_NONBLOCK flag otherwise. @@ -1610,29 +1445,25 @@ if sys.version_info >= (3, 12) or sys.platform != "win32": if sys.platform != "win32": def fchown(fd: int, uid: int, gid: int) -> None: - """ - Change the owner and group id of the file specified by file descriptor. + """Change the owner and group id of the file specified by file descriptor. Equivalent to os.chown(fd, uid, gid). """ def fpathconf(fd: int, name: str | int, /) -> int: - """ - Return the configuration limit name for the file descriptor fd. + """Return the configuration limit name for the file descriptor fd. If there is no limit, return -1. """ def fstatvfs(fd: int, /) -> statvfs_result: - """ - Perform an fstatvfs system call on the given fd. + """Perform an fstatvfs system call on the given fd. Equivalent to statvfs(fd). """ def lockf(fd: int, command: int, length: int, /) -> None: - """ - Apply, test or remove a POSIX lock on an open file descriptor. + """Apply, test or remove a POSIX lock on an open file descriptor. fd An open file descriptor. @@ -1643,21 +1474,17 @@ if sys.platform != "win32": """ def openpty() -> tuple[int, int]: # some flavors of Unix - """ - Open a pseudo-terminal. + """Open a pseudo-terminal. Return a tuple of (master_fd, slave_fd) containing open file descriptors for both the master and slave ends. """ if sys.platform != "darwin": def fdatasync(fd: FileDescriptorLike) -> None: - """ - Force write of fd to disk without forcing update of metadata. - """ + """Force write of fd to disk without forcing update of metadata.""" def pipe2(flags: int, /) -> tuple[int, int]: # some flavors of Unix - """ - Create a pipe with flags set atomically. + """Create a pipe with flags set atomically. Returns a tuple of two file descriptors: (read_fd, write_fd) @@ -1667,16 +1494,14 @@ if sys.platform != "win32": """ def posix_fallocate(fd: int, offset: int, length: int, /) -> None: - """ - Ensure a file has allocated at least a particular number of bytes on disk. + """Ensure a file has allocated at least a particular number of bytes on disk. Ensure that the file specified by fd encompasses a range of bytes starting at offset bytes from the beginning and continuing for length bytes. """ def posix_fadvise(fd: int, offset: int, length: int, advice: int, /) -> None: - """ - Announce an intention to access data in a specific pattern. + """Announce an intention to access data in a specific pattern. Announce an intention to access data in a specific pattern, thus allowing the kernel to make optimizations. @@ -1688,16 +1513,14 @@ if sys.platform != "win32": """ def pread(fd: int, length: int, offset: int, /) -> bytes: - """ - Read a number of bytes from a file descriptor starting at a particular offset. + """Read a number of bytes from a file descriptor starting at a particular offset. Read length bytes from file descriptor fd, starting at offset bytes from the beginning of the file. The file offset remains unchanged. """ def pwrite(fd: int, buffer: ReadableBuffer, offset: int, /) -> int: - """ - Write bytes to a file descriptor starting at a particular offset. + """Write bytes to a file descriptor starting at a particular offset. Write buffer to fd, starting at offset bytes from the beginning of the file. Returns the number of bytes written. Does not change the @@ -1705,8 +1528,7 @@ if sys.platform != "win32": """ # In CI, stubtest sometimes reports that these are available on MacOS, sometimes not def preadv(fd: int, buffers: SupportsLenAndGetItem[WriteableBuffer], offset: int, flags: int = 0, /) -> int: - """ - Reads from a file descriptor into a number of mutable bytes-like objects. + """Reads from a file descriptor into a number of mutable bytes-like objects. Combines the functionality of readv() and pread(). As readv(), it will transfer data into each buffer until it is full and then move on to the next @@ -1724,8 +1546,7 @@ if sys.platform != "win32": """ def pwritev(fd: int, buffers: SupportsLenAndGetItem[ReadableBuffer], offset: int, flags: int = 0, /) -> int: - """ - Writes the contents of bytes-like objects to a file descriptor at a given offset. + """Writes the contents of bytes-like objects to a file descriptor at a given offset. Combines the functionality of writev() and pwrite(). All buffers must be a sequence of bytes-like objects. Buffers are processed in array order. Entire contents of first @@ -1752,9 +1573,7 @@ if sys.platform != "win32": if sys.platform == "linux": def sendfile(out_fd: FileDescriptor, in_fd: FileDescriptor, offset: int | None, count: int) -> int: - """ - Copy count bytes from file descriptor in_fd to file descriptor out_fd. - """ + """Copy count bytes from file descriptor in_fd to file descriptor out_fd.""" else: def sendfile( out_fd: FileDescriptor, @@ -1764,11 +1583,11 @@ if sys.platform != "win32": headers: Sequence[ReadableBuffer] = ..., trailers: Sequence[ReadableBuffer] = ..., flags: int = 0, - ) -> int: ... # FreeBSD and Mac OS X only + ) -> int: # FreeBSD and Mac OS X only + """Copy count bytes from file descriptor in_fd to file descriptor out_fd.""" def readv(fd: int, buffers: SupportsLenAndGetItem[WriteableBuffer], /) -> int: - """ - Read from a file descriptor fd into an iterable of buffers. + """Read from a file descriptor fd into an iterable of buffers. The buffers should be mutable buffers accepting bytes. readv will transfer data into each buffer until it is full @@ -1780,8 +1599,7 @@ if sys.platform != "win32": """ def writev(fd: int, buffers: SupportsLenAndGetItem[ReadableBuffer], /) -> int: - """ - Iterate over buffers, and write the contents of each to a file descriptor. + """Iterate over buffers, and write the contents of each to a file descriptor. Returns the total number of bytes written. buffers must be a sequence of bytes-like objects. @@ -1789,8 +1607,7 @@ if sys.platform != "win32": if sys.version_info >= (3, 14): def readinto(fd: int, buffer: ReadableBuffer, /) -> int: - """ - Read into a buffer object from a file descriptor. + """Read into a buffer object from a file descriptor. The buffer should be mutable and bytes-like. On success, returns the number of bytes read. Less bytes may be read than the size of the buffer. The underlying @@ -1805,28 +1622,21 @@ if sys.version_info >= (3, 14): @final class terminal_size(structseq[int], tuple[int, int]): - """ - A tuple of (columns, lines) for holding terminal window size - """ + """A tuple of (columns, lines) for holding terminal window size""" if sys.version_info >= (3, 10): __match_args__: Final = ("columns", "lines") @property def columns(self) -> int: - """ - width of the terminal window in characters - """ + """width of the terminal window in characters""" @property def lines(self) -> int: - """ - height of the terminal window in characters - """ + """height of the terminal window in characters""" def get_terminal_size(fd: int = ..., /) -> terminal_size: - """ - Return the size of the terminal window as (columns, lines). + """Return the size of the terminal window as (columns, lines). The optional argument fd (default standard output) specifies which file descriptor should be queried. @@ -1842,49 +1652,40 @@ def get_terminal_size(fd: int = ..., /) -> terminal_size: """ def get_inheritable(fd: int, /) -> bool: - """ - Get the close-on-exe flag of the specified file descriptor. - """ + """Get the close-on-exe flag of the specified file descriptor.""" def set_inheritable(fd: int, inheritable: bool, /) -> None: - """ - Set the inheritable flag of the specified file descriptor. - """ + """Set the inheritable flag of the specified file descriptor.""" if sys.platform == "win32": - def get_handle_inheritable(handle: int, /) -> bool: ... - def set_handle_inheritable(handle: int, inheritable: bool, /) -> None: ... + def get_handle_inheritable(handle: int, /) -> bool: + """Get the close-on-exe flag of the specified file descriptor.""" + + def set_handle_inheritable(handle: int, inheritable: bool, /) -> None: + """Set the inheritable flag of the specified handle.""" if sys.platform != "win32": # Unix only def tcgetpgrp(fd: int, /) -> int: - """ - Return the process group associated with the terminal specified by fd. - """ + """Return the process group associated with the terminal specified by fd.""" def tcsetpgrp(fd: int, pgid: int, /) -> None: - """ - Set the process group associated with the terminal specified by fd. - """ + """Set the process group associated with the terminal specified by fd.""" def ttyname(fd: int, /) -> str: - """ - Return the name of the terminal device connected to 'fd'. + """Return the name of the terminal device connected to 'fd'. fd Integer file descriptor handle. """ def write(fd: int, data: ReadableBuffer, /) -> int: - """ - Write a bytes object to a file descriptor. - """ + """Write a bytes object to a file descriptor.""" def access( path: FileDescriptorOrPath, mode: int, *, dir_fd: int | None = None, effective_ids: bool = False, follow_symlinks: bool = True ) -> bool: - """ - Use the real uid/gid to test for access to a path. + """Use the real uid/gid to test for access to a path. path Path to be tested; can be string, bytes, or a path-like object. @@ -1913,8 +1714,7 @@ def access( """ def chdir(path: FileDescriptorOrPath) -> None: - """ - Change the current working directory to the specified path. + """Change the current working directory to the specified path. path may always be specified as a string. On some platforms, path may also be specified as an open file descriptor. @@ -1923,26 +1723,20 @@ def chdir(path: FileDescriptorOrPath) -> None: if sys.platform != "win32": def fchdir(fd: FileDescriptorLike) -> None: - """ - Change to the directory of the given file descriptor. + """Change to the directory of the given file descriptor. fd must be opened on a directory, not a file. Equivalent to os.chdir(fd). """ def getcwd() -> str: - """ - Return a unicode string representing the current working directory. - """ + """Return a unicode string representing the current working directory.""" def getcwdb() -> bytes: - """ - Return a bytes string representing the current working directory. - """ + """Return a bytes string representing the current working directory.""" def chmod(path: FileDescriptorOrPath, mode: int, *, dir_fd: int | None = None, follow_symlinks: bool = ...) -> None: - """ - Change the access permissions of a file. + """Change the access permissions of a file. path Path to be modified. May always be specified as a str, bytes, or a path-like object. @@ -1969,18 +1763,29 @@ def chmod(path: FileDescriptorOrPath, mode: int, *, dir_fd: int | None = None, f """ if sys.platform != "win32" and sys.platform != "linux": - def chflags(path: StrOrBytesPath, flags: int, follow_symlinks: bool = True) -> None: ... # some flavors of Unix - def lchflags(path: StrOrBytesPath, flags: int) -> None: ... + def chflags(path: StrOrBytesPath, flags: int, follow_symlinks: bool = True) -> None: # some flavors of Unix + """Set file flags. + + If follow_symlinks is False, and the last element of the path is a symbolic + link, chflags will change flags on the symbolic link itself instead of the + file the link points to. + follow_symlinks may not be implemented on your platform. If it is + unavailable, using it will raise a NotImplementedError. + """ + + def lchflags(path: StrOrBytesPath, flags: int) -> None: + """Set file flags. + + This function will not follow symbolic links. + Equivalent to chflags(path, flags, follow_symlinks=False). + """ if sys.platform != "win32": def chroot(path: StrOrBytesPath) -> None: - """ - Change root directory to path. - """ + """Change root directory to path.""" def chown(path: FileDescriptorOrPath, uid: int, gid: int, *, dir_fd: int | None = None, follow_symlinks: bool = True) -> None: - """ - Change the owner and group id of path to the numeric uid and gid.\\ + """Change the owner and group id of path to the numeric uid and gid.\\ path Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int. @@ -2008,8 +1813,7 @@ if sys.platform != "win32": """ def lchown(path: StrOrBytesPath, uid: int, gid: int) -> None: - """ - Change the owner and group id of path to the numeric uid and gid. + """Change the owner and group id of path to the numeric uid and gid. This function will not follow symbolic links. Equivalent to os.chown(path, uid, gid, follow_symlinks=False). @@ -2023,8 +1827,7 @@ def link( dst_dir_fd: int | None = None, follow_symlinks: bool = True, ) -> None: - """ - Create a hard link to a file. + """Create a hard link to a file. If either src_dir_fd or dst_dir_fd is not None, it should be a file descriptor open to a directory, and the respective path string (src or dst) @@ -2038,16 +1841,14 @@ def link( """ def lstat(path: StrOrBytesPath, *, dir_fd: int | None = None) -> stat_result: - """ - Perform a stat system call on the given path, without following symbolic links. + """Perform a stat system call on the given path, without following symbolic links. Like stat(), but do not follow symbolic links. Equivalent to stat(path, follow_symlinks=False). """ def mkdir(path: StrOrBytesPath, mode: int = 0o777, *, dir_fd: int | None = None) -> None: - """ - Create a directory. + """Create a directory. If dir_fd is not None, it should be a file descriptor open to a directory, and path should be relative; path will then be relative to that directory. @@ -2060,8 +1861,7 @@ def mkdir(path: StrOrBytesPath, mode: int = 0o777, *, dir_fd: int | None = None) if sys.platform != "win32": def mkfifo(path: StrOrBytesPath, mode: int = 0o666, *, dir_fd: int | None = None) -> None: # Unix only - """ - Create a "fifo" (a POSIX named pipe). + """Create a "fifo" (a POSIX named pipe). If dir_fd is not None, it should be a file descriptor open to a directory, and path should be relative; path will then be relative to that directory. @@ -2070,8 +1870,7 @@ if sys.platform != "win32": """ def makedirs(name: StrOrBytesPath, mode: int = 0o777, exist_ok: bool = False) -> None: - """ - makedirs(name [, mode=0o777][, exist_ok=False]) + """makedirs(name [, mode=0o777][, exist_ok=False]) Super-mkdir; create a leaf directory and all intermediate ones. Works like mkdir, except that any intermediate path segment (not just the rightmost) @@ -2082,8 +1881,7 @@ def makedirs(name: StrOrBytesPath, mode: int = 0o777, exist_ok: bool = False) -> if sys.platform != "win32": def mknod(path: StrOrBytesPath, mode: int = 0o600, device: int = 0, *, dir_fd: int | None = None) -> None: - """ - Create a node in the file system. + """Create a node in the file system. Create a node in the file system (file, device special file or named pipe) at path. mode specifies both the permissions to use and the @@ -2099,23 +1897,16 @@ if sys.platform != "win32": """ def major(device: int, /) -> int: - """ - Extracts a device major number from a raw device number. - """ + """Extracts a device major number from a raw device number.""" def minor(device: int, /) -> int: - """ - Extracts a device minor number from a raw device number. - """ + """Extracts a device minor number from a raw device number.""" def makedev(major: int, minor: int, /) -> int: - """ - Composes a raw device number from the major and minor device numbers. - """ + """Composes a raw device number from the major and minor device numbers.""" def pathconf(path: FileDescriptorOrPath, name: str | int) -> int: # Unix only - """ - Return the configuration limit name for the file or directory path. + """Return the configuration limit name for the file or directory path. If there is no limit, return -1. On some platforms, path may also be specified as an open file descriptor. @@ -2123,8 +1914,7 @@ if sys.platform != "win32": """ def readlink(path: GenericPath[AnyStr], *, dir_fd: int | None = None) -> AnyStr: - """ - Return a string representing the path to which the symbolic link points. + """Return a string representing the path to which the symbolic link points. If dir_fd is not None, it should be a file descriptor open to a directory, and path should be relative; path will then be relative to that directory. @@ -2134,8 +1924,7 @@ def readlink(path: GenericPath[AnyStr], *, dir_fd: int | None = None) -> AnyStr: """ def remove(path: StrOrBytesPath, *, dir_fd: int | None = None) -> None: - """ - Remove a file (same as unlink()). + """Remove a file (same as unlink()). If dir_fd is not None, it should be a file descriptor open to a directory, and path should be relative; path will then be relative to that directory. @@ -2144,8 +1933,7 @@ def remove(path: StrOrBytesPath, *, dir_fd: int | None = None) -> None: """ def removedirs(name: StrOrBytesPath) -> None: - """ - removedirs(name) + """removedirs(name) Super-rmdir; remove a leaf directory and all empty intermediate ones. Works like rmdir except that, if the leaf directory is @@ -2156,8 +1944,7 @@ def removedirs(name: StrOrBytesPath) -> None: """ def rename(src: StrOrBytesPath, dst: StrOrBytesPath, *, src_dir_fd: int | None = None, dst_dir_fd: int | None = None) -> None: - """ - Rename a file or directory. + """Rename a file or directory. If either src_dir_fd or dst_dir_fd is not None, it should be a file descriptor open to a directory, and the respective path string (src or dst) @@ -2167,8 +1954,7 @@ def rename(src: StrOrBytesPath, dst: StrOrBytesPath, *, src_dir_fd: int | None = """ def renames(old: StrOrBytesPath, new: StrOrBytesPath) -> None: - """ - renames(old, new) + """renames(old, new) Super-rename; create directories as necessary and delete any left empty. Works like rename, except creation of any intermediate @@ -2183,8 +1969,7 @@ def renames(old: StrOrBytesPath, new: StrOrBytesPath) -> None: """ def replace(src: StrOrBytesPath, dst: StrOrBytesPath, *, src_dir_fd: int | None = None, dst_dir_fd: int | None = None) -> None: - """ - Rename a file or directory, overwriting the destination. + """Rename a file or directory, overwriting the destination. If either src_dir_fd or dst_dir_fd is not None, it should be a file descriptor open to a directory, and the respective path string (src or dst) @@ -2194,8 +1979,7 @@ def replace(src: StrOrBytesPath, dst: StrOrBytesPath, *, src_dir_fd: int | None """ def rmdir(path: StrOrBytesPath, *, dir_fd: int | None = None) -> None: - """ - Remove a directory. + """Remove a directory. If dir_fd is not None, it should be a file descriptor open to a directory, and path should be relative; path will then be relative to that directory. @@ -2214,8 +1998,7 @@ class _ScandirIterator(Generic[AnyStr]): @overload def scandir(path: None = None) -> _ScandirIterator[str]: - """ - Return an iterator of DirEntry objects for given path. + """Return an iterator of DirEntry objects for given path. path can be specified as either str, bytes, or a path-like object. If path is bytes, the names of yielded DirEntry objects will also be bytes; in @@ -2229,8 +2012,7 @@ def scandir(path: int) -> _ScandirIterator[str]: ... @overload def scandir(path: GenericPath[AnyStr]) -> _ScandirIterator[AnyStr]: ... def stat(path: FileDescriptorOrPath, *, dir_fd: int | None = None, follow_symlinks: bool = True) -> stat_result: - """ - Perform a stat system call on the given path. + """Perform a stat system call on the given path. path Path to be examined; can be string, bytes, a path-like object or @@ -2254,8 +2036,7 @@ def stat(path: FileDescriptorOrPath, *, dir_fd: int | None = None, follow_symlin if sys.platform != "win32": def statvfs(path: FileDescriptorOrPath) -> statvfs_result: # Unix only - """ - Perform a statvfs system call on the given path. + """Perform a statvfs system call on the given path. path may always be specified as a string. On some platforms, path may also be specified as an open file descriptor. @@ -2263,8 +2044,7 @@ if sys.platform != "win32": """ def symlink(src: StrOrBytesPath, dst: StrOrBytesPath, target_is_directory: bool = False, *, dir_fd: int | None = None) -> None: - """ - Create a symbolic link pointing to src named dst. + """Create a symbolic link pointing to src named dst. target_is_directory is required on Windows if the target is to be interpreted as a directory. (On Windows, symlink requires @@ -2279,21 +2059,17 @@ def symlink(src: StrOrBytesPath, dst: StrOrBytesPath, target_is_directory: bool if sys.platform != "win32": def sync() -> None: # Unix only - """ - Force write of everything to disk. - """ + """Force write of everything to disk.""" def truncate(path: FileDescriptorOrPath, length: int) -> None: # Unix only up to version 3.4 - """ - Truncate a file, specified by path, to a specific length. + """Truncate a file, specified by path, to a specific length. On some platforms, path may also be specified as an open file descriptor. If this functionality is unavailable, using it raises an exception. """ def unlink(path: StrOrBytesPath, *, dir_fd: int | None = None) -> None: - """ - Remove a file (same as remove()). + """Remove a file (same as remove()). If dir_fd is not None, it should be a file descriptor open to a directory, and path should be relative; path will then be relative to that directory. @@ -2309,8 +2085,7 @@ def utime( dir_fd: int | None = None, follow_symlinks: bool = True, ) -> None: - """ - Set the access and modified time of path. + """Set the access and modified time of path. path may always be specified as a string. On some platforms, path may also be specified as an open file descriptor. @@ -2340,8 +2115,7 @@ _OnError: TypeAlias = Callable[[OSError], object] def walk( top: GenericPath[AnyStr], topdown: bool = True, onerror: _OnError | None = None, followlinks: bool = False ) -> Iterator[tuple[AnyStr, list[AnyStr], list[AnyStr]]]: - """ - Directory tree generator. + """Directory tree generator. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), yields a 3-tuple @@ -2410,8 +2184,7 @@ if sys.platform != "win32": follow_symlinks: bool = False, dir_fd: int | None = None, ) -> Iterator[tuple[str, list[str], list[str], int]]: - """ - Directory tree generator. + """Directory tree generator. This behaves exactly like walk(), except that it yields a 4-tuple @@ -2455,8 +2228,7 @@ if sys.platform != "win32": ) -> Iterator[tuple[bytes, list[bytes], list[bytes], int]]: ... if sys.platform == "linux": def getxattr(path: FileDescriptorOrPath, attribute: StrOrBytesPath, *, follow_symlinks: bool = True) -> bytes: - """ - Return the value of extended attribute attribute on path. + """Return the value of extended attribute attribute on path. path may be either a string, a path-like object, or an open file descriptor. If follow_symlinks is False, and the last element of the path is a symbolic @@ -2465,8 +2237,7 @@ if sys.platform != "win32": """ def listxattr(path: FileDescriptorOrPath | None = None, *, follow_symlinks: bool = True) -> list[str]: - """ - Return a list of extended attributes on path. + """Return a list of extended attributes on path. path may be either None, a string, a path-like object, or an open file descriptor. if path is None, listxattr will examine the current directory. @@ -2476,8 +2247,7 @@ if sys.platform != "win32": """ def removexattr(path: FileDescriptorOrPath, attribute: StrOrBytesPath, *, follow_symlinks: bool = True) -> None: - """ - Remove extended attribute attribute on path. + """Remove extended attribute attribute on path. path may be either a string, a path-like object, or an open file descriptor. If follow_symlinks is False, and the last element of the path is a symbolic @@ -2493,8 +2263,7 @@ if sys.platform != "win32": *, follow_symlinks: bool = True, ) -> None: - """ - Set extended attribute attribute on path to value. + """Set extended attribute attribute on path to value. path may be either a string, a path-like object, or an open file descriptor. If follow_symlinks is False, and the last element of the path is a symbolic @@ -2503,8 +2272,7 @@ if sys.platform != "win32": """ def abort() -> NoReturn: - """ - Abort the interpreter immediately. + """Abort the interpreter immediately. This function 'dumps core' or otherwise fails in the hardest way possible on the hosting operating system. This function never returns. @@ -2512,16 +2280,14 @@ def abort() -> NoReturn: # 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: - """ - execl(file, *args) + """execl(file, *args) Execute the executable file with argument list args, replacing the current process. """ def execlp(file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]]]]) -> NoReturn: - """ - execlp(file, *args) + """execlp(file, *args) Execute the executable file (which is searched for along $PATH) with argument list args, replacing the current process. @@ -2529,16 +2295,14 @@ def execlp(file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tupl # 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: - """ - execle(file, *args, env) + """execle(file, *args, env) Execute the executable file with argument list args and environment env, replacing the current process. """ def execlpe(file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]], _ExecEnv]]) -> NoReturn: - """ - execlpe(file, *args, env) + """execlpe(file, *args, env) Execute the executable file (which is searched for along $PATH) with argument list args and environment env, replacing the current @@ -2567,8 +2331,7 @@ _ExecVArgs: TypeAlias = ( _ExecEnv: TypeAlias = Mapping[bytes, bytes | str] | Mapping[str, bytes | str] def execv(path: StrOrBytesPath, argv: _ExecVArgs, /) -> NoReturn: - """ - Execute an executable path with arguments, replacing current process. + """Execute an executable path with arguments, replacing current process. path Path of executable file. @@ -2577,8 +2340,7 @@ def execv(path: StrOrBytesPath, argv: _ExecVArgs, /) -> NoReturn: """ def execve(path: FileDescriptorOrPath, argv: _ExecVArgs, env: _ExecEnv) -> NoReturn: - """ - Execute an executable path with arguments, replacing current process. + """Execute an executable path with arguments, replacing current process. path Path of executable file. @@ -2589,8 +2351,7 @@ def execve(path: FileDescriptorOrPath, argv: _ExecVArgs, env: _ExecEnv) -> NoRet """ def execvp(file: StrOrBytesPath, args: _ExecVArgs) -> NoReturn: - """ - execvp(file, args) + """execvp(file, args) Execute the executable file (which is searched for along $PATH) with argument list args, replacing the current process. @@ -2598,8 +2359,7 @@ def execvp(file: StrOrBytesPath, args: _ExecVArgs) -> NoReturn: """ def execvpe(file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> NoReturn: - """ - execvpe(file, args, env) + """execvpe(file, args, env) Execute the executable file (which is searched for along $PATH) with argument list args and environment env, replacing the @@ -2608,27 +2368,21 @@ def execvpe(file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> NoReturn: """ def _exit(status: int) -> NoReturn: - """ - Exit to the system with specified status, without normal exit processing. - """ + """Exit to the system with specified status, without normal exit processing.""" def kill(pid: int, signal: int, /) -> None: - """ - Kill a process with a signal. - """ + """Kill a process with a signal.""" if sys.platform != "win32": # Unix only def fork() -> int: - """ - Fork a child process. + """Fork a child process. Return 0 to child process and PID of child to parent process. """ def forkpty() -> tuple[int, int]: # some flavors of Unix - """ - Fork a new process with a new pseudo-terminal as controlling tty. + """Fork a new process with a new pseudo-terminal as controlling tty. Returns a tuple of (pid, master_fd). Like fork(), return pid of 0 to the child process, @@ -2637,14 +2391,10 @@ if sys.platform != "win32": """ def killpg(pgid: int, signal: int, /) -> None: - """ - Kill a process group with a signal. - """ + """Kill a process group with a signal.""" def nice(increment: int, /) -> int: - """ - Add increment to the priority of process and return the new priority. - """ + """Add increment to the priority of process and return the new priority.""" if sys.platform != "darwin" and sys.platform != "linux": def plock(op: int, /) -> None: ... @@ -2670,8 +2420,7 @@ class _wrap_close: def popen(cmd: str, mode: str = "r", buffering: int = -1) -> _wrap_close: ... def spawnl(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: - """ - spawnl(mode, file, *args) -> integer + """spawnl(mode, file, *args) -> integer Execute file with arguments from args in a subprocess. If mode == P_NOWAIT return the pid of the process. @@ -2680,8 +2429,7 @@ def spawnl(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBy """ def spawnle(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: # Imprecise sig - """ - spawnle(mode, file, *args, env) -> integer + """spawnle(mode, file, *args, env) -> integer Execute file with arguments from args in a subprocess with the supplied environment. @@ -2692,8 +2440,7 @@ def spawnle(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) - if sys.platform != "win32": def spawnv(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: - """ - spawnv(mode, file, args) -> integer + """spawnv(mode, file, args) -> integer Execute file with arguments from args in a subprocess. If mode == P_NOWAIT return the pid of the process. @@ -2702,8 +2449,7 @@ if sys.platform != "win32": """ def spawnve(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: - """ - spawnve(mode, file, args, env) -> integer + """spawnve(mode, file, args, env) -> integer Execute file with arguments from args in a subprocess with the specified environment. @@ -2713,18 +2459,36 @@ if sys.platform != "win32": """ else: - def spawnv(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, /) -> int: ... - def spawnve(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, env: _ExecEnv, /) -> int: ... + def spawnv(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, /) -> int: + """Execute the program specified by path in a new process. + + mode + Mode of process creation. + path + Path of executable file. + argv + Tuple or list of strings. + """ + + def spawnve(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, env: _ExecEnv, /) -> int: + """Execute the program specified by path in a new process. + + mode + Mode of process creation. + path + Path of executable file. + argv + Tuple or list of strings. + env + Dictionary of strings mapping to strings. + """ def system(command: StrOrBytesPath) -> int: - """ - Execute the command in a subshell. - """ + """Execute the command in a subshell.""" @final class times_result(structseq[float], tuple[float, float, float, float, float]): - """ - times_result: Result from os.times(). + """times_result: Result from os.times(). This object may be accessed either as a tuple of (user, system, children_user, children_system, elapsed), @@ -2739,37 +2503,26 @@ class times_result(structseq[float], tuple[float, float, float, float, float]): @property def user(self) -> float: - """ - user time - """ + """user time""" @property def system(self) -> float: - """ - system time - """ + """system time""" @property def children_user(self) -> float: - """ - user time of children - """ + """user time of children""" @property def children_system(self) -> float: - """ - system time of children - """ + """system time of children""" @property def elapsed(self) -> float: - """ - elapsed time since an arbitrary point in the past - """ + """elapsed time since an arbitrary point in the past""" def times() -> times_result: - """ - Return a collection containing process timing information. + """Return a collection containing process timing information. The object returned behaves like a named tuple with these fields: (utime, stime, cutime, cstime, elapsed_time) @@ -2777,8 +2530,7 @@ def times() -> times_result: """ def waitpid(pid: int, options: int, /) -> tuple[int, int]: - """ - Wait for completion of a given child process. + """Wait for completion of a given child process. Returns a tuple of information regarding the child process: (pid, status) @@ -2794,14 +2546,57 @@ if sys.platform == "win32": arguments: str = "", cwd: StrOrBytesPath | None = None, show_cmd: int = 1, - ) -> None: ... + ) -> None: + """Start a file with its associated application. + + When "operation" is not specified or "open", this acts like + double-clicking the file in Explorer, or giving the file name as an + argument to the DOS "start" command: the file is opened with whatever + application (if any) its extension is associated. + When another "operation" is given, it specifies what should be done with + the file. A typical operation is "print". + + "arguments" is passed to the application, but should be omitted if the + file is a document. + + "cwd" is the working directory for the operation. If "filepath" is + relative, it will be resolved against this directory. This argument + should usually be an absolute path. + + "show_cmd" can be used to override the recommended visibility option. + See the Windows ShellExecute documentation for values. + + startfile returns as soon as the associated application is launched. + There is no option to wait for the application to close, and no way + to retrieve the application's exit status. + + The filepath is relative to the current directory. If you want to use + an absolute path, make sure the first character is not a slash ("/"); + the underlying Win32 ShellExecute function doesn't work if it is. + """ else: - def startfile(filepath: StrOrBytesPath, operation: str = ...) -> None: ... + def startfile(filepath: StrOrBytesPath, operation: str = ...) -> None: + """Start a file with its associated application. + + When "operation" is not specified or "open", this acts like + double-clicking the file in Explorer, or giving the file name as an + argument to the DOS "start" command: the file is opened with whatever + application (if any) its extension is associated. + When another "operation" is given, it specifies what should be done with + the file. A typical operation is "print". + + startfile returns as soon as the associated application is launched. + There is no option to wait for the application to close, and no way + to retrieve the application's exit status. + + The filepath is relative to the current directory. If you want to use + an absolute path, make sure the first character is not a slash ("/"); + the underlying Win32 ShellExecute function doesn't work if it is. + """ else: def spawnlp(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: - """ - spawnlp(mode, file, *args) -> integer + """spawnlp(mode, file, *args) -> integer Execute file (which is looked for along $PATH) with arguments from args in a subprocess with the supplied environment. @@ -2811,8 +2606,7 @@ else: """ def spawnlpe(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: # Imprecise signature - """ - spawnlpe(mode, file, *args, env) -> integer + """spawnlpe(mode, file, *args, env) -> integer Execute file (which is looked for along $PATH) with arguments from args in a subprocess with the supplied environment. @@ -2822,8 +2616,7 @@ else: """ def spawnvp(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: - """ - spawnvp(mode, file, args) -> integer + """spawnvp(mode, file, args) -> integer Execute file (which is looked for along $PATH) with arguments from args in a subprocess. @@ -2833,8 +2626,7 @@ else: """ def spawnvpe(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: - """ - spawnvpe(mode, file, args, env) -> integer + """spawnvpe(mode, file, args, env) -> integer Execute file (which is looked for along $PATH) with arguments from args in a subprocess with the supplied environment. @@ -2844,8 +2636,7 @@ else: """ def wait() -> tuple[int, int]: # Unix only - """ - Wait for completion of a child process. + """Wait for completion of a child process. Returns a tuple of information about the child process: (pid, status) @@ -2854,8 +2645,7 @@ else: if sys.platform != "darwin" or sys.version_info >= (3, 13): @final class waitid_result(structseq[int], tuple[int, int, int, int, int]): - """ - waitid_result: Result from waitid. + """waitid_result: Result from waitid. This object may be accessed either as a tuple of (si_pid, si_uid, si_signo, si_status, si_code), @@ -2879,8 +2669,7 @@ else: def si_code(self) -> int: ... def waitid(idtype: int, ident: int, options: int, /) -> waitid_result | None: - """ - Returns the result of waiting for a process or processes. + """Returns the result of waiting for a process or processes. idtype Must be one of be P_PID, P_PGID or P_ALL. @@ -2896,63 +2685,46 @@ else: from resource import struct_rusage def wait3(options: int) -> tuple[int, int, struct_rusage]: - """ - Wait for completion of a child process. + """Wait for completion of a child process. Returns a tuple of information about the child process: (pid, status, rusage) """ def wait4(pid: int, options: int) -> tuple[int, int, struct_rusage]: - """ - Wait for completion of a specific child process. + """Wait for completion of a specific child process. Returns a tuple of information about the child process: (pid, status, rusage) """ def WCOREDUMP(status: int, /) -> bool: - """ - Return True if the process returning status was dumped to a core file. - """ + """Return True if the process returning status was dumped to a core file.""" def WIFCONTINUED(status: int) -> bool: - """ - Return True if a particular process was continued from a job control stop. + """Return True if a particular process was continued from a job control stop. Return True if the process returning status was continued from a job control stop. """ def WIFSTOPPED(status: int) -> bool: - """ - Return True if the process returning status was stopped. - """ + """Return True if the process returning status was stopped.""" def WIFSIGNALED(status: int) -> bool: - """ - Return True if the process returning status was terminated by a signal. - """ + """Return True if the process returning status was terminated by a signal.""" def WIFEXITED(status: int) -> bool: - """ - Return True if the process returning status exited via the exit() system call. - """ + """Return True if the process returning status exited via the exit() system call.""" def WEXITSTATUS(status: int) -> int: - """ - Return the process return code from status. - """ + """Return the process return code from status.""" def WSTOPSIG(status: int) -> int: - """ - Return the signal that stopped the process that provided the status value. - """ + """Return the signal that stopped the process that provided the status value.""" def WTERMSIG(status: int) -> int: - """ - Return the signal that terminated the process that provided the status value. - """ + """Return the signal that terminated the process that provided the status value.""" def posix_spawn( path: StrOrBytesPath, @@ -2968,8 +2740,7 @@ else: setsigdef: Iterable[int] = ..., scheduler: tuple[Any, sched_param] | None = ..., ) -> int: - """ - Execute the program specified by path in a new process. + """Execute the program specified by path in a new process. path Path of executable file. @@ -3007,8 +2778,7 @@ else: setsigdef: Iterable[int] = ..., scheduler: tuple[Any, sched_param] | None = ..., ) -> int: - """ - Execute the program specified by path in a new process. + """Execute the program specified by path in a new process. path Path of executable file. @@ -3038,8 +2808,7 @@ else: if sys.platform != "win32": @final class sched_param(structseq[int], tuple[int]): - """ - Currently has only one field: sched_priority + """Currently has only one field: sched_priority sched_priority A scheduling parameter. @@ -3051,80 +2820,64 @@ if sys.platform != "win32": def __new__(cls, sched_priority: int) -> Self: ... @property def sched_priority(self) -> int: - """ - the scheduling priority - """ + """the scheduling priority""" def sched_get_priority_min(policy: int) -> int: # some flavors of Unix - """ - Get the minimum scheduling priority for policy. - """ + """Get the minimum scheduling priority for policy.""" def sched_get_priority_max(policy: int) -> int: # some flavors of Unix - """ - Get the maximum scheduling priority for policy. - """ + """Get the maximum scheduling priority for policy.""" def sched_yield() -> None: # some flavors of Unix - """ - Voluntarily relinquish the CPU. - """ + """Voluntarily relinquish the CPU.""" if sys.platform != "darwin": def sched_setscheduler(pid: int, policy: int, param: sched_param, /) -> None: # some flavors of Unix - """ - Set the scheduling policy for the process identified by pid. + """Set the scheduling policy for the process identified by pid. If pid is 0, the calling process is changed. param is an instance of sched_param. """ def sched_getscheduler(pid: int, /) -> int: # some flavors of Unix - """ - Get the scheduling policy for the process identified by pid. + """Get the scheduling policy for the process identified by pid. Passing 0 for pid returns the scheduling policy for the calling process. """ def sched_rr_get_interval(pid: int, /) -> float: # some flavors of Unix - """ - Return the round-robin quantum for the process identified by pid, in seconds. + """Return the round-robin quantum for the process identified by pid, in seconds. Value returned is a float. """ def sched_setparam(pid: int, param: sched_param, /) -> None: # some flavors of Unix - """ - Set scheduling parameters for the process identified by pid. + """Set scheduling parameters for the process identified by pid. If pid is 0, sets parameters for the calling process. param should be an instance of sched_param. """ def sched_getparam(pid: int, /) -> sched_param: # some flavors of Unix - """ - Returns scheduling parameters for the process identified by pid. + """Returns scheduling parameters for the process identified by pid. If pid is 0, returns parameters for the calling process. Return value is an instance of sched_param. """ def sched_setaffinity(pid: int, mask: Iterable[int], /) -> None: # some flavors of Unix - """ - Set the CPU affinity of the process identified by pid to mask. + """Set the CPU affinity of the process identified by pid to mask. mask should be an iterable of integers identifying CPUs. """ def sched_getaffinity(pid: int, /) -> set[int]: # some flavors of Unix - """ - Return the affinity of the process identified by pid (or the current process if zero). + """Return the affinity of the process identified by pid (or the current process if zero). The affinity is returned as a set of CPU identifiers. """ def cpu_count() -> int | None: - """ - Return the number of logical CPUs in the system. + """Return the number of logical CPUs in the system. Return None if indeterminable. """ @@ -3134,25 +2887,25 @@ if sys.version_info >= (3, 13): # available. See https://github.com/python/cpython/blob/417c130/Lib/os.py#L1175-L1186. if sys.platform != "win32" and sys.platform != "darwin": def process_cpu_count() -> int: - """ - Get the number of CPUs of the current process. + """Get the number of CPUs of the current process. Return the number of logical CPUs usable by the calling thread of the current process. Return None if indeterminable. """ else: - def process_cpu_count() -> int | None: ... + def process_cpu_count() -> int | None: + """Return the number of logical CPUs in the system. + + Return None if indeterminable. + """ if sys.platform != "win32": # Unix only def confstr(name: str | int, /) -> str | None: - """ - Return a string-valued system configuration variable. - """ + """Return a string-valued system configuration variable.""" def getloadavg() -> tuple[float, float, float]: - """ - Return average recent system load information. + """Return average recent system load information. Return the number of processes in the system run queue averaged over the last 1, 5, and 15 minutes as a tuple of three floats. @@ -3160,20 +2913,14 @@ if sys.platform != "win32": """ def sysconf(name: str | int, /) -> int: - """ - Return an integer-valued system configuration variable. - """ + """Return an integer-valued system configuration variable.""" if sys.platform == "linux": def getrandom(size: int, flags: int = 0) -> bytes: - """ - Obtain a series of random bytes. - """ + """Obtain a series of random bytes.""" def urandom(size: int, /) -> bytes: - """ - Return a bytes object containing random bytes suitable for cryptographic use. - """ + """Return a bytes object containing random bytes suitable for cryptographic use.""" if sys.platform != "win32": def register_at_fork( @@ -3182,8 +2929,7 @@ if sys.platform != "win32": after_in_parent: Callable[..., Any] | None = ..., after_in_child: Callable[..., Any] | None = ..., ) -> None: - """ - Register callables to be called when forking a new process. + """Register callables to be called when forking a new process. before A callable to be called in the parent before the fork() syscall. @@ -3204,7 +2950,16 @@ if sys.platform == "win32": def __enter__(self) -> Self: ... def __exit__(self, *args: Unused) -> None: ... - def add_dll_directory(path: str) -> _AddedDllDirectory: ... + def add_dll_directory(path: str) -> _AddedDllDirectory: + """Add a path to the DLL search path. + + This search path is used when resolving dependencies for imported + extension modules (the module itself is resolved through sys.path), + and also by ctypes. + + Remove the directory by calling close() on the returned object or + using it in a with statement. + """ if sys.platform == "linux": MFD_CLOEXEC: int @@ -3226,8 +2981,7 @@ if sys.platform == "linux": MFD_HUGE_16GB: int def memfd_create(name: str, flags: int = ...) -> int: ... def copy_file_range(src: int, dst: int, count: int, offset_src: int | None = ..., offset_dst: int | None = ...) -> int: - """ - Copy count bytes from one file descriptor to another. + """Copy count bytes from one file descriptor to another. src Source file descriptor. @@ -3245,8 +2999,7 @@ if sys.platform == "linux": """ def waitstatus_to_exitcode(status: int) -> int: - """ - Convert a wait status to an exit code. + """Convert a wait status to an exit code. On Unix: @@ -3263,8 +3016,7 @@ def waitstatus_to_exitcode(status: int) -> int: if sys.platform == "linux": def pidfd_open(pid: int, flags: int = ...) -> int: - """ - Return a file descriptor referring to the process *pid*. + """Return a file descriptor referring to the process *pid*. The descriptor can be used to perform process management without races and signals. @@ -3274,9 +3026,23 @@ if sys.version_info >= (3, 12) and sys.platform == "linux": PIDFD_NONBLOCK: Final = 2048 if sys.version_info >= (3, 12) and sys.platform == "win32": - def listdrives() -> list[str]: ... - def listmounts(volume: str) -> list[str]: ... - def listvolumes() -> list[str]: ... + def listdrives() -> list[str]: + """Return a list containing the names of drives in the system. + + A drive name typically looks like 'C:\\\\'. + """ + + def listmounts(volume: str) -> list[str]: + """Return a list containing mount points for a particular volume. + + 'volume' should be a GUID path as returned from os.listvolumes. + """ + + def listvolumes() -> list[str]: + """Return a list containing the volumes in the system. + + Volumes are typically represented as a GUID path. + """ if sys.version_info >= (3, 10) and sys.platform == "linux": EFD_CLOEXEC: int @@ -3286,19 +3052,13 @@ if sys.version_info >= (3, 10) and sys.platform == "linux": SPLICE_F_MOVE: int SPLICE_F_NONBLOCK: int def eventfd(initval: int, flags: int = 524288) -> FileDescriptor: - """ - Creates and returns an event notification file descriptor. - """ + """Creates and returns an event notification file descriptor.""" def eventfd_read(fd: FileDescriptor) -> int: - """ - Read eventfd value - """ + """Read eventfd value""" def eventfd_write(fd: FileDescriptor, value: int) -> None: - """ - Write eventfd value. - """ + """Write eventfd value.""" def splice( src: FileDescriptor, @@ -3308,8 +3068,7 @@ if sys.version_info >= (3, 10) and sys.platform == "linux": offset_dst: int | None = ..., flags: int = 0, ) -> int: - """ - Transfer count bytes from one pipe to a descriptor or vice versa. + """Transfer count bytes from one pipe to a descriptor or vice versa. src Source file descriptor. @@ -3345,16 +3104,14 @@ if sys.version_info >= (3, 12) and sys.platform == "linux": CLONE_THREAD: int CLONE_VM: int def unshare(flags: int) -> None: - """ - Disassociate parts of a process (or thread) execution context. + """Disassociate parts of a process (or thread) execution context. flags Namespaces to be unshared. """ def setns(fd: FileDescriptorLike, nstype: int = 0) -> None: - """ - Move the calling thread into different namespaces. + """Move the calling thread into different namespaces. fd A file descriptor to a namespace. @@ -3364,8 +3121,7 @@ if sys.version_info >= (3, 12) and sys.platform == "linux": if sys.version_info >= (3, 13) and sys.platform != "win32": def posix_openpt(oflag: int, /) -> int: - """ - Open and return a file descriptor for a master pseudo-terminal device. + """Open and return a file descriptor for a master pseudo-terminal device. Performs a posix_openpt() C function call. The oflag argument is used to set file status flags and file access modes as specified in the manual page @@ -3373,8 +3129,7 @@ if sys.version_info >= (3, 13) and sys.platform != "win32": """ def grantpt(fd: FileDescriptorLike, /) -> None: - """ - Grant access to the slave pseudo-terminal device. + """Grant access to the slave pseudo-terminal device. fd File descriptor of a master pseudo-terminal device. @@ -3383,8 +3138,7 @@ if sys.version_info >= (3, 13) and sys.platform != "win32": """ def unlockpt(fd: FileDescriptorLike, /) -> None: - """ - Unlock a pseudo-terminal master/slave pair. + """Unlock a pseudo-terminal master/slave pair. fd File descriptor of a master pseudo-terminal device. @@ -3393,8 +3147,7 @@ if sys.version_info >= (3, 13) and sys.platform != "win32": """ def ptsname(fd: FileDescriptorLike, /) -> str: - """ - Return the name of the slave pseudo-terminal device. + """Return the name of the slave pseudo-terminal device. fd File descriptor of a master pseudo-terminal device. @@ -3411,8 +3164,7 @@ if sys.version_info >= (3, 13) and sys.platform == "linux": POSIX_SPAWN_CLOSEFROM: Final[int] def timerfd_create(clockid: int, /, *, flags: int = 0) -> int: - """ - Create and return a timer file descriptor. + """Create and return a timer file descriptor. clockid A valid clock ID constant as timer file descriptor. @@ -3434,8 +3186,7 @@ if sys.version_info >= (3, 13) and sys.platform == "linux": def timerfd_settime( fd: FileDescriptor, /, *, flags: int = 0, initial: float = 0.0, interval: float = 0.0 ) -> tuple[float, float]: - """ - Alter a timer file descriptor's internal timer in seconds. + """Alter a timer file descriptor's internal timer in seconds. fd A timer file descriptor. @@ -3448,8 +3199,7 @@ if sys.version_info >= (3, 13) and sys.platform == "linux": """ def timerfd_settime_ns(fd: FileDescriptor, /, *, flags: int = 0, initial: int = 0, interval: int = 0) -> tuple[int, int]: - """ - Alter a timer file descriptor's internal timer in nanoseconds. + """Alter a timer file descriptor's internal timer in nanoseconds. fd A timer file descriptor. @@ -3462,16 +3212,14 @@ if sys.version_info >= (3, 13) and sys.platform == "linux": """ def timerfd_gettime(fd: FileDescriptor, /) -> tuple[float, float]: - """ - Return a tuple of a timer file descriptor's (interval, next expiration) in float seconds. + """Return a tuple of a timer file descriptor's (interval, next expiration) in float seconds. fd A timer file descriptor. """ def timerfd_gettime_ns(fd: FileDescriptor, /) -> tuple[int, int]: - """ - Return a tuple of a timer file descriptor's (interval, next expiration) in nanoseconds. + """Return a tuple of a timer file descriptor's (interval, next expiration) in nanoseconds. fd A timer file descriptor. @@ -3480,8 +3228,7 @@ if sys.version_info >= (3, 13) and sys.platform == "linux": if sys.version_info >= (3, 13) or sys.platform != "win32": # Added to Windows in 3.13. def fchmod(fd: int, mode: int) -> None: - """ - Change the access permissions of the file given by file descriptor fd. + """Change the access permissions of the file given by file descriptor fd. fd The file descriptor of the file to be modified. @@ -3497,4 +3244,9 @@ if sys.version_info >= (3, 13) or sys.platform != "win32": if sys.platform != "linux": if sys.version_info >= (3, 13) or sys.platform != "win32": # Added to Windows in 3.13. - def lchmod(path: StrOrBytesPath, mode: int) -> None: ... + def lchmod(path: StrOrBytesPath, mode: int) -> None: + """Change the access permissions of a file, without following symbolic links. + + If path is a symlink, this affects the link itself rather than the target. + Equivalent to chmod(path, mode, follow_symlinks=False)." + """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/parser.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/parser.pyi index ca986711ab..c9144926fd 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/parser.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/parser.pyi @@ -8,80 +8,50 @@ from types import CodeType from typing import Any, ClassVar, final def expr(source: str) -> STType: - """ - Creates an ST object from an expression. - """ + """Creates an ST object from an expression.""" def suite(source: str) -> STType: - """ - Creates an ST object from a suite. - """ + """Creates an ST object from a suite.""" def sequence2st(sequence: Sequence[Any]) -> STType: - """ - Creates an ST object from a tree representation. - """ + """Creates an ST object from a tree representation.""" def tuple2st(sequence: Sequence[Any]) -> STType: - """ - Creates an ST object from a tree representation. - """ + """Creates an ST object from a tree representation.""" def st2list(st: STType, line_info: bool = ..., col_info: bool = ...) -> list[Any]: - """ - Creates a list-tree representation of an ST. - """ + """Creates a list-tree representation of an ST.""" def st2tuple(st: STType, line_info: bool = ..., col_info: bool = ...) -> tuple[Any, ...]: - """ - Creates a tuple-tree representation of an ST. - """ + """Creates a tuple-tree representation of an ST.""" def compilest(st: STType, filename: StrOrBytesPath = ...) -> CodeType: - """ - Compiles an ST object into a code object. - """ + """Compiles an ST object into a code object.""" def isexpr(st: STType) -> bool: - """ - Determines if an ST object was created from an expression. - """ + """Determines if an ST object was created from an expression.""" def issuite(st: STType) -> bool: - """ - Determines if an ST object was created from a suite. - """ + """Determines if an ST object was created from a suite.""" class ParserError(Exception): ... @final class STType: - """ - Intermediate representation of a Python parse tree. - """ + """Intermediate representation of a Python parse tree.""" __hash__: ClassVar[None] # type: ignore[assignment] def compile(self, filename: StrOrBytesPath = ...) -> CodeType: - """ - Compile this ST object into a code object. - """ + """Compile this ST object into a code object.""" def isexpr(self) -> bool: - """ - Determines if this ST object was created from an expression. - """ + """Determines if this ST object was created from an expression.""" def issuite(self) -> bool: - """ - Determines if this ST object was created from a suite. - """ + """Determines if this ST object was created from a suite.""" def tolist(self, line_info: bool = ..., col_info: bool = ...) -> list[Any]: - """ - Creates a list-tree representation of this ST. - """ + """Creates a list-tree representation of this ST.""" def totuple(self, line_info: bool = ..., col_info: bool = ...) -> tuple[Any, ...]: - """ - Creates a tuple-tree representation of this ST. - """ + """Creates a tuple-tree representation of this ST.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/pathlib/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/pathlib/__init__.pyi index add8bf8930..aac0ecc774 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/pathlib/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/pathlib/__init__.pyi @@ -37,8 +37,7 @@ if sys.version_info >= (3, 13): __all__ += ["UnsupportedOperation"] class PurePath(PathLike[str]): - """ - Base class for manipulating paths without I/O. + """Base class for manipulating paths without I/O. PurePath represents a filesystem path and offers operations which don't imply any actual filesystem I/O. Depending on your system, @@ -50,67 +49,52 @@ class PurePath(PathLike[str]): if sys.version_info >= (3, 13): parser: ClassVar[types.ModuleType] def full_match(self, pattern: StrPath, *, case_sensitive: bool | None = None) -> bool: - """ - Return True if this path matches the given glob-style pattern. The + """Return True if this path matches the given glob-style pattern. The pattern is matched against the entire path. """ @property def parts(self) -> tuple[str, ...]: - """ - An object providing sequence-like access to the + """An object providing sequence-like access to the components in the filesystem path. """ @property def drive(self) -> str: - """ - The drive prefix (letter or UNC path), if any. - """ + """The drive prefix (letter or UNC path), if any.""" @property def root(self) -> str: - """ - The root of the path, if any. - """ + """The root of the path, if any.""" @property def anchor(self) -> str: - """ - The concatenation of the drive and root, or ''. - """ + """The concatenation of the drive and root, or ''.""" @property def name(self) -> str: - """ - The final path component, if any. - """ + """The final path component, if any.""" @property def suffix(self) -> str: - """ - The final component's last suffix, if any. + """The final component's last suffix, if any. This includes the leading period. For example: '.txt' """ @property def suffixes(self) -> list[str]: - """ - A list of the final component's suffixes, if any. + """A list of the final component's suffixes, if any. These include the leading periods. For example: ['.tar', '.gz'] """ @property def stem(self) -> str: - """ - The final path component, minus its last suffix. - """ + """The final path component, minus its last suffix.""" if sys.version_info >= (3, 12): def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: - """ - Construct a PurePath from one or several strings and or existing + """Construct a PurePath from one or several strings and or existing PurePath objects. The strings and path objects are combined so as to yield a canonicalized path, which is incorporated into the new PurePath object. @@ -119,8 +103,7 @@ class PurePath(PathLike[str]): def __init__(self, *args: StrPath) -> None: ... # pyright: ignore[reportInconsistentConstructor] else: def __new__(cls, *args: StrPath) -> Self: - """ - Construct a PurePath from one or several strings and or existing + """Construct a PurePath from one or several strings and or existing PurePath objects. The strings and path objects are combined so as to yield a canonicalized path, which is incorporated into the new PurePath object. @@ -135,68 +118,53 @@ class PurePath(PathLike[str]): def __truediv__(self, key: StrPath) -> Self: ... def __rtruediv__(self, key: StrPath) -> Self: ... def __bytes__(self) -> bytes: - """ - Return the bytes representation of the path. This is only + """Return the bytes representation of the path. This is only recommended to use under Unix. """ def as_posix(self) -> str: - """ - Return the string representation of the path with forward (/) + """Return the string representation of the path with forward (/) slashes. """ def as_uri(self) -> str: - """ - Return the path as a URI. - """ + """Return the path as a URI.""" def is_absolute(self) -> bool: - """ - True if the path is absolute (has both a root and, if applicable, + """True if the path is absolute (has both a root and, if applicable, a drive). """ def is_reserved(self) -> bool: - """ - Return True if the path contains one of the special names reserved + """Return True if the path contains one of the special names reserved by the system, if any. """ if sys.version_info >= (3, 14): def is_relative_to(self, other: StrPath) -> bool: - """ - Return True if the path is relative to another path or False. - """ + """Return True if the path is relative to another path or False.""" elif sys.version_info >= (3, 12): def is_relative_to(self, other: StrPath, /, *_deprecated: StrPath) -> bool: - """ - Return True if the path is relative to another path or False. - """ + """Return True if the path is relative to another path or False.""" else: def is_relative_to(self, *other: StrPath) -> bool: - """ - Return True if the path is relative to another path or False. - """ + """Return True if the path is relative to another path or False.""" if sys.version_info >= (3, 12): def match(self, path_pattern: str, *, case_sensitive: bool | None = None) -> bool: - """ - Return True if this path matches the given pattern. If the pattern is + """Return True if this path matches the given pattern. If the pattern is relative, matching is done from the right; otherwise, the entire path is matched. The recursive wildcard '**' is *not* supported by this method. """ else: def match(self, path_pattern: str) -> bool: - """ - Return True if this path matches the given pattern. If the pattern is + """Return True if this path matches the given pattern. If the pattern is relative, matching is done from the right; otherwise, the entire path is matched. The recursive wildcard '**' is *not* supported by this method. """ if sys.version_info >= (3, 14): def relative_to(self, other: StrPath, *, walk_up: bool = False) -> Self: - """ - Return the relative path to another path identified by the passed + """Return the relative path to another path identified by the passed arguments. If the operation is not possible (because this is not related to the other path), raise ValueError. @@ -205,8 +173,7 @@ class PurePath(PathLike[str]): """ elif sys.version_info >= (3, 12): def relative_to(self, other: StrPath, /, *_deprecated: StrPath, walk_up: bool = False) -> Self: - """ - Return the relative path to another path identified by the passed + """Return the relative path to another path identified by the passed arguments. If the operation is not possible (because this is not related to the other path), raise ValueError. @@ -215,8 +182,7 @@ class PurePath(PathLike[str]): """ else: def relative_to(self, *other: StrPath) -> Self: - """ - Return the relative path to another path identified by the passed + """Return the relative path to another path identified by the passed arguments. If the operation is not possible (because this is not related to the other path), raise ValueError. @@ -225,25 +191,19 @@ class PurePath(PathLike[str]): """ def with_name(self, name: str) -> Self: - """ - Return a new path with the file name changed. - """ + """Return a new path with the file name changed.""" def with_stem(self, stem: str) -> Self: - """ - Return a new path with the stem changed. - """ + """Return a new path with the stem changed.""" def with_suffix(self, suffix: str) -> Self: - """ - Return a new path with the file suffix changed. If the path + """Return a new path with the file suffix changed. If the path has no suffix, add given suffix. If the given suffix is an empty string, remove the suffix from the path. """ def joinpath(self, *other: StrPath) -> Self: - """ - Combine this path with one or several arguments, and return a + """Combine this path with one or several arguments, and return a new path representing either a subpath (if all arguments are relative paths) or a totally different path (if one of the arguments is anchored). @@ -251,45 +211,37 @@ class PurePath(PathLike[str]): @property def parents(self) -> Sequence[Self]: - """ - A sequence of this path's logical parents. - """ + """A sequence of this path's logical parents.""" @property def parent(self) -> Self: - """ - The logical parent of the path. - """ + """The logical parent of the path.""" if sys.version_info < (3, 11): def __class_getitem__(cls, type: Any) -> GenericAlias: ... if sys.version_info >= (3, 12): def with_segments(self, *args: StrPath) -> Self: - """ - Construct a new path object from any number of path-like objects. + """Construct a new path object from any number of path-like objects. Subclasses may override this method to customize how new path objects are created from methods like `iterdir()`. """ class PurePosixPath(PurePath): - """ - PurePath subclass for non-Windows systems. + """PurePath subclass for non-Windows systems. On a POSIX system, instantiating a PurePath should return this object. However, you can also instantiate it directly on any system. """ class PureWindowsPath(PurePath): - """ - PurePath subclass for Windows systems. + """PurePath subclass for Windows systems. On a Windows system, instantiating a PurePath should return this object. However, you can also instantiate it directly on any system. """ class Path(PurePath): - """ - PurePath subclass that can make system calls. + """PurePath subclass that can make system calls. Path represents a filesystem path but unlike PurePath, also offers methods to do system calls on path objects. Depending on your system, @@ -305,219 +257,165 @@ class Path(PurePath): @classmethod def cwd(cls) -> Self: - """ - Return a new path pointing to the current working directory. - """ + """Return a new path pointing to the current working directory.""" if sys.version_info >= (3, 10): def stat(self, *, follow_symlinks: bool = True) -> stat_result: - """ - Return the result of the stat() system call on this path, like + """Return the result of the stat() system call on this path, like os.stat() does. """ def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None: - """ - Change the permissions of the path, like os.chmod(). - """ + """Change the permissions of the path, like os.chmod().""" else: def stat(self) -> stat_result: - """ - Return the result of the stat() system call on this path, like + """Return the result of the stat() system call on this path, like os.stat() does. """ def chmod(self, mode: int) -> None: - """ - Change the permissions of the path, like os.chmod(). - """ + """Change the permissions of the path, like os.chmod().""" if sys.version_info >= (3, 13): @classmethod def from_uri(cls, uri: str) -> Self: - """ - Return a new path from the given 'file' URI. - """ + """Return a new path from the given 'file' URI.""" def is_dir(self, *, follow_symlinks: bool = True) -> bool: - """ - Whether this path is a directory. - """ + """Whether this path is a directory.""" def is_file(self, *, follow_symlinks: bool = True) -> bool: - """ - Whether this path is a regular file (also True for symlinks pointing + """Whether this path is a regular file (also True for symlinks pointing to regular files). """ def read_text(self, encoding: str | None = None, errors: str | None = None, newline: str | None = None) -> str: - """ - Open the file in text mode, read it, and close the file. - """ + """Open the file in text mode, read it, and close the file.""" else: def __enter__(self) -> Self: ... def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... def is_dir(self) -> bool: - """ - Whether this path is a directory. - """ + """Whether this path is a directory.""" def is_file(self) -> bool: - """ - Whether this path is a regular file (also True for symlinks pointing + """Whether this path is a regular file (also True for symlinks pointing to regular files). """ def read_text(self, encoding: str | None = None, errors: str | None = None) -> str: - """ - Open the file in text mode, read it, and close the file. - """ + """Open the file in text mode, read it, and close the file.""" if sys.version_info >= (3, 13): def glob(self, pattern: str, *, case_sensitive: bool | None = None, recurse_symlinks: bool = False) -> Iterator[Self]: - """ - Iterate over this subtree and yield all existing files (of any + """Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern. """ def rglob(self, pattern: str, *, case_sensitive: bool | None = None, recurse_symlinks: bool = False) -> Iterator[Self]: - """ - Recursively yield all existing files (of any kind, including + """Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree. """ elif sys.version_info >= (3, 12): def glob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self, None, None]: - """ - Iterate over this subtree and yield all existing files (of any + """Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern. """ def rglob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self, None, None]: - """ - Recursively yield all existing files (of any kind, including + """Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree. """ else: def glob(self, pattern: str) -> Generator[Self, None, None]: - """ - Iterate over this subtree and yield all existing files (of any + """Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern. """ def rglob(self, pattern: str) -> Generator[Self, None, None]: - """ - Recursively yield all existing files (of any kind, including + """Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree. """ if sys.version_info >= (3, 12): def exists(self, *, follow_symlinks: bool = True) -> bool: - """ - Whether this path exists. + """Whether this path exists. This method normally follows symlinks; to check whether a symlink exists, add the argument follow_symlinks=False. """ else: def exists(self) -> bool: - """ - Whether this path exists. + """Whether this path exists. This method normally follows symlinks; to check whether a symlink exists, add the argument follow_symlinks=False. """ def is_symlink(self) -> bool: - """ - Whether this path is a symbolic link. - """ + """Whether this path is a symbolic link.""" def is_socket(self) -> bool: - """ - Whether this path is a socket. - """ + """Whether this path is a socket.""" def is_fifo(self) -> bool: - """ - Whether this path is a FIFO. - """ + """Whether this path is a FIFO.""" def is_block_device(self) -> bool: - """ - Whether this path is a block device. - """ + """Whether this path is a block device.""" def is_char_device(self) -> bool: - """ - Whether this path is a character device. - """ + """Whether this path is a character device.""" if sys.version_info >= (3, 12): def is_junction(self) -> bool: - """ - Whether this path is a junction. - """ + """Whether this path is a junction.""" def iterdir(self) -> Generator[Self, None, None]: - """ - Yield path objects of the directory contents. + """Yield path objects of the directory contents. The children are yielded in arbitrary order, and the special entries '.' and '..' are not included. """ def lchmod(self, mode: int) -> None: - """ - Like chmod(), except if the path points to a symlink, the symlink's + """Like chmod(), except if the path points to a symlink, the symlink's permissions are changed, rather than its target's. """ def lstat(self) -> stat_result: - """ - Like stat(), except if the path points to a symlink, the symlink's + """Like stat(), except if the path points to a symlink, the symlink's status information is returned, rather than its target's. """ def mkdir(self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None: - """ - Create a new directory at this given path. - """ + """Create a new directory at this given path.""" if sys.version_info >= (3, 14): @property def info(self) -> PathInfo: - """ - A PathInfo object that exposes the file type and other file attributes + """A PathInfo object that exposes the file type and other file attributes of this path. """ @overload def move_into(self, target_dir: _PathT) -> _PathT: # type: ignore[overload-overlap] - """ - Move this file or directory tree into the given existing directory. - """ + """Move this file or directory tree into the given existing directory.""" @overload def move_into(self, target_dir: StrPath) -> Self: ... # type: ignore[overload-overlap] @overload def move(self, target: _PathT) -> _PathT: # type: ignore[overload-overlap] - """ - Recursively move this file or directory tree to the given destination. - """ + """Recursively move this file or directory tree to the given destination.""" @overload def move(self, target: StrPath) -> Self: ... # type: ignore[overload-overlap] @overload def copy_into(self, target_dir: _PathT, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> _PathT: # type: ignore[overload-overlap] - """ - Copy this file or directory tree into the given existing directory. - """ + """Copy this file or directory tree into the given existing directory.""" @overload def copy_into(self, target_dir: StrPath, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> Self: ... # type: ignore[overload-overlap] @overload def copy(self, target: _PathT, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> _PathT: # type: ignore[overload-overlap] - """ - Recursively copy this file or directory tree to the given destination. - """ + """Recursively copy this file or directory tree to the given destination.""" @overload def copy(self, target: StrPath, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> Self: ... # type: ignore[overload-overlap] @@ -534,8 +432,7 @@ class Path(PurePath): errors: str | None = None, newline: str | None = None, ) -> TextIOWrapper: - """ - Open the file pointed to by this path and return a file object, as + """Open the file pointed to by this path and return a file object, as the built-in open() function does. """ # Unbuffered binary mode: returns a FileIO @@ -586,56 +483,37 @@ class Path(PurePath): if sys.platform == "win32": if sys.version_info < (3, 13): def owner(self: Never) -> str: # type: ignore[misc] - """ - Return the login name of the file owner. - """ + """Return the login name of the file owner.""" def group(self: Never) -> str: # type: ignore[misc] - """ - Return the group name of the file gid. - """ + """Return the group name of the file gid.""" else: if sys.version_info >= (3, 13): def owner(self, *, follow_symlinks: bool = True) -> str: - """ - Return the login name of the file owner. - """ + """Return the login name of the file owner.""" def group(self, *, follow_symlinks: bool = True) -> str: - """ - Return the group name of the file gid. - """ + """Return the group name of the file gid.""" else: def owner(self) -> str: - """ - Return the login name of the file owner. - """ + """Return the login name of the file owner.""" def group(self) -> str: - """ - Return the group name of the file gid. - """ + """Return the group name of the file gid.""" # This method does "exist" on Windows on <3.12, but always raises NotImplementedError # On py312+, it works properly on Windows, as with all other platforms if sys.platform == "win32" and sys.version_info < (3, 12): def is_mount(self: Never) -> bool: # type: ignore[misc] - """ - Check if this path is a mount point - """ + """Check if this path is a mount point""" else: def is_mount(self) -> bool: - """ - Check if this path is a mount point - """ + """Check if this path is a mount point""" def readlink(self) -> Self: - """ - Return the path to which the symbolic link points. - """ + """Return the path to which the symbolic link points.""" if sys.version_info >= (3, 10): def rename(self, target: StrPath) -> Self: - """ - Rename this path to the target path. + """Rename this path to the target path. The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, *not* the @@ -645,8 +523,7 @@ class Path(PurePath): """ def replace(self, target: StrPath) -> Self: - """ - Rename this path to the target path, overwriting if that path exists. + """Rename this path to the target path, overwriting if that path exists. The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, *not* the @@ -656,8 +533,7 @@ class Path(PurePath): """ else: def rename(self, target: str | PurePath) -> Self: - """ - Rename this path to the target path. + """Rename this path to the target path. The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, *not* the @@ -667,8 +543,7 @@ class Path(PurePath): """ def replace(self, target: str | PurePath) -> Self: - """ - Rename this path to the target path, overwriting if that path exists. + """Rename this path to the target path, overwriting if that path exists. The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, *not* the @@ -678,87 +553,66 @@ class Path(PurePath): """ def resolve(self, strict: bool = False) -> Self: - """ - Make the path absolute, resolving all symlinks on the way and also + """Make the path absolute, resolving all symlinks on the way and also normalizing it. """ def rmdir(self) -> None: - """ - Remove this directory. The directory must be empty. - """ + """Remove this directory. The directory must be empty.""" def symlink_to(self, target: StrOrBytesPath, target_is_directory: bool = False) -> None: - """ - Make this path a symlink pointing to the target path. + """Make this path a symlink pointing to the target path. Note the order of arguments (link, target) is the reverse of os.symlink. """ if sys.version_info >= (3, 10): def hardlink_to(self, target: StrOrBytesPath) -> None: - """ - Make this path a hard link pointing to the same file as *target*. + """Make this path a hard link pointing to the same file as *target*. Note the order of arguments (self, target) is the reverse of os.link's. """ def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: - """ - Create this file with the given access mode, if it doesn't exist. - """ + """Create this file with the given access mode, if it doesn't exist.""" def unlink(self, missing_ok: bool = False) -> None: - """ - Remove this file or link. + """Remove this file or link. If the path is a directory, use rmdir() instead. """ @classmethod def home(cls) -> Self: - """ - Return a new path pointing to expanduser('~'). - """ + """Return a new path pointing to expanduser('~').""" def absolute(self) -> Self: - """ - Return an absolute version of this path + """Return an absolute version of this path No normalization or symlink resolution is performed. Use resolve() to resolve symlinks and remove '..' segments. """ def expanduser(self) -> Self: - """ - Return a new path with expanded ~ and ~user constructs + """Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser) """ def read_bytes(self) -> bytes: - """ - Open the file in bytes mode, read it, and close the file. - """ + """Open the file in bytes mode, read it, and close the file.""" def samefile(self, other_path: StrPath) -> bool: - """ - Return whether other_path is the same or not as this file + """Return whether other_path is the same or not as this file (as returned by os.path.samefile()). """ def write_bytes(self, data: ReadableBuffer) -> int: - """ - Open the file in bytes mode, write to it, and close the file. - """ + """Open the file in bytes mode, write to it, and close the file.""" if sys.version_info >= (3, 10): def write_text( self, data: str, encoding: str | None = None, errors: str | None = None, newline: str | None = None ) -> int: - """ - Open the file in text mode, write to it, and close the file. - """ + """Open the file in text mode, write to it, and close the file.""" else: def write_text(self, data: str, encoding: str | None = None, errors: str | None = None) -> int: - """ - Open the file in text mode, write to it, and close the file. - """ + """Open the file in text mode, write to it, and close the file.""" if sys.version_info < (3, 12): if sys.version_info >= (3, 10): @deprecated("Deprecated as of Python 3.10 and removed in Python 3.12. Use hardlink_to() instead.") @@ -769,26 +623,20 @@ class Path(PurePath): def walk( self, top_down: bool = ..., on_error: Callable[[OSError], object] | None = ..., follow_symlinks: bool = ... ) -> Iterator[tuple[Self, list[str], list[str]]]: - """ - Walk the directory tree from this directory, similar to os.walk(). - """ + """Walk the directory tree from this directory, similar to os.walk().""" class PosixPath(Path, PurePosixPath): - """ - Path subclass for non-Windows systems. + """Path subclass for non-Windows systems. On a POSIX system, instantiating a Path should return this object. """ class WindowsPath(Path, PureWindowsPath): - """ - Path subclass for Windows systems. + """Path subclass for Windows systems. On a Windows system, instantiating a Path should return this object. """ if sys.version_info >= (3, 13): class UnsupportedOperation(NotImplementedError): - """ - An exception that is raised when an unsupported operation is attempted. - """ + """An exception that is raised when an unsupported operation is attempted.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/pathlib/types.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/pathlib/types.pyi index 4f18c21004..453000165f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/pathlib/types.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/pathlib/types.pyi @@ -1,4 +1,5 @@ """ + Protocols for supporting classes in pathlib. """ @@ -6,8 +7,7 @@ from typing import Protocol, runtime_checkable @runtime_checkable class PathInfo(Protocol): - """ - Protocol for path info objects, which support querying the file type. + """Protocol for path info objects, which support querying the file type. Methods may return cached results. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/pdb.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/pdb.pyi index 4916ccb378..0979de21dd 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/pdb.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/pdb.pyi @@ -1,4 +1,5 @@ """ + The Python Debugger Pdb ======================= @@ -358,13 +359,10 @@ _Mode: TypeAlias = Literal["inline", "cli"] line_prefix: str # undocumented class Restart(Exception): - """ - Causes a debugger to be restarted for the debugged python program. - """ + """Causes a debugger to be restarted for the debugged python program.""" def run(statement: str, globals: dict[str, Any] | None = None, locals: Mapping[str, Any] | None = None) -> None: - """ - Execute the *statement* (given as a string or a code object) + """Execute the *statement* (given as a string or a code object) under debugger control. The debugger prompt appears before any code is executed; you can set @@ -378,8 +376,7 @@ def run(statement: str, globals: dict[str, Any] | None = None, locals: Mapping[s """ def runeval(expression: str, globals: dict[str, Any] | None = None, locals: Mapping[str, Any] | None = None) -> Any: - """ - Evaluate the *expression* (given as a string or a code object) + """Evaluate the *expression* (given as a string or a code object) under debugger control. When runeval() returns, it returns the value of the expression. @@ -388,8 +385,7 @@ def runeval(expression: str, globals: dict[str, Any] | None = None, locals: Mapp def runctx(statement: str, globals: dict[str, Any], locals: Mapping[str, Any]) -> None: ... def runcall(func: Callable[_P, _T], *args: _P.args, **kwds: _P.kwargs) -> _T | None: - """ - Call the function (a function or method object, not a string) + """Call the function (a function or method object, not a string) with the given arguments. When runcall() returns, it returns whatever the function call @@ -399,18 +395,13 @@ def runcall(func: Callable[_P, _T], *args: _P.args, **kwds: _P.kwargs) -> _T | N if sys.version_info >= (3, 14): def set_default_backend(backend: _Backend) -> None: - """ - Set the default backend to use for Pdb instances. - """ + """Set the default backend to use for Pdb instances.""" def get_default_backend() -> _Backend: - """ - Get the default backend to use for Pdb instances. - """ + """Get the default backend to use for Pdb instances.""" def set_trace(*, header: str | None = None, commands: Iterable[str] | None = None) -> None: - """ - Enter the debugger at the calling stack frame. + """Enter the debugger at the calling stack frame. This is useful to hard-code a breakpoint at a given point in a program, even if the code is not otherwise being debugged (e.g. when @@ -420,8 +411,7 @@ if sys.version_info >= (3, 14): """ async def set_trace_async(*, header: str | None = None, commands: Iterable[str] | None = None) -> None: - """ - Enter the debugger at the calling stack frame, but in async mode. + """Enter the debugger at the calling stack frame, but in async mode. This should be used as await pdb.set_trace_async(). Users can do await if they enter the debugger with this function. Otherwise it's the same @@ -430,8 +420,7 @@ if sys.version_info >= (3, 14): else: def set_trace(*, header: str | None = None) -> None: - """ - Enter the debugger at the calling stack frame. + """Enter the debugger at the calling stack frame. This is useful to hard-code a breakpoint at a given point in a program, even if the code is not otherwise being debugged (e.g. when @@ -440,8 +429,7 @@ else: """ def post_mortem(t: TracebackType | None = None) -> None: - """ - Enter post-mortem debugging of the given *traceback*, or *exception* + """Enter post-mortem debugging of the given *traceback*, or *exception* object. If no traceback is given, it uses the one of the exception that is @@ -453,9 +441,7 @@ def post_mortem(t: TracebackType | None = None) -> None: """ def pm() -> None: - """ - Enter post-mortem debugging of the traceback found in sys.last_exc. - """ + """Enter post-mortem debugging of the traceback found in sys.last_exc.""" class Pdb(Bdb, Cmd): # Everything here is undocumented, except for __init__ @@ -506,8 +492,7 @@ class Pdb(Bdb, Cmd): ) -> None: ... if sys.version_info >= (3, 14): def set_trace(self, frame: FrameType | None = None, *, commands: Iterable[str] | None = None) -> None: - """ - Start debugging from frame. + """Start debugging from frame. If frame is not specified, debugging starts from caller's frame. """ @@ -523,8 +508,7 @@ class Pdb(Bdb, Cmd): user_opcode = Bdb.user_line def bp_commands(self, frame: FrameType) -> bool: - """ - Call every command that was set for the current active breakpoint + """Call every command that was set for the current active breakpoint (if there is one). Returns True if the normal interaction function must be called, @@ -536,34 +520,27 @@ class Pdb(Bdb, Cmd): def interaction(self, frame: FrameType | None, traceback: TracebackType | None) -> None: ... def displayhook(self, obj: object) -> None: - """ - Custom displayhook for the exec in default(), which prevents + """Custom displayhook for the exec in default(), which prevents assignment of the _ variable in the builtins. """ def handle_command_def(self, line: str) -> bool: - """ - Handles one command line during command list definition. - """ + """Handles one command line during command list definition.""" def defaultFile(self) -> str: - """ - Produce a reasonable default. - """ + """Produce a reasonable default.""" def lineinfo(self, identifier: str) -> tuple[None, None, None] | tuple[str, str, int]: ... if sys.version_info >= (3, 14): def checkline(self, filename: str, lineno: int, module_globals: _ModuleGlobals | None = None) -> int: - """ - Check whether specified line seems to be executable. + """Check whether specified line seems to be executable. Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank line or EOF). Warning: testing is not comprehensive. """ else: def checkline(self, filename: str, lineno: int) -> int: - """ - Check whether specified line seems to be executable. + """Check whether specified line seems to be executable. Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank line or EOF). Warning: testing is not comprehensive. @@ -577,8 +554,7 @@ class Pdb(Bdb, Cmd): def print_stack_entry(self, frame_lineno: tuple[FrameType, int], prompt_prefix: str = "\n-> ") -> None: ... def lookupmodule(self, filename: str) -> str | None: - """ - Helper function for break/clear parsing -- may be overridden. + """Helper function for break/clear parsing -- may be overridden. lookupmodule() translates (possibly incomplete) file or module name into an absolute file name. @@ -598,16 +574,14 @@ class Pdb(Bdb, Cmd): if sys.version_info >= (3, 13): def completedefault(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: - """ - Method called to complete an input line when no command-specific + """Method called to complete an input line when no command-specific complete_*() method is available. By default, it returns an empty list. """ def do_commands(self, arg: str) -> bool | None: - """ - (Pdb) commands [bpnumber] + """(Pdb) commands [bpnumber] (com) ... (com) end (Pdb) @@ -645,8 +619,7 @@ class Pdb(Bdb, Cmd): """ def do_break(self, arg: str, temporary: bool = ...) -> bool | None: - """ - b(reak) [ ([filename:]lineno | function) [, condition] ] + """b(reak) [ ([filename:]lineno | function) [, condition] ] Without argument, list all breaks. @@ -663,24 +636,21 @@ class Pdb(Bdb, Cmd): """ def do_tbreak(self, arg: str) -> bool | None: - """ - tbreak [ ([filename:]lineno | function) [, condition] ] + """tbreak [ ([filename:]lineno | function) [, condition] ] Same arguments as break, but sets a temporary breakpoint: it is automatically deleted when first hit. """ def do_enable(self, arg: str) -> bool | None: - """ - enable bpnumber [bpnumber ...] + """enable bpnumber [bpnumber ...] Enables the breakpoints given as a space separated list of breakpoint numbers. """ def do_disable(self, arg: str) -> bool | None: - """ - disable bpnumber [bpnumber ...] + """disable bpnumber [bpnumber ...] Disables the breakpoints given as a space separated list of breakpoint numbers. Disabling a breakpoint means it cannot @@ -690,8 +660,7 @@ class Pdb(Bdb, Cmd): """ def do_condition(self, arg: str) -> bool | None: - """ - condition bpnumber [condition] + """condition bpnumber [condition] Set a new condition for the breakpoint, an expression which must evaluate to true before the breakpoint is honored. If @@ -700,8 +669,7 @@ class Pdb(Bdb, Cmd): """ def do_ignore(self, arg: str) -> bool | None: - """ - ignore bpnumber [count] + """ignore bpnumber [count] Set the ignore count for the given breakpoint number. If count is omitted, the ignore count is set to 0. A breakpoint @@ -712,8 +680,7 @@ class Pdb(Bdb, Cmd): """ def do_clear(self, arg: str) -> bool | None: - """ - cl(ear) [filename:lineno | bpnumber ...] + """cl(ear) [filename:lineno | bpnumber ...] With a space separated list of breakpoint numbers, clear those breakpoints. Without argument, clear all breaks (but @@ -722,8 +689,7 @@ class Pdb(Bdb, Cmd): """ def do_where(self, arg: str) -> bool | None: - """ - w(here) [count] + """w(here) [count] Print a stack trace. If count is not specified, print the full stack. If count is 0, print the current frame entry. If count is positive, @@ -734,8 +700,7 @@ class Pdb(Bdb, Cmd): """ if sys.version_info >= (3, 13): def do_exceptions(self, arg: str) -> bool | None: - """ - exceptions [number] + """exceptions [number] List or change current exception in an exception chain. @@ -747,24 +712,21 @@ class Pdb(Bdb, Cmd): """ def do_up(self, arg: str) -> bool | None: - """ - u(p) [count] + """u(p) [count] Move the current frame count (default one) levels up in the stack trace (to an older frame). """ def do_down(self, arg: str) -> bool | None: - """ - d(own) [count] + """d(own) [count] Move the current frame count (default one) levels down in the stack trace (to a newer frame). """ def do_until(self, arg: str) -> bool | None: - """ - unt(il) [lineno] + """unt(il) [lineno] Without argument, continue execution until the line with a number greater than the current one is reached. With a line @@ -774,8 +736,7 @@ class Pdb(Bdb, Cmd): """ def do_step(self, arg: str) -> bool | None: - """ - s(tep) + """s(tep) Execute the current line, stop at the first possible occasion (either in a function that is called or in the current @@ -783,16 +744,14 @@ class Pdb(Bdb, Cmd): """ def do_next(self, arg: str) -> bool | None: - """ - n(ext) + """n(ext) Continue execution until the next line in the current function is reached or it returns. """ def do_run(self, arg: str) -> bool | None: - """ - run [args...] + """run [args...] Restart the debugged python program. If a string is supplied it is split with "shlex", and the result is used as the new @@ -801,22 +760,19 @@ class Pdb(Bdb, Cmd): """ def do_return(self, arg: str) -> bool | None: - """ - r(eturn) + """r(eturn) Continue execution until the current function returns. """ def do_continue(self, arg: str) -> bool | None: - """ - c(ont(inue)) + """c(ont(inue)) Continue execution, only stop when a breakpoint is encountered. """ def do_jump(self, arg: str) -> bool | None: - """ - j(ump) lineno + """j(ump) lineno Set the next line that will be executed. Only available in the bottom-most frame. This lets you jump back and execute @@ -829,8 +785,7 @@ class Pdb(Bdb, Cmd): """ def do_debug(self, arg: str) -> bool | None: - """ - debug code + """debug code Enter a recursive debugger that steps through the code argument (which is an arbitrary expression or statement to be @@ -838,50 +793,43 @@ class Pdb(Bdb, Cmd): """ def do_quit(self, arg: str) -> bool | None: - """ - q(uit) | exit + """q(uit) | exit Quit from the debugger. The program being executed is aborted. """ def do_EOF(self, arg: str) -> bool | None: - """ - EOF + """EOF Handles the receipt of EOF as a command. """ def do_args(self, arg: str) -> bool | None: - """ - a(rgs) + """a(rgs) Print the argument list of the current function. """ def do_retval(self, arg: str) -> bool | None: - """ - retval + """retval Print the return value for the last return of a function. """ def do_p(self, arg: str) -> bool | None: - """ - p expression + """p expression Print the value of the expression. """ def do_pp(self, arg: str) -> bool | None: - """ - pp expression + """pp expression Pretty-print the value of the expression. """ def do_list(self, arg: str) -> bool | None: - """ - l(ist) [first[, last] | .] + """l(ist) [first[, last] | .] List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous @@ -897,15 +845,13 @@ class Pdb(Bdb, Cmd): """ def do_whatis(self, arg: str) -> bool | None: - """ - whatis expression + """whatis expression Print the type of the argument. """ def do_alias(self, arg: str) -> bool | None: - """ - alias [name [command]] + """alias [name [command]] Create an alias called 'name' that executes 'command'. The command must *not* be enclosed in quotes. Replaceable @@ -931,15 +877,13 @@ class Pdb(Bdb, Cmd): """ def do_unalias(self, arg: str) -> bool | None: - """ - unalias name + """unalias name Delete the specified alias. """ def do_help(self, arg: str) -> bool | None: - """ - h(elp) + """h(elp) Without argument, print the list of available commands. With a command name as argument, print help about that command. @@ -967,8 +911,7 @@ class Pdb(Bdb, Cmd): do_l = do_list do_h = do_help def help_exec(self) -> None: - """ - (!) statement + """(!) statement Execute the (one-line) statement in the context of the current stack frame. The exclamation point can be omitted unless the @@ -998,14 +941,11 @@ class Pdb(Bdb, Cmd): def _select_frame(self, number: int) -> None: ... def _getval_except(self, arg: str, frame: FrameType | None = None) -> object: ... def _print_lines(self, lines: Sequence[str], start: int, breaks: Sequence[int] = (), frame: FrameType | None = None) -> None: - """ - Print a range of lines. - """ + """Print a range of lines.""" def _cmdloop(self) -> None: ... def do_display(self, arg: str) -> bool | None: - """ - display [expression] + """display [expression] Display the value of the expression if it changed, each time execution stops in the current frame. @@ -1014,30 +954,26 @@ class Pdb(Bdb, Cmd): """ def do_interact(self, arg: str) -> bool | None: - """ - interact + """interact Start an interactive interpreter whose global namespace contains all the (global and local) names found in the current scope. """ def do_longlist(self, arg: str) -> bool | None: - """ - ll | longlist + """ll | longlist List the whole source code for the current function or frame. """ def do_source(self, arg: str) -> bool | None: - """ - source expression + """source expression Try to get source code for the given object and display it. """ def do_undisplay(self, arg: str) -> bool | None: - """ - undisplay [expression] + """undisplay [expression] Do not display the expression any more in the current frame. @@ -1082,8 +1018,6 @@ if sys.version_info < (3, 10): def lasti2lineno(code: CodeType, lasti: int) -> int: ... class _rstr(str): - """ - String that doesn't quote its repr. - """ + """String that doesn't quote its repr.""" def __repr__(self) -> Self: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/pickle.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/pickle.pyi index ba907984c5..585e0b8541 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/pickle.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/pickle.pyi @@ -134,31 +134,22 @@ bytes_types: tuple[type[Any], ...] # undocumented @final class PickleBuffer: - """ - Wrapper for potentially out-of-band buffers - """ + """Wrapper for potentially out-of-band buffers""" def __new__(cls, buffer: ReadableBuffer) -> Self: ... def raw(self) -> memoryview: - """ - Return a memoryview of the raw memory underlying this buffer. + """Return a memoryview of the raw memory underlying this buffer. Will raise BufferError is the buffer isn't contiguous. """ def release(self) -> None: - """ - Release the underlying buffer exposed by the PickleBuffer object. - """ + """Release the underlying buffer exposed by the PickleBuffer object.""" def __buffer__(self, flags: int, /) -> memoryview: - """ - Return a buffer object that exposes the underlying memory of the object. - """ + """Return a buffer object that exposes the underlying memory of the object.""" def __release_buffer__(self, buffer: memoryview, /) -> None: - """ - Release the buffer object that exposes the underlying memory of the object. - """ + """Release the buffer object that exposes the underlying memory of the object.""" MARK: bytes STOP: bytes @@ -241,8 +232,7 @@ NEXT_BUFFER: bytes READONLY_BUFFER: bytes def encode_long(x: int) -> bytes: # undocumented - """ - Encode a long to a two's complement little-endian binary string. + """Encode a long to a two's complement little-endian binary string. Note that 0 is a special case, returning an empty string, to save a byte in the LONG1 pickling context. @@ -264,8 +254,7 @@ def encode_long(x: int) -> bytes: # undocumented """ def decode_long(data: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer) -> int: # undocumented - """ - Decode a long from a two's complement little-endian binary string. + """Decode a long from a two's complement little-endian binary string. >>> decode_long(b'') 0 @@ -298,8 +287,7 @@ class _Pickler: fix_imports: bool = True, buffer_callback: _BufferCallback = None, ) -> None: - """ - This takes a binary file for writing a pickle data stream. + """This takes a binary file for writing a pickle data stream. The optional *protocol* argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2, 3, 4 and 5. @@ -334,13 +322,10 @@ class _Pickler: """ def dump(self, obj: Any) -> None: - """ - Write a pickled representation of obj to the open file. - """ + """Write a pickled representation of obj to the open file.""" def clear_memo(self) -> None: - """ - Clears the pickler's "memo". + """Clears the pickler's "memo". The memo is the data structure that remembers which objects the pickler has already seen, so that shared or recursive objects @@ -361,8 +346,7 @@ class _Unpickler: errors: str = "strict", buffers: Iterable[Any] | None = None, ) -> None: - """ - This takes a binary file for reading a pickle data stream. + """This takes a binary file for reading a pickle data stream. The protocol version of the pickle is detected automatically, so no proto argument is needed. @@ -401,8 +385,7 @@ class _Unpickler: """ def load(self) -> Any: - """ - Read a pickled object representation from the open file. + """Read a pickled object representation from the open file. Return the reconstituted object hierarchy specified in the file. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/pickletools.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/pickletools.pyi index 0e55821975..a49a813a80 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/pickletools.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/pickletools.pyi @@ -35,8 +35,7 @@ class ArgumentDescriptor: def __init__(self, name: str, n: int, reader: _Reader, doc: str) -> None: ... def read_uint1(f: IO[bytes]) -> int: - """ - >>> import io + """>>> import io >>> read_uint1(io.BytesIO(b'\\xff')) 255 """ @@ -44,8 +43,7 @@ def read_uint1(f: IO[bytes]) -> int: uint1: ArgumentDescriptor def read_uint2(f: IO[bytes]) -> int: - """ - >>> import io + """>>> import io >>> read_uint2(io.BytesIO(b'\\xff\\x00')) 255 >>> read_uint2(io.BytesIO(b'\\xff\\xff')) @@ -55,8 +53,7 @@ def read_uint2(f: IO[bytes]) -> int: uint2: ArgumentDescriptor def read_int4(f: IO[bytes]) -> int: - """ - >>> import io + """>>> import io >>> read_int4(io.BytesIO(b'\\xff\\x00\\x00\\x00')) 255 >>> read_int4(io.BytesIO(b'\\x00\\x00\\x00\\x80')) == -(2**31) @@ -66,8 +63,7 @@ def read_int4(f: IO[bytes]) -> int: int4: ArgumentDescriptor def read_uint4(f: IO[bytes]) -> int: - """ - >>> import io + """>>> import io >>> read_uint4(io.BytesIO(b'\\xff\\x00\\x00\\x00')) 255 >>> read_uint4(io.BytesIO(b'\\x00\\x00\\x00\\x80')) == 2**31 @@ -77,8 +73,7 @@ def read_uint4(f: IO[bytes]) -> int: uint4: ArgumentDescriptor def read_uint8(f: IO[bytes]) -> int: - """ - >>> import io + """>>> import io >>> read_uint8(io.BytesIO(b'\\xff\\x00\\x00\\x00\\x00\\x00\\x00\\x00')) 255 >>> read_uint8(io.BytesIO(b'\\xff' * 8)) == 2**64-1 @@ -89,8 +84,7 @@ uint8: ArgumentDescriptor if sys.version_info >= (3, 12): def read_stringnl(f: IO[bytes], decode: bool = True, stripquotes: bool = True, *, encoding: str = "latin-1") -> bytes | str: - """ - >>> import io + """>>> import io >>> read_stringnl(io.BytesIO(b"'abcd'\\nefg\\n")) 'abcd' @@ -117,8 +111,7 @@ if sys.version_info >= (3, 12): else: def read_stringnl(f: IO[bytes], decode: bool = True, stripquotes: bool = True) -> bytes | str: - """ - >>> import io + """>>> import io >>> read_stringnl(io.BytesIO(b"'abcd'\\nefg\\n")) 'abcd' @@ -150,8 +143,7 @@ def read_stringnl_noescape(f: IO[bytes]) -> str: ... stringnl_noescape: ArgumentDescriptor def read_stringnl_noescape_pair(f: IO[bytes]) -> str: - """ - >>> import io + """>>> import io >>> read_stringnl_noescape_pair(io.BytesIO(b"Queue\\nEmpty\\njunk")) 'Queue Empty' """ @@ -159,8 +151,7 @@ def read_stringnl_noescape_pair(f: IO[bytes]) -> str: stringnl_noescape_pair: ArgumentDescriptor def read_string1(f: IO[bytes]) -> str: - """ - >>> import io + """>>> import io >>> read_string1(io.BytesIO(b"\\x00")) '' >>> read_string1(io.BytesIO(b"\\x03abcdef")) @@ -170,8 +161,7 @@ def read_string1(f: IO[bytes]) -> str: string1: ArgumentDescriptor def read_string4(f: IO[bytes]) -> str: - """ - >>> import io + """>>> import io >>> read_string4(io.BytesIO(b"\\x00\\x00\\x00\\x00abc")) '' >>> read_string4(io.BytesIO(b"\\x03\\x00\\x00\\x00abcdef")) @@ -185,8 +175,7 @@ def read_string4(f: IO[bytes]) -> str: string4: ArgumentDescriptor def read_bytes1(f: IO[bytes]) -> bytes: - """ - >>> import io + """>>> import io >>> read_bytes1(io.BytesIO(b"\\x00")) b'' >>> read_bytes1(io.BytesIO(b"\\x03abcdef")) @@ -196,8 +185,7 @@ def read_bytes1(f: IO[bytes]) -> bytes: bytes1: ArgumentDescriptor def read_bytes4(f: IO[bytes]) -> bytes: - """ - >>> import io + """>>> import io >>> read_bytes4(io.BytesIO(b"\\x00\\x00\\x00\\x00abc")) b'' >>> read_bytes4(io.BytesIO(b"\\x03\\x00\\x00\\x00abcdef")) @@ -211,8 +199,7 @@ def read_bytes4(f: IO[bytes]) -> bytes: bytes4: ArgumentDescriptor def read_bytes8(f: IO[bytes]) -> bytes: - """ - >>> import io, struct, sys + """>>> import io, struct, sys >>> read_bytes8(io.BytesIO(b"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00abc")) b'' >>> read_bytes8(io.BytesIO(b"\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00abcdef")) @@ -227,8 +214,7 @@ def read_bytes8(f: IO[bytes]) -> bytes: bytes8: ArgumentDescriptor def read_unicodestringnl(f: IO[bytes]) -> str: - """ - >>> import io + """>>> import io >>> read_unicodestringnl(io.BytesIO(b"abc\\\\uabcd\\njunk")) == 'abc\\uabcd' True """ @@ -236,8 +222,7 @@ def read_unicodestringnl(f: IO[bytes]) -> str: unicodestringnl: ArgumentDescriptor def read_unicodestring1(f: IO[bytes]) -> str: - """ - >>> import io + """>>> import io >>> s = 'abcd\\uabcd' >>> enc = s.encode('utf-8') >>> enc @@ -256,8 +241,7 @@ def read_unicodestring1(f: IO[bytes]) -> str: unicodestring1: ArgumentDescriptor def read_unicodestring4(f: IO[bytes]) -> str: - """ - >>> import io + """>>> import io >>> s = 'abcd\\uabcd' >>> enc = s.encode('utf-8') >>> enc @@ -276,8 +260,7 @@ def read_unicodestring4(f: IO[bytes]) -> str: unicodestring4: ArgumentDescriptor def read_unicodestring8(f: IO[bytes]) -> str: - """ - >>> import io + """>>> import io >>> s = 'abcd\\uabcd' >>> enc = s.encode('utf-8') >>> enc @@ -296,8 +279,7 @@ def read_unicodestring8(f: IO[bytes]) -> str: unicodestring8: ArgumentDescriptor def read_decimalnl_short(f: IO[bytes]) -> int: - """ - >>> import io + """>>> import io >>> read_decimalnl_short(io.BytesIO(b"1234\\n56")) 1234 @@ -308,8 +290,7 @@ def read_decimalnl_short(f: IO[bytes]) -> int: """ def read_decimalnl_long(f: IO[bytes]) -> int: - """ - >>> import io + """>>> import io >>> read_decimalnl_long(io.BytesIO(b"1234L\\n56")) 1234 @@ -322,8 +303,7 @@ decimalnl_short: ArgumentDescriptor decimalnl_long: ArgumentDescriptor def read_floatnl(f: IO[bytes]) -> float: - """ - >>> import io + """>>> import io >>> read_floatnl(io.BytesIO(b"-1.25\\n6")) -1.25 """ @@ -331,8 +311,7 @@ def read_floatnl(f: IO[bytes]) -> float: floatnl: ArgumentDescriptor def read_float8(f: IO[bytes]) -> float: - """ - >>> import io, struct + """>>> import io, struct >>> raw = struct.pack(">d", -1.25) >>> raw b'\\xbf\\xf4\\x00\\x00\\x00\\x00\\x00\\x00' @@ -343,8 +322,7 @@ def read_float8(f: IO[bytes]) -> float: float8: ArgumentDescriptor def read_long1(f: IO[bytes]) -> int: - """ - >>> import io + """>>> import io >>> read_long1(io.BytesIO(b"\\x00")) 0 >>> read_long1(io.BytesIO(b"\\x02\\xff\\x00")) @@ -360,8 +338,7 @@ def read_long1(f: IO[bytes]) -> int: long1: ArgumentDescriptor def read_long4(f: IO[bytes]) -> int: - """ - >>> import io + """>>> import io >>> read_long4(io.BytesIO(b"\\x02\\x00\\x00\\x00\\xff\\x00")) 255 >>> read_long4(io.BytesIO(b"\\x02\\x00\\x00\\x00\\xff\\x7f")) @@ -423,8 +400,7 @@ class OpcodeInfo: opcodes: list[OpcodeInfo] def genops(pickle: bytes | bytearray | IO[bytes]) -> Iterator[tuple[OpcodeInfo, Any | None, int | None]]: - """ - Generate all the opcodes in a pickle. + """Generate all the opcodes in a pickle. 'pickle' is a file-like object, or string, containing the pickle. @@ -448,9 +424,7 @@ def genops(pickle: bytes | bytearray | IO[bytes]) -> Iterator[tuple[OpcodeInfo, """ def optimize(p: bytes | bytearray | IO[bytes]) -> bytes: - """ - Optimize a pickle string by removing unused PUT opcodes - """ + """Optimize a pickle string by removing unused PUT opcodes""" def dis( pickle: bytes | bytearray | IO[bytes], @@ -459,8 +433,7 @@ def dis( indentlevel: int = 4, annotate: int = 0, ) -> None: - """ - Produce a symbolic disassembly of a pickle. + """Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/pipes.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/pipes.pyi index b72f5f5033..ba577166b4 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/pipes.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/pipes.pyi @@ -62,39 +62,27 @@ import os __all__ = ["Template"] class Template: - """ - Class representing a pipeline template. - """ + """Class representing a pipeline template.""" def reset(self) -> None: - """ - t.reset() restores a pipeline template to its initial state. - """ + """t.reset() restores a pipeline template to its initial state.""" def clone(self) -> Template: - """ - t.clone() returns a new pipeline template with identical + """t.clone() returns a new pipeline template with identical initial state as the current one. """ def debug(self, flag: bool) -> None: - """ - t.debug(flag) turns debugging on or off. - """ + """t.debug(flag) turns debugging on or off.""" def append(self, cmd: str, kind: str) -> None: - """ - t.append(cmd, kind) adds a new step at the end. - """ + """t.append(cmd, kind) adds a new step at the end.""" def prepend(self, cmd: str, kind: str) -> None: - """ - t.prepend(cmd, kind) adds a new step at the front. - """ + """t.prepend(cmd, kind) adds a new step at the front.""" def open(self, file: str, rw: str) -> os._wrap_close: - """ - t.open(file, rw) returns a pipe or file object open for + """t.open(file, rw) returns a pipe or file object open for reading or writing; the file is the other end of the pipeline. """ @@ -103,6 +91,4 @@ class Template: # Not documented, but widely used. # Documented as shlex.quote since 3.3. def quote(s: str) -> str: - """ - Return a shell-escaped version of the string *s*. - """ + """Return a shell-escaped version of the string *s*.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/pkgutil.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/pkgutil.pyi index f489320e8d..c95a7f3982 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/pkgutil.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/pkgutil.pyi @@ -27,17 +27,14 @@ if sys.version_info < (3, 12): _PathT = TypeVar("_PathT", bound=Iterable[str]) class ModuleInfo(NamedTuple): - """ - A namedtuple with minimal info about a module. - """ + """A namedtuple with minimal info about a module.""" module_finder: MetaPathFinderProtocol | PathEntryFinderProtocol name: str ispkg: bool def extend_path(path: _PathT, name: str) -> _PathT: - """ - Extend a package's path. + """Extend a package's path. Intended use is to place the following code in a package's __init__.py: @@ -71,8 +68,7 @@ def extend_path(path: _PathT, name: str) -> _PathT: if sys.version_info < (3, 12): class ImpImporter: - """ - PEP 302 Finder that wraps Python's "classic" import algorithm + """PEP 302 Finder that wraps Python's "classic" import algorithm ImpImporter(dirname) produces a PEP 302 finder that searches that directory. ImpImporter(None) produces a PEP 302 finder that searches @@ -85,17 +81,14 @@ if sys.version_info < (3, 12): def __init__(self, path: StrOrBytesPath | None = None) -> None: ... class ImpLoader: - """ - PEP 302 Loader that wraps Python's "classic" import algorithm - """ + """PEP 302 Loader that wraps Python's "classic" import algorithm""" def __init__(self, fullname: str, file: IO[str], filename: StrOrBytesPath, etc: tuple[str, str, int]) -> None: ... if sys.version_info < (3, 14): @deprecated("Use importlib.util.find_spec() instead. Will be removed in Python 3.14.") def find_loader(fullname: str) -> LoaderProtocol | None: - """ - Find a "loader" object for fullname + """Find a "loader" object for fullname This is a backwards compatibility wrapper around importlib.util.find_spec that converts most failures to ImportError @@ -104,8 +97,7 @@ if sys.version_info < (3, 14): @deprecated("Use importlib.util.find_spec() instead. Will be removed in Python 3.14.") def get_loader(module_or_name: str) -> LoaderProtocol | None: - """ - Get a "loader" object for module_or_name + """Get a "loader" object for module_or_name Returns None if the module cannot be found or imported. If the named module is not already imported, its containing package @@ -113,8 +105,7 @@ if sys.version_info < (3, 14): """ def get_importer(path_item: StrOrBytesPath) -> PathEntryFinderProtocol | None: - """ - Retrieve a finder for the given path item + """Retrieve a finder for the given path item The returned finder is cached in sys.path_importer_cache if it was newly created by a path hook. @@ -124,8 +115,7 @@ def get_importer(path_item: StrOrBytesPath) -> PathEntryFinderProtocol | None: """ def iter_importers(fullname: str = "") -> Iterator[MetaPathFinderProtocol | PathEntryFinderProtocol]: - """ - Yield finders for the given module name + """Yield finders for the given module name If fullname contains a '.', the finders will be for the package containing fullname, otherwise they will be all registered top level @@ -138,8 +128,7 @@ def iter_importers(fullname: str = "") -> Iterator[MetaPathFinderProtocol | Path """ def iter_modules(path: Iterable[StrOrBytesPath] | None = None, prefix: str = "") -> Iterator[ModuleInfo]: - """ - Yields ModuleInfo for all submodules on path, + """Yields ModuleInfo for all submodules on path, or, if path is None, all top-level modules on sys.path. 'path' should be either None or a list of paths to look for @@ -153,8 +142,7 @@ def read_code(stream: SupportsRead[bytes]) -> Any: ... # undocumented def walk_packages( path: Iterable[StrOrBytesPath] | None = None, prefix: str = "", onerror: Callable[[str], object] | None = None ) -> Iterator[ModuleInfo]: - """ - Yields ModuleInfo for all modules recursively + """Yields ModuleInfo for all modules recursively on path, or, if path is None, all accessible modules. 'path' should be either None or a list of paths to look for @@ -183,8 +171,7 @@ def walk_packages( """ def get_data(package: str, resource: str) -> bytes | None: - """ - Get a resource from a package. + """Get a resource from a package. This is a wrapper round the PEP 302 loader get_data API. The package argument should be the name of a package, in standard module format @@ -206,8 +193,7 @@ def get_data(package: str, resource: str) -> bytes | None: """ def resolve_name(name: str) -> Any: - """ - Resolve a name to an object. + """Resolve a name to an object. It is expected that `name` will be a string in one of the following formats, where W is shorthand for a valid Python identifier and dot stands diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/platform.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/platform.pyi index 1f1a4e1383..bcf0d8ba1b 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/platform.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/platform.pyi @@ -12,8 +12,7 @@ from typing import NamedTuple, type_check_only from typing_extensions import Self def libc_ver(executable: str | None = None, lib: str = "", version: str = "", chunksize: int = 16384) -> tuple[str, str]: - """ - Tries to determine the libc version that the file executable + """Tries to determine the libc version that the file executable (which defaults to the Python interpreter) is linked against. Returns a tuple of strings (lib,version) which default to the @@ -32,8 +31,7 @@ def win32_is_iot() -> bool: ... def mac_ver( release: str = "", versioninfo: tuple[str, str, str] = ("", "", ""), machine: str = "" ) -> tuple[str, tuple[str, str, str], str]: - """ - Get macOS version information and return it as tuple (release, + """Get macOS version information and return it as tuple (release, versioninfo, machine) with versioninfo being a tuple (version, dev_stage, non_release_version). @@ -44,8 +42,7 @@ def mac_ver( def java_ver( release: str = "", vendor: str = "", vminfo: tuple[str, str, str] = ("", "", ""), osinfo: tuple[str, str, str] = ("", "", "") ) -> tuple[str, str, tuple[str, str, str], tuple[str, str, str]]: - """ - Version interface for Jython. + """Version interface for Jython. Returns a tuple (release, vendor, vminfo, osinfo) with vminfo being a tuple (vm_name, vm_release, vm_vendor) and osinfo being a @@ -56,8 +53,7 @@ def java_ver( """ def system_alias(system: str, release: str, version: str) -> tuple[str, str, str]: - """ - Returns (system, release, version) aliased to common + """Returns (system, release, version) aliased to common marketing names used for some systems. It also does some reordering of the information in some cases @@ -65,8 +61,7 @@ def system_alias(system: str, release: str, version: str) -> tuple[str, str, str """ def architecture(executable: str = sys.executable, bits: str = "", linkage: str = "") -> tuple[str, str]: - """ - Queries the given executable (defaults to the Python interpreter + """Queries the given executable (defaults to the Python interpreter binary) for various architecture information. Returns a tuple (bits, linkage) which contains information about @@ -102,8 +97,7 @@ class _uname_result_base(NamedTuple): # uname_result emulates a 6-field named tuple, but the processor field # is lazily evaluated rather than being passed in to the constructor. class uname_result(_uname_result_base): - """ - A uname_result that's largely compatible with a + """A uname_result that's largely compatible with a simple namedtuple except that 'processor' is resolved late and cached to avoid calling "uname" except when needed. @@ -113,16 +107,13 @@ class uname_result(_uname_result_base): __match_args__ = ("system", "node", "release", "version", "machine") # pyright: ignore[reportAssignmentType] def __new__(_cls, system: str, node: str, release: str, version: str, machine: str) -> Self: - """ - Create new instance of uname_result_base(system, node, release, version, machine) - """ + """Create new instance of uname_result_base(system, node, release, version, machine)""" @property def processor(self) -> str: ... def uname() -> uname_result: - """ - Fairly portable uname interface. Returns a tuple + """Fairly portable uname interface. Returns a tuple of strings (system, node, release, version, machine, processor) identifying the underlying platform. @@ -133,44 +124,38 @@ def uname() -> uname_result: """ def system() -> str: - """ - Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'. + """Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'. An empty string is returned if the value cannot be determined. """ def node() -> str: - """ - Returns the computer's network name (which may not be fully + """Returns the computer's network name (which may not be fully qualified) An empty string is returned if the value cannot be determined. """ def release() -> str: - """ - Returns the system's release, e.g. '2.2.0' or 'NT' + """Returns the system's release, e.g. '2.2.0' or 'NT' An empty string is returned if the value cannot be determined. """ def version() -> str: - """ - Returns the system's release version, e.g. '#3 on degas' + """Returns the system's release version, e.g. '#3 on degas' An empty string is returned if the value cannot be determined. """ def machine() -> str: - """ - Returns the machine type, e.g. 'i386' + """Returns the machine type, e.g. 'i386' An empty string is returned if the value cannot be determined. """ def processor() -> str: - """ - Returns the (true) processor name, e.g. 'amdk6' + """Returns the (true) processor name, e.g. 'amdk6' An empty string is returned if the value cannot be determined. Note that many platforms do not provide this @@ -179,8 +164,7 @@ def processor() -> str: """ def python_implementation() -> str: - """ - Returns a string identifying the Python implementation. + """Returns a string identifying the Python implementation. Currently, the following implementations are identified: 'CPython' (C implementation of Python), @@ -189,16 +173,14 @@ def python_implementation() -> str: """ def python_version() -> str: - """ - Returns the Python version as string 'major.minor.patchlevel' + """Returns the Python version as string 'major.minor.patchlevel' Note that unlike the Python sys.version, the returned value will always include the patchlevel (it defaults to 0). """ def python_version_tuple() -> tuple[str, str, str]: - """ - Returns the Python version as tuple (major, minor, patchlevel) + """Returns the Python version as tuple (major, minor, patchlevel) of strings. Note that unlike the Python sys.version, the returned value @@ -206,8 +188,7 @@ def python_version_tuple() -> tuple[str, str, str]: """ def python_branch() -> str: - """ - Returns a string identifying the Python implementation + """Returns a string identifying the Python implementation branch. For CPython this is the SCM branch from which the @@ -217,8 +198,7 @@ def python_branch() -> str: """ def python_revision() -> str: - """ - Returns a string identifying the Python implementation + """Returns a string identifying the Python implementation revision. For CPython this is the SCM revision from which the @@ -228,20 +208,17 @@ def python_revision() -> str: """ def python_build() -> tuple[str, str]: - """ - Returns a tuple (buildno, builddate) stating the Python + """Returns a tuple (buildno, builddate) stating the Python build number and date as strings. """ def python_compiler() -> str: - """ - Returns a string identifying the compiler used for compiling + """Returns a string identifying the compiler used for compiling Python. """ def platform(aliased: bool = ..., terse: bool = ...) -> str: - """ - Returns a single string identifying the underlying platform + """Returns a single string identifying the underlying platform with as much useful information as possible (but no more :). The output is intended to be human readable rather than @@ -260,15 +237,11 @@ def platform(aliased: bool = ..., terse: bool = ...) -> str: if sys.version_info >= (3, 10): def freedesktop_os_release() -> dict[str, str]: - """ - Return operation system identification from freedesktop.org os-release - """ + """Return operation system identification from freedesktop.org os-release""" if sys.version_info >= (3, 13): class AndroidVer(NamedTuple): - """ - AndroidVer(release, api_level, manufacturer, model, device, is_emulator) - """ + """AndroidVer(release, api_level, manufacturer, model, device, is_emulator)""" release: str api_level: int @@ -278,9 +251,7 @@ if sys.version_info >= (3, 13): is_emulator: bool class IOSVersionInfo(NamedTuple): - """ - IOSVersionInfo(system, release, model, is_simulator) - """ + """IOSVersionInfo(system, release, model, is_simulator)""" system: str release: str @@ -296,8 +267,7 @@ if sys.version_info >= (3, 13): is_emulator: bool = False, ) -> AndroidVer: ... def ios_ver(system: str = "", release: str = "", model: str = "", is_simulator: bool = False) -> IOSVersionInfo: - """ - Get iOS version information, and return it as a namedtuple: + """Get iOS version information, and return it as a namedtuple: (system, release, model, is_simulator). If values can't be determined, they are set to values provided as @@ -306,6 +276,4 @@ if sys.version_info >= (3, 13): if sys.version_info >= (3, 14): def invalidate_caches() -> None: - """ - Invalidate the cached results. - """ + """Invalidate the cached results.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/plistlib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/plistlib.pyi index 998465397f..b2c73b45a5 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/plistlib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/plistlib.pyi @@ -67,9 +67,7 @@ from typing_extensions import Self __all__ = ["InvalidFileException", "FMT_XML", "FMT_BINARY", "load", "dump", "loads", "dumps", "UID"] class PlistFormat(Enum): - """ - An enumeration. - """ + """An enumeration.""" FMT_XML = 1 FMT_BINARY = 2 @@ -84,8 +82,7 @@ if sys.version_info >= (3, 13): dict_type: type[MutableMapping[str, Any]] = ..., aware_datetime: bool = False, ) -> Any: - """ - Read a .plist file. 'fp' should be a readable and binary file object. + """Read a .plist file. 'fp' should be a readable and binary file object. Return the unpacked root object (which usually is a dictionary). """ @@ -96,21 +93,18 @@ if sys.version_info >= (3, 13): dict_type: type[MutableMapping[str, Any]] = ..., aware_datetime: bool = False, ) -> Any: - """ - Read a .plist file from a bytes object. + """Read a .plist file from a bytes object. Return the unpacked root object (which usually is a dictionary). """ else: def load(fp: IO[bytes], *, fmt: PlistFormat | None = None, dict_type: type[MutableMapping[str, Any]] = ...) -> Any: - """ - Read a .plist file. 'fp' should be a readable and binary file object. + """Read a .plist file. 'fp' should be a readable and binary file object. Return the unpacked root object (which usually is a dictionary). """ def loads(value: ReadableBuffer, *, fmt: PlistFormat | None = None, dict_type: type[MutableMapping[str, Any]] = ...) -> Any: - """ - Read a .plist file from a bytes object. + """Read a .plist file from a bytes object. Return the unpacked root object (which usually is a dictionary). """ @@ -124,8 +118,7 @@ if sys.version_info >= (3, 13): skipkeys: bool = False, aware_datetime: bool = False, ) -> None: - """ - Write 'value' to a .plist file. 'fp' should be a writable, + """Write 'value' to a .plist file. 'fp' should be a writable, binary file object. """ @@ -137,9 +130,7 @@ if sys.version_info >= (3, 13): sort_keys: bool = True, aware_datetime: bool = False, ) -> bytes: - """ - Return a bytes object with the contents for a .plist file. - """ + """Return a bytes object with the contents for a .plist file.""" else: def dump( @@ -150,8 +141,7 @@ else: sort_keys: bool = True, skipkeys: bool = False, ) -> None: - """ - Write 'value' to a .plist file. 'fp' should be a writable, + """Write 'value' to a .plist file. 'fp' should be a writable, binary file object. """ @@ -162,9 +152,7 @@ else: skipkeys: bool = False, sort_keys: bool = True, ) -> bytes: - """ - Return a bytes object with the contents for a .plist file. - """ + """Return a bytes object with the contents for a .plist file.""" class UID: data: int diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/poplib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/poplib.pyi index 6981ba5fd6..7dd21d41a5 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/poplib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/poplib.pyi @@ -26,8 +26,7 @@ CRLF: Final = b"\r\n" HAVE_SSL: bool class POP3: - """ - This class supports both the minimal and optional command sets. + """This class supports both the minimal and optional command sets. Arguments can be strings or integers (where appropriate) (e.g.: retr(1) and retr('1') both work equally well. @@ -80,15 +79,13 @@ class POP3: def getwelcome(self) -> bytes: ... def set_debuglevel(self, level: int) -> None: ... def user(self, user: str) -> bytes: - """ - Send user name, return response + """Send user name, return response (should indicate password required). """ def pass_(self, pswd: str) -> bytes: - """ - Send password, return response + """Send password, return response (response includes message count, mailbox size). @@ -96,15 +93,13 @@ class POP3: """ def stat(self) -> tuple[int, int]: - """ - Get mailbox status. + """Get mailbox status. Result is tuple of 2 ints (message count, mailbox size) """ def list(self, which: Any | None = None) -> _LongResp: - """ - Request listing, return result. + """Request listing, return result. Result without a message number argument is in form ['response', ['mesg_num octets', ...], octets]. @@ -114,49 +109,37 @@ class POP3: """ def retr(self, which: Any) -> _LongResp: - """ - Retrieve whole message number 'which'. + """Retrieve whole message number 'which'. Result is in form ['response', ['line', ...], octets]. """ def dele(self, which: Any) -> bytes: - """ - Delete message number 'which'. + """Delete message number 'which'. Result is 'response'. """ def noop(self) -> bytes: - """ - Does nothing. + """Does nothing. One supposes the response indicates the server is alive. """ def rset(self) -> bytes: - """ - Unmark all messages marked for deletion. - """ + """Unmark all messages marked for deletion.""" def quit(self) -> bytes: - """ - Signoff: commit changes on server, unlock mailbox, close connection. - """ + """Signoff: commit changes on server, unlock mailbox, close connection.""" def close(self) -> None: - """ - Close the connection without assuming anything about it. - """ + """Close the connection without assuming anything about it.""" def rpop(self, user: str) -> bytes: - """ - Send RPOP command to access the mailbox with an alternate user. - """ + """Send RPOP command to access the mailbox with an alternate user.""" timestamp: Pattern[str] def apop(self, user: str, password: str) -> bytes: - """ - Authorisation + """Authorisation - only possible if server has supplied a timestamp in initial greeting. @@ -168,8 +151,7 @@ class POP3: """ def top(self, which: Any, howmuch: int) -> _LongResp: - """ - Retrieve message header of message number 'which' + """Retrieve message header of message number 'which' and first 'howmuch' lines of message body. Result is in form ['response', ['line', ...], octets]. @@ -177,8 +159,7 @@ class POP3: @overload def uidl(self) -> _LongResp: - """ - Return message digest (unique id) list. + """Return message digest (unique id) list. If 'which', result contains unique id for that message in the form 'response mesgnum uid', otherwise result is @@ -188,13 +169,10 @@ class POP3: @overload def uidl(self, which: Any) -> bytes: ... def utf8(self) -> bytes: - """ - Try to enter UTF-8 mode (see RFC 6856). Returns server response. - """ + """Try to enter UTF-8 mode (see RFC 6856). Returns server response.""" def capa(self) -> dict[str, _list[str]]: - """ - Return server capabilities (RFC 2449) as a dictionary + """Return server capabilities (RFC 2449) as a dictionary >>> c=poplib.POP3('localhost') >>> c.capa() {'IMPLEMENTATION': ['Cyrus', 'POP3', 'server', 'v2.2.12'], @@ -208,15 +186,13 @@ class POP3: """ def stls(self, context: ssl.SSLContext | None = None) -> bytes: - """ - Start a TLS session on the active connection as specified in RFC 2595. + """Start a TLS session on the active connection as specified in RFC 2595. context - a ssl.SSLContext """ class POP3_SSL(POP3): - """ - POP3 client class over SSL connection + """POP3 client class over SSL connection Instantiate with: POP3_SSL(hostname, port=995, context=None) @@ -232,8 +208,7 @@ class POP3_SSL(POP3): self, host: str, port: int = 995, *, timeout: float = ..., context: ssl.SSLContext | None = None ) -> None: ... def stls(self, context: Any = None) -> NoReturn: - """ - The method unconditionally raises an exception since the + """The method unconditionally raises an exception since the STLS command doesn't make any sense on an already established SSL/TLS session. """ @@ -250,8 +225,7 @@ class POP3_SSL(POP3): # "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: - """ - The method unconditionally raises an exception since the + """The method unconditionally raises an exception since the STLS command doesn't make any sense on an already established SSL/TLS session. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/posixpath.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/posixpath.pyi index 0df105876e..a997806454 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/posixpath.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/posixpath.pyi @@ -96,32 +96,25 @@ devnull: LiteralString # Overloads are necessary to work around python/mypy#17952 & python/mypy#11880 @overload def abspath(path: PathLike[AnyStr]) -> AnyStr: - """ - Return an absolute path. - """ + """Return an absolute path.""" @overload def abspath(path: AnyStr) -> AnyStr: ... @overload def basename(p: PathLike[AnyStr]) -> AnyStr: - """ - Returns the final component of a pathname - """ + """Returns the final component of a pathname""" @overload def basename(p: AnyOrLiteralStr) -> AnyOrLiteralStr: ... @overload def dirname(p: PathLike[AnyStr]) -> AnyStr: - """ - Returns the directory component of a pathname - """ + """Returns the directory component of a pathname""" @overload def dirname(p: AnyOrLiteralStr) -> AnyOrLiteralStr: ... @overload def expanduser(path: PathLike[AnyStr]) -> AnyStr: - """ - Expand ~ and ~user constructions. If user or $HOME is unknown, + """Expand ~ and ~user constructions. If user or $HOME is unknown, do nothing. """ @@ -129,8 +122,7 @@ def expanduser(path: PathLike[AnyStr]) -> AnyStr: def expanduser(path: AnyStr) -> AnyStr: ... @overload def expandvars(path: PathLike[AnyStr]) -> AnyStr: - """ - Expand shell variables of form $var and ${var}. Unknown variables + """Expand shell variables of form $var and ${var}. Unknown variables are left unchanged. """ @@ -138,25 +130,19 @@ def expandvars(path: PathLike[AnyStr]) -> AnyStr: def expandvars(path: AnyStr) -> AnyStr: ... @overload def normcase(s: PathLike[AnyStr]) -> AnyStr: - """ - Normalize case of pathname. Has no effect under Posix - """ + """Normalize case of pathname. Has no effect under Posix""" @overload def normcase(s: AnyOrLiteralStr) -> AnyOrLiteralStr: ... @overload def normpath(path: PathLike[AnyStr]) -> AnyStr: - """ - Normalize path, eliminating double slashes, etc. - """ + """Normalize path, eliminating double slashes, etc.""" @overload def normpath(path: AnyOrLiteralStr) -> AnyOrLiteralStr: ... @overload def commonpath(paths: Iterable[LiteralString]) -> LiteralString: - """ - Given a sequence of path names, returns the longest common sub-path. - """ + """Given a sequence of path names, returns the longest common sub-path.""" @overload def commonpath(paths: Iterable[StrPath]) -> str: ... @@ -168,8 +154,7 @@ def commonpath(paths: Iterable[BytesPath]) -> bytes: ... # as the parameter name is different in ntpath.join() @overload def join(a: LiteralString, /, *paths: LiteralString) -> LiteralString: - """ - Join two or more pathname components, inserting '/' as needed. + """Join two or more pathname components, inserting '/' as needed. If any component is an absolute path, all previous path components will be discarded. An empty last part will result in a path that ends with a separator. @@ -181,8 +166,7 @@ def join(a: StrPath, /, *paths: StrPath) -> str: ... def join(a: BytesPath, /, *paths: BytesPath) -> bytes: ... @overload def realpath(filename: PathLike[AnyStr], *, strict: bool | _AllowMissingType = False) -> AnyStr: - """ - Return the canonical path of the specified filename, eliminating any + """Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path. """ @@ -190,9 +174,7 @@ def realpath(filename: PathLike[AnyStr], *, strict: bool | _AllowMissingType = F def realpath(filename: AnyStr, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... @overload def relpath(path: LiteralString, start: LiteralString | None = None) -> LiteralString: - """ - Return a relative version of a path - """ + """Return a relative version of a path""" @overload def relpath(path: BytesPath, start: BytesPath | None = None) -> bytes: ... @@ -200,8 +182,7 @@ def relpath(path: BytesPath, start: BytesPath | None = None) -> bytes: ... def relpath(path: StrPath, start: StrPath | None = None) -> str: ... @overload def split(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: - """ - Split a pathname. Returns tuple "(head, tail)" where "tail" is + """Split a pathname. Returns tuple "(head, tail)" where "tail" is everything after the final slash. Either part may be empty. """ @@ -209,8 +190,7 @@ def split(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: def split(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... @overload def splitdrive(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: - """ - Split a pathname into drive and path. On Posix, drive is always + """Split a pathname into drive and path. On Posix, drive is always empty. """ @@ -218,8 +198,7 @@ def splitdrive(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: def splitdrive(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... @overload def splitext(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: - """ - Split the extension from a pathname. + """Split the extension from a pathname. Extension is everything from the last dot to the end, ignoring leading dots. Returns "(root, ext)"; ext may be empty. @@ -228,36 +207,26 @@ def splitext(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: @overload def splitext(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... def isabs(s: StrOrBytesPath) -> bool: - """ - Test whether a path is absolute - """ + """Test whether a path is absolute""" def islink(path: FileDescriptorOrPath) -> bool: - """ - Test whether a path is a symbolic link - """ + """Test whether a path is a symbolic link""" def ismount(path: FileDescriptorOrPath) -> bool: - """ - Test whether a path is a mount point - """ + """Test whether a path is a mount point""" def lexists(path: FileDescriptorOrPath) -> bool: - """ - Test whether a path exists. Returns True for broken symbolic links - """ + """Test whether a path exists. Returns True for broken symbolic links""" if sys.version_info >= (3, 12): def isjunction(path: StrOrBytesPath) -> bool: - """ - Test whether a path is a junction + """Test whether a path is a junction Junctions are not supported on the current platform """ @overload def splitroot(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr, AnyOrLiteralStr]: - """ - Split a pathname into drive, root and tail. + """Split a pathname into drive, root and tail. The tail contains anything after the root. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/pprint.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/pprint.pyi index 3d675fe65f..e3ea161cdb 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/pprint.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/pprint.pyi @@ -40,9 +40,7 @@ if sys.version_info >= (3, 10): sort_dicts: bool = True, underscore_numbers: bool = False, ) -> str: - """ - Format a Python object into a pretty-printed representation. - """ + """Format a Python object into a pretty-printed representation.""" else: def pformat( @@ -54,9 +52,7 @@ else: compact: bool = False, sort_dicts: bool = True, ) -> str: - """ - Format a Python object into a pretty-printed representation. - """ + """Format a Python object into a pretty-printed representation.""" if sys.version_info >= (3, 10): def pp( @@ -70,9 +66,7 @@ if sys.version_info >= (3, 10): sort_dicts: bool = False, underscore_numbers: bool = ..., ) -> None: - """ - Pretty-print a Python object - """ + """Pretty-print a Python object""" else: def pp( @@ -85,9 +79,7 @@ else: compact: bool = ..., sort_dicts: bool = False, ) -> None: - """ - Pretty-print a Python object - """ + """Pretty-print a Python object""" if sys.version_info >= (3, 10): def pprint( @@ -101,9 +93,7 @@ if sys.version_info >= (3, 10): sort_dicts: bool = True, underscore_numbers: bool = False, ) -> None: - """ - Pretty-print a Python object to a stream [default is sys.stdout]. - """ + """Pretty-print a Python object to a stream [default is sys.stdout].""" else: def pprint( @@ -116,24 +106,16 @@ else: compact: bool = False, sort_dicts: bool = True, ) -> None: - """ - Pretty-print a Python object to a stream [default is sys.stdout]. - """ + """Pretty-print a Python object to a stream [default is sys.stdout].""" def isreadable(object: object) -> bool: - """ - Determine if saferepr(object) is readable by eval(). - """ + """Determine if saferepr(object) is readable by eval().""" def isrecursive(object: object) -> bool: - """ - Determine if object requires a recursive representation. - """ + """Determine if object requires a recursive representation.""" def saferepr(object: object) -> str: - """ - Version of repr() which can handle recursive data structures. - """ + """Version of repr() which can handle recursive data structures.""" class PrettyPrinter: if sys.version_info >= (3, 10): @@ -148,8 +130,7 @@ class PrettyPrinter: sort_dicts: bool = True, underscore_numbers: bool = False, ) -> None: - """ - Handle pretty printing operations onto a stream using a set of + """Handle pretty printing operations onto a stream using a set of configured parameters. indent @@ -185,8 +166,7 @@ class PrettyPrinter: compact: bool = False, sort_dicts: bool = True, ) -> None: - """ - Handle pretty printing operations onto a stream using a set of + """Handle pretty printing operations onto a stream using a set of configured parameters. indent @@ -217,8 +197,7 @@ class PrettyPrinter: def isreadable(self, object: object) -> bool: ... def isrecursive(self, object: object) -> bool: ... def format(self, object: object, context: dict[int, int], maxlevels: int, level: int) -> tuple[str, bool, bool]: - """ - Format object for a specific context, returning a string + """Format object for a specific context, returning a string and flags indicating whether the representation is 'readable' and whether the object represents a recursive construct. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/profile.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/profile.pyi index 51cead2c53..9049102fa4 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/profile.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/profile.pyi @@ -10,8 +10,7 @@ from typing_extensions import ParamSpec, Self, TypeAlias __all__ = ["run", "runctx", "Profile"] def run(statement: str, filename: str | None = None, sort: str | int = -1) -> None: - """ - Run statement under profiler optionally saving results in filename + """Run statement under profiler optionally saving results in filename This function takes a single argument that can be passed to the "exec" statement, and an optional file name. In all cases this @@ -25,8 +24,7 @@ def run(statement: str, filename: str | None = None, sort: str | int = -1) -> No def runctx( statement: str, globals: dict[str, Any], locals: Mapping[str, Any], filename: str | None = None, sort: str | int = -1 ) -> None: - """ - Run statement under profiler, supplying your own globals and locals, + """Run statement under profiler, supplying your own globals and locals, optionally saving results in filename. statement and filename have the same semantics as profile.run @@ -37,8 +35,7 @@ _P = ParamSpec("_P") _Label: TypeAlias = tuple[str, int, str] class Profile: - """ - Profiler class. + """Profiler class. self.cur is always a tuple. Each such tuple corresponds to a stack frame that is currently active (self.cur[-2]). The following are the diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/pstats.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/pstats.pyi index 8a753ac4fc..e2f0153259 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/pstats.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/pstats.pyi @@ -22,9 +22,7 @@ _Selector: TypeAlias = str | float | int if sys.version_info >= (3, 11): class SortKey(StrEnum): - """ - An enumeration. - """ + """An enumeration.""" CALLS = "calls" CUMULATIVE = "cumulative" @@ -38,9 +36,7 @@ if sys.version_info >= (3, 11): else: class SortKey(str, Enum): - """ - An enumeration. - """ + """An enumeration.""" CALLS = "calls" CUMULATIVE = "cumulative" @@ -54,9 +50,7 @@ else: @dataclass(unsafe_hash=True) class FunctionProfile: - """ - FunctionProfile(ncalls: str, tottime: float, percall_tottime: float, cumtime: float, percall_cumtime: float, file_name: str, line_number: int) - """ + """FunctionProfile(ncalls: str, tottime: float, percall_tottime: float, cumtime: float, percall_cumtime: float, file_name: str, line_number: int)""" ncalls: str tottime: float @@ -68,9 +62,7 @@ class FunctionProfile: @dataclass(unsafe_hash=True) class StatsProfile: - """ - Class for keeping track of an item in inventory. - """ + """Class for keeping track of an item in inventory.""" total_tt: float func_profiles: dict[str, FunctionProfile] @@ -78,8 +70,7 @@ class StatsProfile: _SortArgDict: TypeAlias = dict[str, tuple[tuple[tuple[int, int], ...], str]] class Stats: - """ - This class is used for creating reports from data generated by the + """This class is used for creating reports from data generated by the Profile class. It is a "friend" of that class, and imports data either by direct access to members of Profile class, or by reading in a dictionary that was emitted (via marshal) from the Profile class. @@ -124,14 +115,10 @@ class Stats: def get_top_level_stats(self) -> None: ... def add(self, *arg_list: None | str | Profile | _cProfile | Self) -> Self: ... def dump_stats(self, filename: StrOrBytesPath) -> None: - """ - Write the profile data to a file we know how to load back. - """ + """Write the profile data to a file we know how to load back.""" def get_sort_arg_defs(self) -> _SortArgDict: - """ - Expand all abbreviations that are unique. - """ + """Expand all abbreviations that are unique.""" @overload def sort_stats(self, field: Literal[-1, 0, 1, 2]) -> Self: ... @@ -142,8 +129,7 @@ class Stats: def calc_callees(self) -> None: ... def eval_print_amount(self, sel: _Selector, list: list[str], msg: str) -> tuple[list[str], str]: ... def get_stats_profile(self) -> StatsProfile: - """ - This method returns an instance of StatsProfile, which contains a mapping + """This method returns an instance of StatsProfile, which contains a mapping of function names to instances of FunctionProfile. Each FunctionProfile instance holds information related to the function's profile such as how long the function took to run, how many times it was called, etc... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/pty.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/pty.pyi index 15df1614f6..28629d2665 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/pty.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/pty.pyi @@ -17,35 +17,29 @@ if sys.platform != "win32": CHILD: Final = 0 def openpty() -> tuple[int, int]: - """ - openpty() -> (master_fd, slave_fd) + """openpty() -> (master_fd, slave_fd) Open a pty master/slave pair, using os.openpty() if possible. """ if sys.version_info < (3, 14): @deprecated("Deprecated in 3.12, to be removed in 3.14; use openpty() instead") def master_open() -> tuple[int, str]: - """ - master_open() -> (master_fd, slave_name) + """master_open() -> (master_fd, slave_name) Open a pty master and return the fd, and the filename of the slave end. Deprecated, use openpty() instead. """ @deprecated("Deprecated in 3.12, to be removed in 3.14; use openpty() instead") def slave_open(tty_name: str) -> int: - """ - slave_open(tty_name) -> slave_fd + """slave_open(tty_name) -> slave_fd Open the pty slave and acquire the controlling terminal, returning opened filedescriptor. Deprecated, use openpty() instead. """ def fork() -> tuple[int, int]: - """ - fork() -> (pid, master_fd) + """fork() -> (pid, master_fd) Fork and make the child a session leader with a controlling terminal. """ def spawn(argv: str | Iterable[str], master_read: _Reader = ..., stdin_read: _Reader = ...) -> int: - """ - Create a spawned process. - """ + """Create a spawned process.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/pwd.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/pwd.pyi index 74c778f582..e0365eb4d6 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/pwd.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/pwd.pyi @@ -16,8 +16,7 @@ from typing import Any, Final, final if sys.platform != "win32": @final class struct_passwd(structseq[Any], tuple[str, str, int, int, str, str, str]): - """ - pwd.struct_passwd: Results from getpw*() routines. + """pwd.struct_passwd: Results from getpw*() routines. This object may be accessed either as a tuple of (pw_name,pw_passwd,pw_uid,pw_gid,pw_gecos,pw_dir,pw_shell) @@ -29,63 +28,46 @@ if sys.platform != "win32": @property def pw_name(self) -> str: - """ - user name - """ + """user name""" @property def pw_passwd(self) -> str: - """ - password - """ + """password""" @property def pw_uid(self) -> int: - """ - user id - """ + """user id""" @property def pw_gid(self) -> int: - """ - group id - """ + """group id""" @property def pw_gecos(self) -> str: - """ - real name - """ + """real name""" @property def pw_dir(self) -> str: - """ - home directory - """ + """home directory""" @property def pw_shell(self) -> str: - """ - shell program - """ + """shell program""" def getpwall() -> list[struct_passwd]: - """ - Return a list of all available password database entries, in arbitrary order. + """Return a list of all available password database entries, in arbitrary order. See help(pwd) for more on password database entries. """ def getpwuid(uid: int, /) -> struct_passwd: - """ - Return the password database entry for the given numeric user ID. + """Return the password database entry for the given numeric user ID. See `help(pwd)` for more on password database entries. """ def getpwnam(name: str, /) -> struct_passwd: - """ - Return the password database entry for the given user name. + """Return the password database entry for the given user name. See `help(pwd)` for more on password database entries. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/py_compile.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/py_compile.pyi index 64e992260f..aae28d6d80 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/py_compile.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/py_compile.pyi @@ -11,8 +11,7 @@ from typing import AnyStr __all__ = ["compile", "main", "PyCompileError", "PycInvalidationMode"] class PyCompileError(Exception): - """ - Exception raised when an error occurs while attempting to + """Exception raised when an error occurs while attempting to compile the file. To raise this exception, use @@ -45,9 +44,7 @@ class PyCompileError(Exception): def __init__(self, exc_type: type[BaseException], exc_value: BaseException, file: str, msg: str = "") -> None: ... class PycInvalidationMode(enum.Enum): - """ - An enumeration. - """ + """An enumeration.""" TIMESTAMP = 1 CHECKED_HASH = 2 @@ -63,8 +60,7 @@ def compile( invalidation_mode: PycInvalidationMode | None = None, quiet: int = 0, ) -> AnyStr | None: - """ - Byte-compile one Python source file to Python bytecode. + """Byte-compile one Python source file to Python bytecode. :param file: The source file name. :param cfile: The target byte compiled file name. When not given, this @@ -113,8 +109,7 @@ if sys.version_info >= (3, 10): else: def main(args: list[str] | None = None) -> int: - """ - Compile several source files. + """Compile several source files. The files named in 'args' (or on the command line, if 'args' is not specified) are compiled and the resulting bytecode is cached diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/pyclbr.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/pyclbr.pyi index 5b93215abd..41b81eb128 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/pyclbr.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/pyclbr.pyi @@ -48,9 +48,7 @@ from collections.abc import Mapping, Sequence __all__ = ["readmodule", "readmodule_ex", "Class", "Function"] class _Object: - """ - Information about Python class or function. - """ + """Information about Python class or function.""" module: str name: str @@ -74,9 +72,7 @@ class _Object: def __init__(self, module: str, name: str, file: str, lineno: int, parent: _Object | None) -> None: ... class Function(_Object): - """ - Information about a Python function, including methods. - """ + """Information about a Python function, including methods.""" if sys.version_info >= (3, 10): is_async: bool @@ -100,9 +96,7 @@ class Function(_Object): def __init__(self, module: str, name: str, file: str, lineno: int, parent: Function | Class | None = None) -> None: ... class Class(_Object): - """ - Information about a Python class. - """ + """Information about a Python class.""" super: list[Class | str] | None methods: dict[str, int] @@ -127,15 +121,13 @@ class Class(_Object): ) -> None: ... def readmodule(module: str, path: Sequence[str] | None = None) -> dict[str, Class]: - """ - Return Class objects for the top-level classes in module. + """Return Class objects for the top-level classes in module. This is the original interface, before Functions were added. """ def readmodule_ex(module: str, path: Sequence[str] | None = None) -> dict[str, Class | Function | list[str]]: - """ - Return a dictionary with all functions and classes in module. + """Return a dictionary with all functions and classes in module. Search for module in PATH + sys.path. If possible, include imported superclasses. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/pydoc.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/pydoc.pyi index 2a5cd6b449..d96df035bc 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/pydoc.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/pydoc.pyi @@ -61,83 +61,53 @@ class _Pager(Protocol): def __call__(self, text: str, title: str = "") -> None: ... def pathdirs() -> list[str]: - """ - Convert sys.path into a list of absolute, existing, unique paths. - """ + """Convert sys.path into a list of absolute, existing, unique paths.""" def getdoc(object: object) -> str: - """ - Get the doc string or comments for an object. - """ + """Get the doc string or comments for an object.""" def splitdoc(doc: AnyStr) -> tuple[AnyStr, AnyStr]: - """ - Split a doc string into a synopsis line (if any) and the rest. - """ + """Split a doc string into a synopsis line (if any) and the rest.""" def classname(object: object, modname: str) -> str: - """ - Get a class name and qualify it with a module name if necessary. - """ + """Get a class name and qualify it with a module name if necessary.""" def isdata(object: object) -> bool: - """ - Check if an object is of a type that probably means it's data. - """ + """Check if an object is of a type that probably means it's data.""" def replace(text: AnyStr, *pairs: AnyStr) -> AnyStr: - """ - Do a series of global replacements on a string. - """ + """Do a series of global replacements on a string.""" def cram(text: str, maxlen: int) -> str: - """ - Omit part of a string if needed to make it fit in a maximum length. - """ + """Omit part of a string if needed to make it fit in a maximum length.""" def stripid(text: str) -> str: - """ - Remove the hexadecimal id from a Python object representation. - """ + """Remove the hexadecimal id from a Python object representation.""" def allmethods(cl: type) -> MutableMapping[str, MethodType]: ... def visiblename(name: str, all: Container[str] | None = None, obj: object = None) -> bool: - """ - Decide whether to show documentation on a variable. - """ + """Decide whether to show documentation on a variable.""" def classify_class_attrs(object: object) -> list[tuple[str, str, type, str]]: - """ - Wrap inspect.classify_class_attrs, with fixup for data descriptors and bound methods. - """ + """Wrap inspect.classify_class_attrs, with fixup for data descriptors and bound methods.""" if sys.version_info >= (3, 13): @deprecated("Deprecated in Python 3.13.") def ispackage(path: str) -> bool: - """ - Guess whether a path refers to a package directory. - """ + """Guess whether a path refers to a package directory.""" else: def ispackage(path: str) -> bool: - """ - Guess whether a path refers to a package directory. - """ + """Guess whether a path refers to a package directory.""" def source_synopsis(file: IO[AnyStr]) -> AnyStr | None: - """ - Return the one-line summary of a file object, if present - """ + """Return the one-line summary of a file object, if present""" def synopsis(filename: str, cache: MutableMapping[str, tuple[int, str]] = {}) -> str | None: - """ - Get the one-line summary out of a module file. - """ + """Get the one-line summary out of a module file.""" class ErrorDuringImport(Exception): - """ - Errors that occurred while trying to import something to document it. - """ + """Errors that occurred while trying to import something to document it.""" filename: str exc: type[BaseException] | None @@ -146,13 +116,10 @@ class ErrorDuringImport(Exception): def __init__(self, filename: str, exc_info: OptExcInfo) -> None: ... def importfile(path: str) -> ModuleType: - """ - Import a Python source file or compiled file given its path. - """ + """Import a Python source file or compiled file given its path.""" def safeimport(path: str, forceload: bool = ..., cache: MutableMapping[str, ModuleType] = {}) -> ModuleType | None: - """ - Import a module; handle errors; return None if the module isn't found. + """Import a module; handle errors; return None if the module isn't found. If the module *is* found but an exception occurs, it's wrapped in an ErrorDuringImport exception and reraised. Unlike __import__, if a @@ -164,60 +131,40 @@ def safeimport(path: str, forceload: bool = ..., cache: MutableMapping[str, Modu class Doc: PYTHONDOCS: str def document(self, object: object, name: str | None = None, *args: Any) -> str: - """ - Generate documentation for an object. - """ + """Generate documentation for an object.""" def fail(self, object: object, name: str | None = None, *args: Any) -> NoReturn: - """ - Raise an exception for unimplemented types. - """ + """Raise an exception for unimplemented types.""" @abstractmethod def docmodule(self, object: object, name: str | None = None, *args: Any) -> str: - """ - Raise an exception for unimplemented types. - """ + """Raise an exception for unimplemented types.""" @abstractmethod def docclass(self, object: object, name: str | None = None, *args: Any) -> str: - """ - Raise an exception for unimplemented types. - """ + """Raise an exception for unimplemented types.""" @abstractmethod def docroutine(self, object: object, name: str | None = None, *args: Any) -> str: - """ - Raise an exception for unimplemented types. - """ + """Raise an exception for unimplemented types.""" @abstractmethod def docother(self, object: object, name: str | None = None, *args: Any) -> str: - """ - Raise an exception for unimplemented types. - """ + """Raise an exception for unimplemented types.""" @abstractmethod def docproperty(self, object: object, name: str | None = None, *args: Any) -> str: - """ - Raise an exception for unimplemented types. - """ + """Raise an exception for unimplemented types.""" @abstractmethod def docdata(self, object: object, name: str | None = None, *args: Any) -> str: - """ - Raise an exception for unimplemented types. - """ + """Raise an exception for unimplemented types.""" def getdocloc(self, object: object, basedir: str = ...) -> str | None: - """ - Return the location of module docs or None - """ + """Return the location of module docs or None""" class HTMLRepr(Repr): - """ - Class for safely making an HTML representation of a Python object. - """ + """Class for safely making an HTML representation of a Python object.""" def __init__(self) -> None: ... def escape(self, text: str) -> str: ... @@ -229,22 +176,16 @@ class HTMLRepr(Repr): def repr_unicode(self, x: AnyStr, level: complex) -> str: ... class HTMLDoc(Doc): - """ - Formatter class for HTML documentation. - """ + """Formatter class for HTML documentation.""" _repr_instance: HTMLRepr repr = _repr_instance.repr escape = _repr_instance.escape def page(self, title: str, contents: str) -> str: - """ - Format an HTML page. - """ + """Format an HTML page.""" if sys.version_info >= (3, 11): def heading(self, title: str, extras: str = "") -> str: - """ - Format a page heading. - """ + """Format a page heading.""" def section( self, @@ -256,19 +197,13 @@ class HTMLDoc(Doc): marginalia: str | None = None, gap: str = " ", ) -> str: - """ - Format a section with a heading. - """ + """Format a section with a heading.""" def multicolumn(self, list: list[_T], format: Callable[[_T], str]) -> str: - """ - Format a list of items into a multi-column list. - """ + """Format a list of items into a multi-column list.""" else: def heading(self, title: str, fgcol: str, bgcol: str, extras: str = "") -> str: - """ - Format a page heading. - """ + """Format a page heading.""" def section( self, @@ -281,45 +216,29 @@ class HTMLDoc(Doc): marginalia: str | None = None, gap: str = " ", ) -> str: - """ - Format a section with a heading. - """ + """Format a section with a heading.""" def multicolumn(self, list: list[_T], format: Callable[[_T], str], cols: int = 4) -> str: - """ - Format a list of items into a multi-column list. - """ + """Format a list of items into a multi-column list.""" def bigsection(self, title: str, *args: Any) -> str: - """ - Format a section with a big heading. - """ + """Format a section with a big heading.""" def preformat(self, text: str) -> str: - """ - Format literal preformatted text. - """ + """Format literal preformatted text.""" def grey(self, text: str) -> str: ... def namelink(self, name: str, *dicts: MutableMapping[str, str]) -> str: - """ - Make a link for an identifier, given name-to-URL mappings. - """ + """Make a link for an identifier, given name-to-URL mappings.""" def classlink(self, object: object, modname: str) -> str: - """ - Make a link for a class. - """ + """Make a link for a class.""" def modulelink(self, object: object) -> str: - """ - Make a link for a module. - """ + """Make a link for a module.""" def modpkglink(self, modpkginfo: tuple[str, str, bool, bool]) -> str: - """ - Make a link for a module or package to display in an index. - """ + """Make a link for a module or package to display in an index.""" def markup( self, @@ -329,20 +248,15 @@ class HTMLDoc(Doc): classes: Mapping[str, str] = {}, methods: Mapping[str, str] = {}, ) -> str: - """ - Mark up some plain text, given a context of symbols to look for. + """Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names. """ def formattree(self, tree: list[tuple[type, tuple[type, ...]] | list[Any]], modname: str, parent: type | None = None) -> str: - """ - Produce HTML for a class tree as given by inspect.getclasstree(). - """ + """Produce HTML for a class tree as given by inspect.getclasstree().""" def docmodule(self, object: object, name: str | None = None, mod: str | None = None, *ignored: Unused) -> str: - """ - Produce HTML documentation for a module object. - """ + """Produce HTML documentation for a module object.""" def docclass( self, @@ -353,19 +267,13 @@ class HTMLDoc(Doc): classes: Mapping[str, str] = {}, *ignored: Unused, ) -> str: - """ - Produce HTML documentation for a class object. - """ + """Produce HTML documentation for a class object.""" def formatvalue(self, object: object) -> str: - """ - Format an argument default value as text. - """ + """Format an argument default value as text.""" def docother(self, object: object, name: str | None = None, mod: Any | None = None, *ignored: Unused) -> str: - """ - Produce HTML documentation for a data object. - """ + """Produce HTML documentation for a data object.""" if sys.version_info >= (3, 11): def docroutine( # type: ignore[override] self, @@ -378,23 +286,17 @@ class HTMLDoc(Doc): cl: type | None = None, homecls: type | None = None, ) -> str: - """ - Produce HTML documentation for a function or method object. - """ + """Produce HTML documentation for a function or method object.""" def docproperty( self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None, *ignored: Unused ) -> str: - """ - Produce html documentation for a data descriptor. - """ + """Produce html documentation for a data descriptor.""" def docdata( self, object: object, name: str | None = None, mod: Any | None = None, cl: Any | None = None, *ignored: Unused ) -> str: - """ - Produce html documentation for a data descriptor. - """ + """Produce html documentation for a data descriptor.""" else: def docroutine( # type: ignore[override] self, @@ -406,39 +308,25 @@ class HTMLDoc(Doc): methods: Mapping[str, str] = {}, cl: type | None = None, ) -> str: - """ - Produce HTML documentation for a function or method object. - """ + """Produce HTML documentation for a function or method object.""" def docproperty(self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None) -> str: # type: ignore[override] - """ - Produce html documentation for a data descriptor. - """ + """Produce html documentation for a data descriptor.""" def docdata(self, object: object, name: str | None = None, mod: Any | None = None, cl: Any | None = None) -> str: # type: ignore[override] - """ - Produce html documentation for a data descriptor. - """ + """Produce html documentation for a data descriptor.""" if sys.version_info >= (3, 11): def parentlink(self, object: type | ModuleType, modname: str) -> str: - """ - Make a link for the enclosing class or module. - """ + """Make a link for the enclosing class or module.""" def index(self, dir: str, shadowed: MutableMapping[str, bool] | None = None) -> str: - """ - Generate an HTML index for a directory of modules. - """ + """Generate an HTML index for a directory of modules.""" def filelink(self, url: str, path: str) -> str: - """ - Make a link to source file. - """ + """Make a link to source file.""" class TextRepr(Repr): - """ - Class for safely making a text representation of a Python object. - """ + """Class for safely making a text representation of a Python object.""" def __init__(self) -> None: ... def repr1(self, x: object, level: complex) -> str: ... @@ -447,43 +335,29 @@ class TextRepr(Repr): def repr_instance(self, x: object, level: complex) -> str: ... class TextDoc(Doc): - """ - Formatter class for text documentation. - """ + """Formatter class for text documentation.""" _repr_instance: TextRepr repr = _repr_instance.repr def bold(self, text: str) -> str: - """ - Format a string in bold by overstriking. - """ + """Format a string in bold by overstriking.""" def indent(self, text: str, prefix: str = " ") -> str: - """ - Indent text by prepending a given prefix to each line. - """ + """Indent text by prepending a given prefix to each line.""" def section(self, title: str, contents: str) -> str: - """ - Format a section with a given heading. - """ + """Format a section with a given heading.""" def formattree( self, tree: list[tuple[type, tuple[type, ...]] | list[Any]], modname: str, parent: type | None = None, prefix: str = "" ) -> str: - """ - Render in text a class tree as returned by inspect.getclasstree(). - """ + """Render in text a class tree as returned by inspect.getclasstree().""" def docclass(self, object: object, name: str | None = None, mod: str | None = None, *ignored: Unused) -> str: - """ - Produce text documentation for a given class object. - """ + """Produce text documentation for a given class object.""" def formatvalue(self, object: object) -> str: - """ - Format an argument default value as text. - """ + """Format an argument default value as text.""" if sys.version_info >= (3, 11): def docroutine( # type: ignore[override] self, @@ -493,28 +367,20 @@ class TextDoc(Doc): cl: Any | None = None, homecls: Any | None = None, ) -> str: - """ - Produce text documentation for a function or method object. - """ + """Produce text documentation for a function or method object.""" def docmodule(self, object: object, name: str | None = None, mod: Any | None = None, *ignored: Unused) -> str: - """ - Produce text documentation for a given module object. - """ + """Produce text documentation for a given module object.""" def docproperty( self, object: object, name: str | None = None, mod: Any | None = None, cl: Any | None = None, *ignored: Unused ) -> str: - """ - Produce text documentation for a data descriptor. - """ + """Produce text documentation for a data descriptor.""" def docdata( self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None, *ignored: Unused ) -> str: - """ - Produce text documentation for a data descriptor. - """ + """Produce text documentation for a data descriptor.""" def docother( self, @@ -526,29 +392,19 @@ class TextDoc(Doc): maxlen: int | None = None, doc: Any | None = None, ) -> str: - """ - Produce text documentation for a data object. - """ + """Produce text documentation for a data object.""" else: def docroutine(self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None) -> str: # type: ignore[override] - """ - Produce text documentation for a function or method object. - """ + """Produce text documentation for a function or method object.""" def docmodule(self, object: object, name: str | None = None, mod: Any | None = None) -> str: # type: ignore[override] - """ - Produce text documentation for a given module object. - """ + """Produce text documentation for a given module object.""" def docproperty(self, object: object, name: str | None = None, mod: Any | None = None, cl: Any | None = None) -> str: # type: ignore[override] - """ - Produce text documentation for a data descriptor. - """ + """Produce text documentation for a data descriptor.""" def docdata(self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None) -> str: # type: ignore[override] - """ - Produce text documentation for a data descriptor. - """ + """Produce text documentation for a data descriptor.""" def docother( # type: ignore[override] self, @@ -559,62 +415,40 @@ class TextDoc(Doc): maxlen: int | None = None, doc: Any | None = None, ) -> str: - """ - Produce text documentation for a data object. - """ + """Produce text documentation for a data object.""" if sys.version_info >= (3, 13): def pager(text: str, title: str = "") -> None: - """ - The first time this is called, determine what kind of pager to use. - """ + """The first time this is called, determine what kind of pager to use.""" else: def pager(text: str) -> None: - """ - The first time this is called, determine what kind of pager to use. - """ + """The first time this is called, determine what kind of pager to use.""" def plain(text: str) -> str: - """ - Remove boldface formatting from text. - """ + """Remove boldface formatting from text.""" def describe(thing: Any) -> str: - """ - Produce a short description of the given thing. - """ + """Produce a short description of the given thing.""" def locate(path: str, forceload: bool = ...) -> object: - """ - Locate an object by name or dotted path, importing as necessary. - """ + """Locate an object by name or dotted path, importing as necessary.""" if sys.version_info >= (3, 13): def get_pager() -> _Pager: - """ - Decide what method to use for paging through text. - """ + """Decide what method to use for paging through text.""" def pipe_pager(text: str, cmd: str, title: str = "") -> None: - """ - Page through text by feeding it to another program. - """ + """Page through text by feeding it to another program.""" def tempfile_pager(text: str, cmd: str, title: str = "") -> None: - """ - Page through text by invoking a program on a temporary file. - """ + """Page through text by invoking a program on a temporary file.""" def tty_pager(text: str, title: str = "") -> None: - """ - Page through text on a text terminal. - """ + """Page through text on a text terminal.""" def plain_pager(text: str, title: str = "") -> None: - """ - Simply print unformatted text. This is the ultimate fallback. - """ + """Simply print unformatted text. This is the ultimate fallback.""" # For backwards compatibility. getpager = get_pager pipepager = pipe_pager @@ -623,44 +457,30 @@ if sys.version_info >= (3, 13): plainpager = plain_pager else: def getpager() -> Callable[[str], None]: - """ - Decide what method to use for paging through text. - """ + """Decide what method to use for paging through text.""" def pipepager(text: str, cmd: str) -> None: - """ - Page through text by feeding it to another program. - """ + """Page through text by feeding it to another program.""" def tempfilepager(text: str, cmd: str) -> None: - """ - Page through text by invoking a program on a temporary file. - """ + """Page through text by invoking a program on a temporary file.""" def ttypager(text: str) -> None: - """ - Page through text on a text terminal. - """ + """Page through text on a text terminal.""" def plainpager(text: str) -> None: - """ - Simply print unformatted text. This is the ultimate fallback. - """ + """Simply print unformatted text. This is the ultimate fallback.""" text: TextDoc html: HTMLDoc def resolve(thing: str | object, forceload: bool = ...) -> tuple[object, str] | None: - """ - Given an object or a path to an object, get the object and its name. - """ + """Given an object or a path to an object, get the object and its name.""" def render_doc( thing: str | object, title: str = "Python Library Documentation: %s", forceload: bool = ..., renderer: Doc | None = None ) -> str: - """ - Render text documentation, given an object or a path to an object. - """ + """Render text documentation, given an object or a path to an object.""" if sys.version_info >= (3, 11): def doc( @@ -670,9 +490,7 @@ if sys.version_info >= (3, 11): output: SupportsWrite[str] | None = None, is_cli: bool = False, ) -> None: - """ - Display text documentation, given an object or a path to an object. - """ + """Display text documentation, given an object or a path to an object.""" else: def doc( @@ -681,19 +499,13 @@ else: forceload: bool = ..., output: SupportsWrite[str] | None = None, ) -> None: - """ - Display text documentation, given an object or a path to an object. - """ + """Display text documentation, given an object or a path to an object.""" def writedoc(thing: str | object, forceload: bool = ...) -> None: - """ - Write HTML documentation to a file in the current directory. - """ + """Write HTML documentation to a file in the current directory.""" def writedocs(dir: str, pkgpath: str = "", done: Any | None = None) -> None: - """ - Write out HTML documentation for all modules in a directory tree. - """ + """Write out HTML documentation for all modules in a directory tree.""" class Helper: keywords: dict[str, str | tuple[str, str]] @@ -707,9 +519,7 @@ class Helper: def __call__(self, request: str | Helper | object = ...) -> None: ... def interact(self) -> None: ... def getline(self, prompt: str) -> str: - """ - Read one line, using input() when appropriate. - """ + """Read one line, using input() when appropriate.""" if sys.version_info >= (3, 11): def help(self, request: Any, is_cli: bool = False) -> None: ... else: @@ -727,9 +537,7 @@ class Helper: help: Helper class ModuleScanner: - """ - An interruptible scanner that searches module synopses. - """ + """An interruptible scanner that searches module synopses.""" quit: bool def run( @@ -741,12 +549,8 @@ class ModuleScanner: ) -> None: ... def apropos(key: str) -> None: - """ - Print all the one-line module summaries that contain a substring. - """ + """Print all the one-line module summaries that contain a substring.""" def ispath(x: object) -> TypeGuard[str]: ... def cli() -> None: - """ - Command-line interface (looks at sys.argv to decide what to do). - """ + """Command-line interface (looks at sys.argv to decide what to do).""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/pyexpat/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/pyexpat/__init__.pyi index 62c44a3136..4e7287715d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/pyexpat/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/pyexpat/__init__.pyi @@ -23,48 +23,35 @@ _Model: TypeAlias = tuple[int, int, str | None, tuple[Any, ...]] @final class XMLParserType: - """ - XML parser - """ + """XML parser""" def Parse(self, data: str | ReadableBuffer, isfinal: bool = False, /) -> int: - """ - Parse XML data. + """Parse XML data. 'isfinal' should be true at end of input. """ def ParseFile(self, file: SupportsRead[bytes], /) -> int: - """ - Parse XML data from file-like object. - """ + """Parse XML data from file-like object.""" def SetBase(self, base: str, /) -> None: - """ - Set the base URL for the parser. - """ + """Set the base URL for the parser.""" def GetBase(self) -> str | None: - """ - Return base URL string for the parser. - """ + """Return base URL string for the parser.""" def GetInputContext(self) -> bytes | None: - """ - Return the untranslated text of the input that caused the current event. + """Return the untranslated text of the input that caused the current event. If the event was generated by a large amount of text (such as a start tag for an element with many attributes), not all of the text may be available. """ def ExternalEntityParserCreate(self, context: str | None, encoding: str = ..., /) -> XMLParserType: - """ - Create a parser for parsing an external entity based on the information passed to the ExternalEntityRefHandler. - """ + """Create a parser for parsing an external entity based on the information passed to the ExternalEntityRefHandler.""" def SetParamEntityParsing(self, flag: int, /) -> int: - """ - Controls parsing of parameter entities (including the external DTD subset). + """Controls parsing of parameter entities (including the external DTD subset). Possible flag values are XML_PARAM_ENTITY_PARSING_NEVER, XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE and @@ -73,8 +60,7 @@ class XMLParserType: """ def UseForeignDTD(self, flag: bool = True, /) -> None: - """ - Allows the application to provide an artificial external subset if one is not specified as part of the document instance. + """Allows the application to provide an artificial external subset if one is not specified as part of the document instance. This readily allows the use of a 'default' document type controlled by the application, while still getting the advantage of providing document type @@ -82,14 +68,10 @@ class XMLParserType: """ def GetReparseDeferralEnabled(self) -> bool: - """ - Retrieve reparse deferral enabled status; always returns false with Expat <2.6.0. - """ + """Retrieve reparse deferral enabled status; always returns false with Expat <2.6.0.""" def SetReparseDeferralEnabled(self, enabled: bool, /) -> None: - """ - Enable/Disable reparse deferral; enabled by default with Expat >=2.6.0. - """ + """Enable/Disable reparse deferral; enabled by default with Expat >=2.6.0.""" @property def intern(self) -> dict[str, str]: ... @@ -135,16 +117,12 @@ class XMLParserType: SkippedEntityHandler: Callable[[str, bool], Any] | None def ErrorString(code: int, /) -> str: - """ - Returns string error for given number. - """ + """Returns string error for given number.""" # intern is undocumented def ParserCreate( encoding: str | None = None, namespace_separator: str | None = None, intern: dict[str, Any] | None = None ) -> XMLParserType: - """ - Return a new XML parser object. - """ + """Return a new XML parser object.""" expat_CAPI: CapsuleType diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/queue.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/queue.pyi index 72649f15c7..58b86a5976 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/queue.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/queue.pyi @@ -15,19 +15,14 @@ if sys.version_info >= (3, 13): _T = TypeVar("_T") class Full(Exception): - """ - Exception raised by Queue.put(block=0)/put_nowait(). - """ + """Exception raised by Queue.put(block=0)/put_nowait().""" if sys.version_info >= (3, 13): class ShutDown(Exception): - """ - Raised when put/get with shut-down queue. - """ + """Raised when put/get with shut-down queue.""" class Queue(Generic[_T]): - """ - Create a queue object with a given maximum size. + """Create a queue object with a given maximum size. If maxsize is <= 0, the queue size is infinite. """ @@ -47,8 +42,7 @@ class Queue(Generic[_T]): def __init__(self, maxsize: int = 0) -> None: ... def _init(self, maxsize: int) -> None: ... def empty(self) -> bool: - """ - Return True if the queue is empty, False otherwise (not reliable!). + """Return True if the queue is empty, False otherwise (not reliable!). This method is likely to be removed at some point. Use qsize() == 0 as a direct substitute, but be aware that either approach risks a race @@ -60,8 +54,7 @@ class Queue(Generic[_T]): """ def full(self) -> bool: - """ - Return True if the queue is full, False otherwise (not reliable!). + """Return True if the queue is full, False otherwise (not reliable!). This method is likely to be removed at some point. Use qsize() >= n as a direct substitute, but be aware that either approach risks a race @@ -70,8 +63,7 @@ class Queue(Generic[_T]): """ def get(self, block: bool = True, timeout: float | None = None) -> _T: - """ - Remove and return an item from the queue. + """Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is @@ -86,16 +78,14 @@ class Queue(Generic[_T]): """ def get_nowait(self) -> _T: - """ - Remove and return an item from the queue without blocking. + """Remove and return an item from the queue without blocking. Only get an item if one is immediately available. Otherwise raise the Empty exception. """ if sys.version_info >= (3, 13): def shutdown(self, immediate: bool = False) -> None: - """ - Shut-down the queue, making queue gets and puts raise ShutDown. + """Shut-down the queue, making queue gets and puts raise ShutDown. By default, gets will only raise once the queue is empty. Set 'immediate' to True to make gets raise immediately instead. @@ -107,8 +97,7 @@ class Queue(Generic[_T]): def _get(self) -> _T: ... def put(self, item: _T, block: bool = True, timeout: float | None = None) -> None: - """ - Put an item into the queue. + """Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is @@ -122,8 +111,7 @@ class Queue(Generic[_T]): """ def put_nowait(self, item: _T) -> None: - """ - Put an item into the queue without blocking. + """Put an item into the queue without blocking. Only enqueue the item if a free slot is immediately available. Otherwise raise the Full exception. @@ -131,8 +119,7 @@ class Queue(Generic[_T]): def _put(self, item: _T) -> None: ... def join(self) -> None: - """ - Blocks until all items in the Queue have been gotten and processed. + """Blocks until all items in the Queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() @@ -142,14 +129,11 @@ class Queue(Generic[_T]): """ def qsize(self) -> int: - """ - Return the approximate size of the queue (not reliable!). - """ + """Return the approximate size of the queue (not reliable!).""" def _qsize(self) -> int: ... def task_done(self) -> None: - """ - Indicate that a formerly enqueued task is complete. + """Indicate that a formerly enqueued task is complete. Used by Queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing @@ -167,15 +151,13 @@ class Queue(Generic[_T]): """ def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ class PriorityQueue(Queue[_T]): - """ - Variant of Queue that retrieves open entries in priority order (lowest first). + """Variant of Queue that retrieves open entries in priority order (lowest first). Entries are typically tuples of the form: (priority number, data). """ @@ -183,8 +165,6 @@ class PriorityQueue(Queue[_T]): queue: list[_T] class LifoQueue(Queue[_T]): - """ - Variant of Queue that retrieves most recently added entries first. - """ + """Variant of Queue that retrieves most recently added entries first.""" queue: list[_T] diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/quopri.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/quopri.pyi index 3f8daaf26a..adbf2c298e 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/quopri.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/quopri.pyi @@ -10,8 +10,7 @@ __all__ = ["encode", "decode", "encodestring", "decodestring"] class _Input(SupportsRead[bytes], SupportsNoArgReadline[bytes], Protocol): ... def encode(input: _Input, output: SupportsWrite[bytes], quotetabs: int, header: bool = False) -> None: - """ - Read 'input', apply quoted-printable encoding, and write to 'output'. + """Read 'input', apply quoted-printable encoding, and write to 'output'. 'input' and 'output' are binary file objects. The 'quotetabs' flag indicates whether embedded tabs and spaces should be quoted. Note that @@ -22,8 +21,7 @@ def encode(input: _Input, output: SupportsWrite[bytes], quotetabs: int, header: def encodestring(s: ReadableBuffer, quotetabs: bool = False, header: bool = False) -> bytes: ... def decode(input: _Input, output: SupportsWrite[bytes], header: bool = False) -> None: - """ - Read 'input', apply quoted-printable decoding, and write to 'output'. + """Read 'input', apply quoted-printable decoding, and write to 'output'. 'input' and 'output' are binary file objects. If 'header' is true, decode underscore as space (per RFC 1522). """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/random.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/random.pyi index 0a9e823655..c4c5cabe21 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/random.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/random.pyi @@ -87,8 +87,7 @@ if sys.version_info >= (3, 12): _T = TypeVar("_T") class Random(_random.Random): - """ - Random number generator base class used by bound module functions. + """Random number generator base class used by bound module functions. Used to instantiate instances of Random to get generators that don't share state. @@ -102,8 +101,7 @@ class Random(_random.Random): VERSION: ClassVar[int] def __init__(self, x: int | float | str | bytes | bytearray | None = None) -> None: # noqa: Y041 - """ - Initialize an instance. + """Initialize an instance. Optional argument x controls seeding, as for Random.seed(). """ @@ -111,8 +109,7 @@ class Random(_random.Random): # Ignore Y041, since random.seed doesn't treat int like a float subtype. Having an explicit # int better documents conventional usage of random.seed. def seed(self, a: int | float | str | bytes | bytearray | None = None, version: int = 2) -> None: # type: ignore[override] # noqa: Y041 - """ - Initialize internal state from a seed. + """Initialize internal state from a seed. The only supported seed types are None, int, float, str, bytes, and bytearray. @@ -129,37 +126,26 @@ class Random(_random.Random): """ def getstate(self) -> tuple[Any, ...]: - """ - Return internal state; can be passed to setstate() later. - """ + """Return internal state; can be passed to setstate() later.""" def setstate(self, state: tuple[Any, ...]) -> None: - """ - Restore internal state from object returned by getstate(). - """ + """Restore internal state from object returned by getstate().""" def randrange(self, start: int, stop: int | None = None, step: int = 1) -> int: - """ - Choose a random item from range(stop) or range(start, stop[, step]). + """Choose a random item from range(stop) or range(start, stop[, step]). Roughly equivalent to ``choice(range(start, stop, step))`` but supports arbitrarily large ranges and is optimized for common cases. """ def randint(self, a: int, b: int) -> int: - """ - Return random integer in range [a, b], including both end points. - """ + """Return random integer in range [a, b], including both end points.""" def randbytes(self, n: int) -> bytes: - """ - Generate n random bytes. - """ + """Generate n random bytes.""" def choice(self, seq: SupportsLenAndGetItem[_T]) -> _T: - """ - Choose a random element from a non-empty sequence. - """ + """Choose a random element from a non-empty sequence.""" def choices( self, @@ -169,26 +155,20 @@ class Random(_random.Random): cum_weights: Sequence[float | Fraction] | None = None, k: int = 1, ) -> list[_T]: - """ - Return a k sized list of population elements chosen with replacement. + """Return a k sized list of population elements chosen with replacement. If the relative weights or cumulative weights are not specified, the selections are made with equal probability. """ if sys.version_info >= (3, 11): def shuffle(self, x: MutableSequence[Any]) -> None: - """ - Shuffle list x in place, and return None. - """ + """Shuffle list x in place, and return None.""" else: def shuffle(self, x: MutableSequence[Any], random: Callable[[], float] | None = None) -> None: - """ - Shuffle list x in place, and return None. - """ + """Shuffle list x in place, and return None.""" if sys.version_info >= (3, 11): def sample(self, population: Sequence[_T], k: int, *, counts: Iterable[int] | None = None) -> list[_T]: - """ - Chooses k unique random elements from a population sequence. + """Chooses k unique random elements from a population sequence. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is @@ -217,8 +197,7 @@ class Random(_random.Random): """ else: def sample(self, population: Sequence[_T] | AbstractSet[_T], k: int, *, counts: Iterable[int] | None = None) -> list[_T]: - """ - Chooses k unique random elements from a population sequence. + """Chooses k unique random elements from a population sequence. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is @@ -247,8 +226,7 @@ class Random(_random.Random): """ def uniform(self, a: float, b: float) -> float: - """ - Get a random number in the range [a, b) or [a, b] depending on rounding. + """Get a random number in the range [a, b) or [a, b] depending on rounding. The mean (expected value) and variance of the random variable are: @@ -257,8 +235,7 @@ class Random(_random.Random): """ def triangular(self, low: float = 0.0, high: float = 1.0, mode: float | None = None) -> float: - """ - Triangular distribution. + """Triangular distribution. Continuous distribution bounded by given lower and upper limits, and having a given mode value in-between. @@ -272,8 +249,7 @@ class Random(_random.Random): """ if sys.version_info >= (3, 12): def binomialvariate(self, n: int = 1, p: float = 0.5) -> int: - """ - Binomial random variable. + """Binomial random variable. Gives the number of successes for *n* independent trials with the probability of success in each trial being *p*: @@ -295,8 +271,7 @@ class Random(_random.Random): """ def betavariate(self, alpha: float, beta: float) -> float: - """ - Beta distribution. + """Beta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1. @@ -308,8 +283,7 @@ class Random(_random.Random): """ if sys.version_info >= (3, 12): def expovariate(self, lambd: float = 1.0) -> float: - """ - Exponential distribution. + """Exponential distribution. lambd is 1.0 divided by the desired mean. It should be nonzero. (The parameter would be called "lambda", but that is @@ -324,8 +298,7 @@ class Random(_random.Random): """ else: def expovariate(self, lambd: float) -> float: - """ - Exponential distribution. + """Exponential distribution. lambd is 1.0 divided by the desired mean. It should be nonzero. (The parameter would be called "lambda", but that is @@ -340,8 +313,7 @@ class Random(_random.Random): """ def gammavariate(self, alpha: float, beta: float) -> float: - """ - Gamma distribution. Not the gamma function! + """Gamma distribution. Not the gamma function! Conditions on the parameters are alpha > 0 and beta > 0. @@ -358,8 +330,7 @@ class Random(_random.Random): """ if sys.version_info >= (3, 11): def gauss(self, mu: float = 0.0, sigma: float = 1.0) -> float: - """ - Gaussian distribution. + """Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function. @@ -368,15 +339,13 @@ class Random(_random.Random): """ def normalvariate(self, mu: float = 0.0, sigma: float = 1.0) -> float: - """ - Normal distribution. + """Normal distribution. mu is the mean, and sigma is the standard deviation. """ else: def gauss(self, mu: float, sigma: float) -> float: - """ - Gaussian distribution. + """Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function. @@ -385,15 +354,13 @@ class Random(_random.Random): """ def normalvariate(self, mu: float, sigma: float) -> float: - """ - Normal distribution. + """Normal distribution. mu is the mean, and sigma is the standard deviation. """ def lognormvariate(self, mu: float, sigma: float) -> float: - """ - Log normal distribution. + """Log normal distribution. If you take the natural logarithm of this distribution, you'll get a normal distribution with mean mu and standard deviation sigma. @@ -401,8 +368,7 @@ class Random(_random.Random): """ def vonmisesvariate(self, mu: float, kappa: float) -> float: - """ - Circular data distribution. + """Circular data distribution. mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or @@ -411,21 +377,17 @@ class Random(_random.Random): """ def paretovariate(self, alpha: float) -> float: - """ - Pareto distribution. alpha is the shape parameter. - """ + """Pareto distribution. alpha is the shape parameter.""" def weibullvariate(self, alpha: float, beta: float) -> float: - """ - Weibull distribution. + """Weibull distribution. alpha is the scale parameter and beta is the shape parameter. """ # SystemRandom is not implemented for all OS's; good on Windows & Linux class SystemRandom(Random): - """ - Alternate random number generator using sources provided + """Alternate random number generator using sources provided by the operating system (such as /dev/urandom on Unix or CryptGenRandom on Windows). @@ -433,19 +395,13 @@ class SystemRandom(Random): """ def getrandbits(self, k: int) -> int: # k can be passed by keyword - """ - getrandbits(k) -> x. Generates an int with k random bits. - """ + """getrandbits(k) -> x. Generates an int with k random bits.""" def getstate(self, *args: Any, **kwds: Any) -> NoReturn: - """ - Method should not be called for a system random number generator. - """ + """Method should not be called for a system random number generator.""" def setstate(self, *args: Any, **kwds: Any) -> NoReturn: - """ - Method should not be called for a system random number generator. - """ + """Method should not be called for a system random number generator.""" _inst: Random seed = _inst.seed diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/re.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/re.pyi index 0839d419ca..a45823c6d2 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/re.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/re.pyi @@ -162,8 +162,7 @@ _T = TypeVar("_T") # The implementation defines this in re._constants (version_info >= 3, 11) or # sre_constants. Typeshed has it here because its __module__ attribute is set to "re". class error(Exception): - """ - Exception raised for invalid regular expressions. + """Exception raised for invalid regular expressions. Attributes: @@ -183,53 +182,38 @@ class error(Exception): @final class Match(Generic[AnyStr]): - """ - The result of re.match() and re.search(). + """The result of re.match() and re.search(). Match objects always have a boolean value of True. """ @property def pos(self) -> int: - """ - The index into the string at which the RE engine started looking for a match. - """ + """The index into the string at which the RE engine started looking for a match.""" @property def endpos(self) -> int: - """ - The index into the string beyond which the RE engine will not go. - """ + """The index into the string beyond which the RE engine will not go.""" @property def lastindex(self) -> int | None: - """ - The integer index of the last matched capturing group. - """ + """The integer index of the last matched capturing group.""" @property def lastgroup(self) -> str | None: - """ - The name of the last matched capturing group. - """ + """The name of the last matched capturing group.""" @property def string(self) -> AnyStr: - """ - The string passed to match() or search(). - """ + """The string passed to match() or search().""" # The regular expression object whose match() or search() method produced # this match instance. @property def re(self) -> Pattern[AnyStr]: - """ - The regular expression object. - """ + """The regular expression object.""" @overload def expand(self: Match[str], template: str) -> str: - """ - Return the string obtained by doing backslash substitution on the string template, as done by the sub() method. - """ + """Return the string obtained by doing backslash substitution on the string template, as done by the sub() method.""" @overload def expand(self: Match[bytes], template: ReadableBuffer) -> bytes: ... @@ -238,8 +222,7 @@ class Match(Generic[AnyStr]): # group() returns "AnyStr" or "AnyStr | None", depending on the pattern. @overload def group(self, group: Literal[0] = 0, /) -> AnyStr: - """ - group([group1, ...]) -> str or tuple. + """group([group1, ...]) -> str or tuple. Return subgroup(s) of the match by indices or names. For 0 returns the entire match. """ @@ -252,8 +235,7 @@ class Match(Generic[AnyStr]): # "AnyStr | None", depending on the pattern. @overload def groups(self) -> tuple[AnyStr | MaybeNone, ...]: - """ - Return a tuple containing all the subgroups of the match, from 1. + """Return a tuple containing all the subgroups of the match, from 1. default Is used for groups that did not participate in the match. @@ -265,8 +247,7 @@ class Match(Generic[AnyStr]): # "AnyStr | None", depending on the pattern. @overload def groupdict(self) -> dict[str, AnyStr | MaybeNone]: - """ - Return a dictionary containing all the named subgroups of the match, keyed by the subgroup name. + """Return a dictionary containing all the named subgroups of the match, keyed by the subgroup name. default Is used for groups that did not participate in the match. @@ -275,72 +256,51 @@ class Match(Generic[AnyStr]): @overload def groupdict(self, default: _T) -> dict[str, AnyStr | _T]: ... def start(self, group: int | str = 0, /) -> int: - """ - Return index of the start of the substring matched by group. - """ + """Return index of the start of the substring matched by group.""" def end(self, group: int | str = 0, /) -> int: - """ - Return index of the end of the substring matched by group. - """ + """Return index of the end of the substring matched by group.""" def span(self, group: int | str = 0, /) -> tuple[int, int]: - """ - For match object m, return the 2-tuple (m.start(group), m.end(group)). - """ + """For match object m, return the 2-tuple (m.start(group), m.end(group)).""" @property def regs(self) -> tuple[tuple[int, int], ...]: ... # undocumented # __getitem__() returns "AnyStr" or "AnyStr | None", depending on the pattern. @overload def __getitem__(self, key: Literal[0], /) -> AnyStr: - """ - Return self[key]. - """ + """Return self[key].""" @overload def __getitem__(self, key: int | str, /) -> AnyStr | MaybeNone: ... def __copy__(self) -> Match[AnyStr]: ... def __deepcopy__(self, memo: Any, /) -> Match[AnyStr]: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" @final class Pattern(Generic[AnyStr]): - """ - Compiled regular expression object. - """ + """Compiled regular expression object.""" @property def flags(self) -> int: - """ - The regex matching flags. - """ + """The regex matching flags.""" @property def groupindex(self) -> Mapping[str, int]: - """ - A dictionary mapping group names to group numbers. - """ + """A dictionary mapping group names to group numbers.""" @property def groups(self) -> int: - """ - The number of capturing groups in the pattern. - """ + """The number of capturing groups in the pattern.""" @property def pattern(self) -> AnyStr: - """ - The pattern string from which the RE object was compiled. - """ + """The pattern string from which the RE object was compiled.""" @overload def search(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Match[str] | None: - """ - Scan through string looking for a match, and return a corresponding match object instance. + """Scan through string looking for a match, and return a corresponding match object instance. Return None if no position in the string matches. """ @@ -351,9 +311,7 @@ class Pattern(Generic[AnyStr]): def search(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Match[AnyStr] | None: ... @overload def match(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Match[str] | None: - """ - Matches zero or more characters at the beginning of the string. - """ + """Matches zero or more characters at the beginning of the string.""" @overload def match(self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize) -> Match[bytes] | None: ... @@ -361,9 +319,7 @@ class Pattern(Generic[AnyStr]): def match(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Match[AnyStr] | None: ... @overload def fullmatch(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Match[str] | None: - """ - Matches against all of the string. - """ + """Matches against all of the string.""" @overload def fullmatch( @@ -373,9 +329,7 @@ class Pattern(Generic[AnyStr]): def fullmatch(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Match[AnyStr] | None: ... @overload def split(self: Pattern[str], string: str, maxsplit: int = 0) -> list[str | MaybeNone]: - """ - Split string by the occurrences of pattern. - """ + """Split string by the occurrences of pattern.""" @overload def split(self: Pattern[bytes], string: ReadableBuffer, maxsplit: int = 0) -> list[bytes | MaybeNone]: ... @@ -384,9 +338,7 @@ class Pattern(Generic[AnyStr]): # return type depends on the number of groups in the pattern @overload def findall(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> list[Any]: - """ - Return a list of all non-overlapping matches of pattern in string. - """ + """Return a list of all non-overlapping matches of pattern in string.""" @overload def findall(self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize) -> list[Any]: ... @@ -394,8 +346,7 @@ class Pattern(Generic[AnyStr]): def findall(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> list[AnyStr]: ... @overload def finditer(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Iterator[Match[str]]: - """ - Return an iterator over all non-overlapping matches for the RE pattern in string. + """Return an iterator over all non-overlapping matches for the RE pattern in string. For each match, the iterator returns a match object. """ @@ -408,9 +359,7 @@ class Pattern(Generic[AnyStr]): def finditer(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Iterator[Match[AnyStr]]: ... @overload def sub(self: Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0) -> str: - """ - Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. - """ + """Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl.""" @overload def sub( @@ -423,9 +372,7 @@ class Pattern(Generic[AnyStr]): def sub(self, repl: AnyStr | Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = 0) -> AnyStr: ... @overload def subn(self: Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0) -> tuple[str, int]: - """ - Return the tuple (new_string, number_of_subs_made) found by replacing the leftmost non-overlapping occurrences of pattern with the replacement repl. - """ + """Return the tuple (new_string, number_of_subs_made) found by replacing the leftmost non-overlapping occurrences of pattern with the replacement repl.""" @overload def subn( @@ -441,16 +388,12 @@ class Pattern(Generic[AnyStr]): def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" # ----- re variables and constants ----- class RegexFlag(enum.IntFlag): - """ - An enumeration. - """ + """An enumeration.""" A = sre_compile.SRE_FLAG_ASCII ASCII = A @@ -506,16 +449,13 @@ _FlagsType: TypeAlias = int | RegexFlag # because the pattern must be hashable. @overload def compile(pattern: AnyStr, flags: _FlagsType = 0) -> Pattern[AnyStr]: - """ - Compile a regular expression pattern, returning a Pattern object. - """ + """Compile a regular expression pattern, returning a Pattern object.""" @overload def compile(pattern: Pattern[AnyStr], flags: _FlagsType = 0) -> Pattern[AnyStr]: ... @overload def search(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: - """ - Scan through string looking for a match to the pattern, returning + """Scan through string looking for a match to the pattern, returning a Match object, or None if no match was found. """ @@ -523,8 +463,7 @@ def search(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> M def search(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ... @overload def match(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: - """ - Try to apply the pattern at the start of the string, returning + """Try to apply the pattern at the start of the string, returning a Match object, or None if no match was found. """ @@ -532,8 +471,7 @@ def match(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Ma def match(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ... @overload def fullmatch(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: - """ - Try to apply the pattern to all of the string, returning + """Try to apply the pattern to all of the string, returning a Match object, or None if no match was found. """ @@ -541,8 +479,7 @@ def fullmatch(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) - def fullmatch(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ... @overload def split(pattern: str | Pattern[str], string: str, maxsplit: int = 0, flags: _FlagsType = 0) -> list[str | MaybeNone]: - """ - Split the source string by the occurrences of the pattern, + """Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting @@ -557,8 +494,7 @@ def split( ) -> list[bytes | MaybeNone]: ... @overload def findall(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> list[Any]: - """ - Return a list of all non-overlapping matches in the string. + """Return a list of all non-overlapping matches in the string. If one or more capturing groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern @@ -571,8 +507,7 @@ def findall(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> def findall(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> list[Any]: ... @overload def finditer(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Iterator[Match[str]]: - """ - Return an iterator over all non-overlapping matches in the + """Return an iterator over all non-overlapping matches in the string. For each match, the iterator returns a Match object. Empty matches are included in the result. @@ -584,8 +519,7 @@ def finditer(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _Fl def sub( pattern: str | Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0, flags: _FlagsType = 0 ) -> str: - """ - Return the string obtained by replacing the leftmost + """Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is @@ -605,8 +539,7 @@ def sub( def subn( pattern: str | Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0, flags: _FlagsType = 0 ) -> tuple[str, int]: - """ - Return a 2-tuple containing (new_string, number). + """Return a 2-tuple containing (new_string, number). new_string is the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in the source string by the replacement repl. number is the number of @@ -625,17 +558,11 @@ def subn( flags: _FlagsType = 0, ) -> tuple[bytes, int]: ... def escape(pattern: AnyStr) -> AnyStr: - """ - Escape special characters in a string. - """ + """Escape special characters in a string.""" def purge() -> None: - """ - Clear the regular expression caches - """ + """Clear the regular expression caches""" if sys.version_info < (3, 13): def template(pattern: AnyStr | Pattern[AnyStr], flags: _FlagsType = 0) -> Pattern[AnyStr]: - """ - Compile a template pattern, returning a Pattern object, deprecated - """ + """Compile a template pattern, returning a Pattern object, deprecated""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/readline.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/readline.pyi index eaabf384f5..80721636fc 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/readline.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/readline.pyi @@ -13,113 +13,83 @@ if sys.platform != "win32": _CompDisp: TypeAlias = Callable[[str, Sequence[str], int], None] def parse_and_bind(string: str, /) -> None: - """ - Execute the init line provided in the string argument. - """ + """Execute the init line provided in the string argument.""" def read_init_file(filename: StrOrBytesPath | None = None, /) -> None: - """ - Execute a readline initialization file. + """Execute a readline initialization file. The default filename is the last filename used. """ def get_line_buffer() -> str: - """ - Return the current contents of the line buffer. - """ + """Return the current contents of the line buffer.""" def insert_text(string: str, /) -> None: - """ - Insert text into the line buffer at the cursor position. - """ + """Insert text into the line buffer at the cursor position.""" def redisplay() -> None: - """ - Change what's displayed on the screen to reflect contents of the line buffer. - """ + """Change what's displayed on the screen to reflect contents of the line buffer.""" def read_history_file(filename: StrOrBytesPath | None = None, /) -> None: - """ - Load a readline history file. + """Load a readline history file. The default filename is ~/.history. """ def write_history_file(filename: StrOrBytesPath | None = None, /) -> None: - """ - Save a readline history file. + """Save a readline history file. The default filename is ~/.history. """ def append_history_file(nelements: int, filename: StrOrBytesPath | None = None, /) -> None: - """ - Append the last nelements items of the history list to file. + """Append the last nelements items of the history list to file. The default filename is ~/.history. """ def get_history_length() -> int: - """ - Return the maximum number of lines that will be written to the history file. - """ + """Return the maximum number of lines that will be written to the history file.""" def set_history_length(length: int, /) -> None: - """ - Set the maximal number of lines which will be written to the history file. + """Set the maximal number of lines which will be written to the history file. A negative length is used to inhibit history truncation. """ def clear_history() -> None: - """ - Clear the current readline history. - """ + """Clear the current readline history.""" def get_current_history_length() -> int: - """ - Return the current (not the maximum) length of history. - """ + """Return the current (not the maximum) length of history.""" def get_history_item(index: int, /) -> str: - """ - Return the current contents of history item at one-based index. - """ + """Return the current contents of history item at one-based index.""" def remove_history_item(pos: int, /) -> None: - """ - Remove history item given by its zero-based position. - """ + """Remove history item given by its zero-based position.""" def replace_history_item(pos: int, line: str, /) -> None: - """ - Replaces history item given by its position with contents of line. + """Replaces history item given by its position with contents of line. pos is zero-based. """ def add_history(string: str, /) -> None: - """ - Add an item to the history buffer. - """ + """Add an item to the history buffer.""" def set_auto_history(enabled: bool, /) -> None: - """ - Enables or disables automatic history. - """ + """Enables or disables automatic history.""" def set_startup_hook(function: Callable[[], object] | None = None, /) -> None: - """ - Set or remove the function invoked by the rl_startup_hook callback. + """Set or remove the function invoked by the rl_startup_hook callback. The function is called with no arguments just before readline prints the first prompt. """ def set_pre_input_hook(function: Callable[[], object] | None = None, /) -> None: - """ - Set or remove the function invoked by the rl_pre_input_hook callback. + """Set or remove the function invoked by the rl_pre_input_hook callback. The function is called with no arguments after the first prompt has been printed and just before readline starts reading input @@ -127,8 +97,7 @@ if sys.platform != "win32": """ def set_completer(function: _Completer | None = None, /) -> None: - """ - Set or remove the completer function. + """Set or remove the completer function. The function is called as function(text, state), for state in 0, 1, 2, ..., until it returns a non-string. @@ -136,38 +105,25 @@ if sys.platform != "win32": """ def get_completer() -> _Completer | None: - """ - Get the current completer function. - """ + """Get the current completer function.""" def get_completion_type() -> int: - """ - Get the type of completion being attempted. - """ + """Get the type of completion being attempted.""" def get_begidx() -> int: - """ - Get the beginning index of the completion scope. - """ + """Get the beginning index of the completion scope.""" def get_endidx() -> int: - """ - Get the ending index of the completion scope. - """ + """Get the ending index of the completion scope.""" def set_completer_delims(string: str, /) -> None: - """ - Set the word delimiters for completion. - """ + """Set the word delimiters for completion.""" def get_completer_delims() -> str: - """ - Get the word delimiters for completion. - """ + """Get the word delimiters for completion.""" def set_completion_display_matches_hook(function: _CompDisp | None = None, /) -> None: - """ - Set or remove the completion display function. + """Set or remove the completion display function. The function is called as function(substitution, [matches], longest_match_length) diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/reprlib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/reprlib.pyi index 9fa6ae228b..e0df3c85df 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/reprlib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/reprlib.pyi @@ -14,9 +14,7 @@ __all__ = ["Repr", "repr", "recursive_repr"] _ReprFunc: TypeAlias = Callable[[Any], str] def recursive_repr(fillvalue: str = "...") -> Callable[[_ReprFunc], _ReprFunc]: - """ - Decorator to make a repr function return fillvalue for a recursive call - """ + """Decorator to make a repr function return fillvalue for a recursive call""" class Repr: maxlevel: int diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/resource.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/resource.pyi index 5fd8aa0886..be5ee3eb14 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/resource.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/resource.pyi @@ -29,8 +29,7 @@ if sys.platform != "win32": class struct_rusage( structseq[float], tuple[float, float, int, int, int, int, int, int, int, int, int, int, int, int, int, int] ): - """ - struct_rusage: Result from getrusage. + """struct_rusage: Result from getrusage. This object may be accessed either as a tuple of (utime,stime,maxrss,ixrss,idrss,isrss,minflt,majflt, @@ -60,99 +59,67 @@ if sys.platform != "win32": @property def ru_utime(self) -> float: - """ - user time used - """ + """user time used""" @property def ru_stime(self) -> float: - """ - system time used - """ + """system time used""" @property def ru_maxrss(self) -> int: - """ - max. resident set size - """ + """max. resident set size""" @property def ru_ixrss(self) -> int: - """ - shared memory size - """ + """shared memory size""" @property def ru_idrss(self) -> int: - """ - unshared data size - """ + """unshared data size""" @property def ru_isrss(self) -> int: - """ - unshared stack size - """ + """unshared stack size""" @property def ru_minflt(self) -> int: - """ - page faults not requiring I/O - """ + """page faults not requiring I/O""" @property def ru_majflt(self) -> int: - """ - page faults requiring I/O - """ + """page faults requiring I/O""" @property def ru_nswap(self) -> int: - """ - number of swap outs - """ + """number of swap outs""" @property def ru_inblock(self) -> int: - """ - block input operations - """ + """block input operations""" @property def ru_oublock(self) -> int: - """ - block output operations - """ + """block output operations""" @property def ru_msgsnd(self) -> int: - """ - IPC messages sent - """ + """IPC messages sent""" @property def ru_msgrcv(self) -> int: - """ - IPC messages received - """ + """IPC messages received""" @property def ru_nsignals(self) -> int: - """ - signals received - """ + """signals received""" @property def ru_nvcsw(self) -> int: - """ - voluntary context switches - """ + """voluntary context switches""" @property def ru_nivcsw(self) -> int: - """ - involuntary context switches - """ + """involuntary context switches""" def getpagesize() -> int: ... def getrlimit(resource: int, /) -> tuple[int, int]: ... @@ -163,7 +130,5 @@ if sys.platform != "win32": def prlimit(pid: int, resource: int, limits: tuple[int, int] | None = None, /) -> tuple[int, int]: ... else: def prlimit(pid: int, resource: int, limits: tuple[int, int] = ..., /) -> tuple[int, int]: - """ - prlimit(pid, resource, [limits]) - """ + """prlimit(pid, resource, [limits])""" error = OSError diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/rlcompleter.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/rlcompleter.pyi index 95ca375c12..4820d53976 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/rlcompleter.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/rlcompleter.pyi @@ -35,8 +35,7 @@ __all__ = ["Completer"] class Completer: def __init__(self, namespace: dict[str, Any] | None = None) -> None: - """ - Create a new completer for the command line. + """Create a new completer for the command line. Completer([namespace]) -> completer instance. @@ -51,16 +50,14 @@ class Completer: """ def complete(self, text: str, state: int) -> str | None: - """ - Return the next possible completion for 'text'. + """Return the next possible completion for 'text'. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. """ def attr_matches(self, text: str) -> list[str]: - """ - Compute matches when text contains a dot. + """Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluable in self.namespace, it will be evaluated and its attributes @@ -72,8 +69,7 @@ class Completer: """ def global_matches(self, text: str) -> list[str]: - """ - Compute matches when text is a simple name. + """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace that match. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/runpy.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/runpy.pyi index 23c77f0873..5442743e30 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/runpy.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/runpy.pyi @@ -16,9 +16,7 @@ from typing_extensions import Self __all__ = ["run_module", "run_path"] class _TempModule: - """ - Temporarily replace a module in sys.modules with an empty namespace - """ + """Temporarily replace a module in sys.modules with an empty namespace""" mod_name: str module: ModuleType @@ -35,8 +33,7 @@ class _ModifiedArgv0: def run_module( mod_name: str, init_globals: dict[str, Any] | None = None, run_name: str | None = None, alter_sys: bool = False ) -> dict[str, Any]: - """ - Execute a module's code without importing it. + """Execute a module's code without importing it. mod_name -- an absolute module name or package name. @@ -57,8 +54,7 @@ def run_module( """ def run_path(path_name: str, init_globals: dict[str, Any] | None = None, run_name: str | None = None) -> dict[str, Any]: - """ - Execute code located at the specified filesystem location. + """Execute code located at the specified filesystem location. path_name -- filesystem location of a Python script, zipfile, or directory containing a top level __main__.py script. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/sched.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/sched.pyi index 9f2c854f67..721651df07 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/sched.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/sched.pyi @@ -35,9 +35,7 @@ _ActionCallback: TypeAlias = Callable[..., Any] if sys.version_info >= (3, 10): class Event(NamedTuple): - """ - Event(time, priority, sequence, action, argument, kwargs) - """ + """Event(time, priority, sequence, action, argument, kwargs)""" time: float priority: Any @@ -63,16 +61,14 @@ class scheduler: delayfunc: Callable[[float], object] def __init__(self, timefunc: Callable[[], float] = ..., delayfunc: Callable[[float], object] = ...) -> None: - """ - Initialize a new instance, passing the time and delay + """Initialize a new instance, passing the time and delay functions """ def enterabs( self, time: float, priority: Any, action: _ActionCallback, argument: tuple[Any, ...] = (), kwargs: dict[str, Any] = ... ) -> Event: - """ - Enter a new event in the queue at an absolute time. + """Enter a new event in the queue at an absolute time. Returns an ID for the event which can be used to remove it, if necessary. @@ -81,15 +77,13 @@ class scheduler: def enter( self, delay: float, priority: Any, action: _ActionCallback, argument: tuple[Any, ...] = (), kwargs: dict[str, Any] = ... ) -> Event: - """ - A variant that specifies the time as a relative time. + """A variant that specifies the time as a relative time. This is actually the more commonly used interface. """ def run(self, blocking: bool = True) -> float | None: - """ - Execute events until the queue is empty. + """Execute events until the queue is empty. If blocking is False executes the scheduled events due to expire soonest (if any) and then return the deadline of the next scheduled call in the scheduler. @@ -113,22 +107,18 @@ class scheduler: """ def cancel(self, event: Event) -> None: - """ - Remove an event from the queue. + """Remove an event from the queue. This must be presented the ID as returned by enter(). If the event is not in the queue, this raises ValueError. """ def empty(self) -> bool: - """ - Check whether the queue is empty. - """ + """Check whether the queue is empty.""" @property def queue(self) -> list[Event]: - """ - An ordered list of upcoming events. + """An ordered list of upcoming events. Events are named tuples with fields for: time, priority, action, arguments, kwargs diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/secrets.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/secrets.pyi index 308140382e..e7416a3153 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/secrets.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/secrets.pyi @@ -16,23 +16,16 @@ __all__ = ["choice", "randbelow", "randbits", "SystemRandom", "token_bytes", "to _T = TypeVar("_T") def randbelow(exclusive_upper_bound: int) -> int: - """ - Return a random int in the range [0, n). - """ + """Return a random int in the range [0, n).""" def randbits(k: int) -> int: - """ - getrandbits(k) -> x. Generates an int with k random bits. - """ + """getrandbits(k) -> x. Generates an int with k random bits.""" def choice(seq: SupportsLenAndGetItem[_T]) -> _T: - """ - Choose a random element from a non-empty sequence. - """ + """Choose a random element from a non-empty sequence.""" def token_bytes(nbytes: int | None = None) -> bytes: - """ - Return a random byte string containing *nbytes* bytes. + """Return a random byte string containing *nbytes* bytes. If *nbytes* is ``None`` or not supplied, a reasonable default is used. @@ -42,8 +35,7 @@ def token_bytes(nbytes: int | None = None) -> bytes: """ def token_hex(nbytes: int | None = None) -> str: - """ - Return a random text string, in hexadecimal. + """Return a random text string, in hexadecimal. The string has *nbytes* random bytes, each byte converted to two hex digits. If *nbytes* is ``None`` or not supplied, a reasonable @@ -54,8 +46,7 @@ def token_hex(nbytes: int | None = None) -> str: """ def token_urlsafe(nbytes: int | None = None) -> str: - """ - Return a random URL-safe text string, in Base64 encoding. + """Return a random URL-safe text string, in Base64 encoding. The string has *nbytes* random bytes. If *nbytes* is ``None`` or not supplied, a reasonable default is used. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/select.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/select.pyi index 96b57745f5..2763bad971 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/select.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/select.pyi @@ -32,8 +32,7 @@ if sys.platform != "win32": # This is actually a function that returns an instance of a class. # The class is not accessible directly, and also calls itself select.poll. class poll: - """ - Returns a polling object. + """Returns a polling object. This object supports registering and unregistering file descriptors, and then polling them for I/O events. @@ -48,8 +47,7 @@ if sys.platform != "win32": def select( rlist: Iterable[Any], wlist: Iterable[Any], xlist: Iterable[Any], timeout: float | None = None, / ) -> tuple[list[Any], list[Any], list[Any]]: - """ - Wait until one or more file descriptors are ready for some kind of I/O. + """Wait until one or more file descriptors are ready for some kind of I/O. The first three arguments are iterables of file descriptors to be waited for: rlist -- wait until ready for reading @@ -79,6 +77,22 @@ if sys.platform != "linux" and sys.platform != "win32": # BSD only @final class kevent: + """kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0) + + This object is the equivalent of the struct kevent for the C API. + + See the kqueue manpage for more detailed information about the meaning + of the arguments. + + One minor note: while you might hope that udata could store a + reference to a python object, it cannot, because it is impossible to + keep a proper reference count of the object once it's passed into the + kernel. Therefore, I have restricted it to only storing an integer. I + recommend ignoring it and simply using the 'ident' field to key off + of. You could also set up a dictionary on the python side to store a + udata->object mapping. + """ + data: Any fflags: int filter: int @@ -99,15 +113,48 @@ if sys.platform != "linux" and sys.platform != "win32": # BSD only @final class kqueue: + """Kqueue syscall wrapper. + + For example, to start watching a socket for input: + >>> kq = kqueue() + >>> sock = socket() + >>> sock.connect((host, port)) + >>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_ADD)], 0) + + To wait one second for it to become writeable: + >>> kq.control(None, 1, 1000) + + To stop listening: + >>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_DELETE)], 0) + """ + closed: bool def __init__(self) -> None: ... - def close(self) -> None: ... - def control( - self, changelist: Iterable[kevent] | None, maxevents: int, timeout: float | None = None, / - ) -> list[kevent]: ... - def fileno(self) -> int: ... + def close(self) -> None: + """Close the kqueue control file descriptor. + + Further operations on the kqueue object will raise an exception. + """ + + def control(self, changelist: Iterable[kevent] | None, maxevents: int, timeout: float | None = None, /) -> list[kevent]: + """Calls the kernel kevent function. + + changelist + Must be an iterable of kevent objects describing the changes to be made + to the kernel's watch list or None. + maxevents + The maximum number of events that the kernel will return. + timeout + The maximum time to wait in seconds, or else None to wait forever. + This accepts floats for smaller timeouts, too. + """ + + def fileno(self) -> int: + """Return the kqueue control file descriptor.""" + @classmethod - def fromfd(cls, fd: FileDescriptorLike, /) -> kqueue: ... + def fromfd(cls, fd: FileDescriptorLike, /) -> kqueue: + """Create a kqueue object from a given control fd.""" KQ_EV_ADD: int KQ_EV_CLEAR: int @@ -152,8 +199,7 @@ if sys.platform != "linux" and sys.platform != "win32": if sys.platform == "linux": @final class epoll: - """ - select.epoll(sizehint=-1, flags=0) + """select.epoll(sizehint=-1, flags=0) Returns an epolling object @@ -172,20 +218,16 @@ if sys.platform == "linux": /, ) -> None: ... def close(self) -> None: - """ - Close the epoll control file descriptor. + """Close the epoll control file descriptor. Further operations on the epoll object will raise an exception. """ closed: bool def fileno(self) -> int: - """ - Return the epoll control file descriptor. - """ + """Return the epoll control file descriptor.""" def register(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: - """ - Registers a new fd or raises an OSError if the fd is already registered. + """Registers a new fd or raises an OSError if the fd is already registered. fd the target file descriptor of the operation @@ -196,8 +238,7 @@ if sys.platform == "linux": """ def modify(self, fd: FileDescriptorLike, eventmask: int) -> None: - """ - Modify event mask for a registered file descriptor. + """Modify event mask for a registered file descriptor. fd the target file descriptor of the operation @@ -206,16 +247,14 @@ if sys.platform == "linux": """ def unregister(self, fd: FileDescriptorLike) -> None: - """ - Remove a registered file descriptor from the epoll object. + """Remove a registered file descriptor from the epoll object. fd the target file descriptor of the operation """ def poll(self, timeout: float | None = None, maxevents: int = -1) -> list[tuple[int, int]]: - """ - Wait for events on the epoll file descriptor. + """Wait for events on the epoll file descriptor. timeout the maximum time to wait in seconds (as float); @@ -229,9 +268,7 @@ if sys.platform == "linux": @classmethod def fromfd(cls, fd: FileDescriptorLike, /) -> epoll: - """ - Create an epoll object from a given control fd. - """ + """Create an epoll object from a given control fd.""" EPOLLERR: int EPOLLEXCLUSIVE: int diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/selectors.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/selectors.pyi index f9d7dd81af..0f4b38c47d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/selectors.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/selectors.pyi @@ -18,8 +18,7 @@ EVENT_READ: _EventMask EVENT_WRITE: _EventMask class SelectorKey(NamedTuple): - """ - SelectorKey(fileobj, fd, events, data) + """SelectorKey(fileobj, fd, events, data) Object used to associate a file object to its backing file descriptor, selected event mask, and attached data. @@ -31,8 +30,7 @@ class SelectorKey(NamedTuple): data: Any class BaseSelector(metaclass=ABCMeta): - """ - Selector abstract base class. + """Selector abstract base class. A selector supports registering file objects to be monitored for specific I/O events. @@ -48,8 +46,7 @@ class BaseSelector(metaclass=ABCMeta): @abstractmethod def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = None) -> SelectorKey: - """ - Register a file object. + """Register a file object. Parameters: fileobj -- file object or file descriptor @@ -71,8 +68,7 @@ class BaseSelector(metaclass=ABCMeta): @abstractmethod def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: - """ - Unregister a file object. + """Unregister a file object. Parameters: fileobj -- file object or file descriptor @@ -89,8 +85,7 @@ class BaseSelector(metaclass=ABCMeta): """ def modify(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = None) -> SelectorKey: - """ - Change a registered file object monitored events or attached data. + """Change a registered file object monitored events or attached data. Parameters: fileobj -- file object or file descriptor @@ -106,8 +101,7 @@ class BaseSelector(metaclass=ABCMeta): @abstractmethod def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, _EventMask]]: - """ - Perform the actual selection, until some monitored file objects are + """Perform the actual selection, until some monitored file objects are ready or a timeout expires. Parameters: @@ -124,15 +118,13 @@ class BaseSelector(metaclass=ABCMeta): """ def close(self) -> None: - """ - Close the selector. + """Close the selector. This must be called to make sure that any underlying resource is freed. """ def get_key(self, fileobj: FileDescriptorLike) -> SelectorKey: - """ - Return the key associated to a registered file object. + """Return the key associated to a registered file object. Returns: SelectorKey for this file object @@ -140,17 +132,13 @@ class BaseSelector(metaclass=ABCMeta): @abstractmethod def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: - """ - Return a mapping of file objects to selector keys. - """ + """Return a mapping of file objects to selector keys.""" def __enter__(self) -> Self: ... def __exit__(self, *args: Unused) -> None: ... class _BaseSelectorImpl(BaseSelector, metaclass=ABCMeta): - """ - Base selector implementation. - """ + """Base selector implementation.""" def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = None) -> SelectorKey: ... def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... @@ -158,30 +146,22 @@ class _BaseSelectorImpl(BaseSelector, metaclass=ABCMeta): def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... class SelectSelector(_BaseSelectorImpl): - """ - Select-based selector. - """ + """Select-based selector.""" def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, _EventMask]]: ... class _PollLikeSelector(_BaseSelectorImpl): - """ - Base class shared between poll, epoll and devpoll selectors. - """ + """Base class shared between poll, epoll and devpoll selectors.""" def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, _EventMask]]: ... if sys.platform != "win32": class PollSelector(_PollLikeSelector): - """ - Poll-based selector. - """ + """Poll-based selector.""" if sys.platform == "linux": class EpollSelector(_PollLikeSelector): - """ - Epoll-based selector. - """ + """Epoll-based selector.""" def fileno(self) -> int: ... @@ -192,6 +172,8 @@ if sys.platform != "linux" and sys.platform != "darwin" and sys.platform != "win if sys.platform != "win32" and sys.platform != "linux": class KqueueSelector(_BaseSelectorImpl): + """Kqueue-based selector.""" + def fileno(self) -> int: ... def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, _EventMask]]: ... @@ -199,9 +181,7 @@ if sys.platform != "win32" and sys.platform != "linux": # The runtime logic is more fine-grained than a `sys.platform` check; # not really expressible in the stubs class DefaultSelector(_BaseSelectorImpl): - """ - Epoll-based selector. - """ + """Epoll-based selector.""" def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, _EventMask]]: ... if sys.platform != "win32": diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/shelve.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/shelve.pyi index 9102e73242..478141c7b7 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/shelve.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/shelve.pyi @@ -71,8 +71,7 @@ _T = TypeVar("_T") _VT = TypeVar("_VT") class Shelf(MutableMapping[str, _VT]): - """ - Base class for shelf implementations. + """Base class for shelf implementations. This is initialized with a dictionary-like object. See the module's __doc__ string for an overview of the interface. @@ -102,8 +101,7 @@ class Shelf(MutableMapping[str, _VT]): def sync(self) -> None: ... class BsdDbShelf(Shelf[_VT]): - """ - Shelf implementation using the "BSD" db interface. + """Shelf implementation using the "BSD" db interface. This adds methods first(), next(), previous(), last() and set_location() that have no counterpart in [g]dbm databases. @@ -122,8 +120,7 @@ class BsdDbShelf(Shelf[_VT]): def last(self) -> tuple[str, _VT]: ... class DbfilenameShelf(Shelf[_VT]): - """ - Shelf implementation using the "dbm" generic dbm interface. + """Shelf implementation using the "dbm" generic dbm interface. This is initialized with the filename for the dbm database. See the module's __doc__ string for an overview of the interface. @@ -138,8 +135,7 @@ class DbfilenameShelf(Shelf[_VT]): if sys.version_info >= (3, 11): def open(filename: StrOrBytesPath, flag: _TFlags = "c", protocol: int | None = None, writeback: bool = False) -> Shelf[Any]: - """ - Open a persistent dictionary for reading and writing. + """Open a persistent dictionary for reading and writing. The filename parameter is the base filename for the underlying database. As a side-effect, an extension may be added to the @@ -153,8 +149,7 @@ if sys.version_info >= (3, 11): else: def open(filename: str, flag: _TFlags = "c", protocol: int | None = None, writeback: bool = False) -> Shelf[Any]: - """ - Open a persistent dictionary for reading and writing. + """Open a persistent dictionary for reading and writing. The filename parameter is the base filename for the underlying database. As a side-effect, an extension may be added to the diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/shlex.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/shlex.pyi index 7af147ffa0..3b837e969f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/shlex.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/shlex.pyi @@ -19,36 +19,26 @@ class _ShlexInstream(Protocol): if sys.version_info >= (3, 12): def split(s: str | _ShlexInstream, comments: bool = False, posix: bool = True) -> list[str]: - """ - Split the string *s* using shell-like syntax. - """ + """Split the string *s* using shell-like syntax.""" else: @overload def split(s: str | _ShlexInstream, comments: bool = False, posix: bool = True) -> list[str]: - """ - Split the string *s* using shell-like syntax. - """ + """Split the string *s* using shell-like syntax.""" @overload @deprecated("Passing None for 's' to shlex.split() is deprecated and will raise an error in Python 3.12.") def split(s: None, comments: bool = False, posix: bool = True) -> list[str]: ... def join(split_command: Iterable[str]) -> str: - """ - Return a shell-escaped string from *split_command*. - """ + """Return a shell-escaped string from *split_command*.""" def quote(s: str) -> str: - """ - Return a shell-escaped version of the string *s*. - """ + """Return a shell-escaped version of the string *s*.""" # TODO: Make generic over infile once PEP 696 is implemented. class shlex: - """ - A lexical analyzer class for simple shell-like syntaxes. - """ + """A lexical analyzer class for simple shell-like syntaxes.""" commenters: str wordchars: str @@ -75,35 +65,23 @@ class shlex: punctuation_chars: bool | str = False, ) -> None: ... def get_token(self) -> str | None: - """ - Get a token from the input stream (or from stack if it's nonempty) - """ + """Get a token from the input stream (or from stack if it's nonempty)""" def push_token(self, tok: str) -> None: - """ - Push a token onto the stack popped by the get_token method - """ + """Push a token onto the stack popped by the get_token method""" def read_token(self) -> str | None: ... def sourcehook(self, newfile: str) -> tuple[str, TextIOWrapper] | None: - """ - Hook called on a filename to be sourced. - """ + """Hook called on a filename to be sourced.""" def push_source(self, newstream: str | _ShlexInstream, newfile: str | None = None) -> None: - """ - Push an input source onto the lexer's input source stack. - """ + """Push an input source onto the lexer's input source stack.""" def pop_source(self) -> None: - """ - Pop the input source stack. - """ + """Pop the input source stack.""" def error_leader(self, infile: str | None = None, lineno: int | None = None) -> str: - """ - Emit a C-compiler-like, Emacs-friendly error-message leader. - """ + """Emit a C-compiler-like, Emacs-friendly error-message leader.""" def __iter__(self) -> Self: ... def __next__(self) -> str: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/shutil.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/shutil.pyi index 33311c62ae..fdebb2e771 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/shutil.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/shutil.pyi @@ -49,13 +49,10 @@ _BytesPathT = TypeVar("_BytesPathT", bound=BytesPath) class Error(OSError): ... class SameFileError(Error): - """ - Raised when source and destination are the same file. - """ + """Raised when source and destination are the same file.""" class SpecialFileError(OSError): - """ - Raised when trying to do a kind of operation (e.g. copying) which is + """Raised when trying to do a kind of operation (e.g. copying) which is not supported on a special file (e.g. a named pipe) """ @@ -64,37 +61,28 @@ if sys.version_info >= (3, 14): else: class ExecError(OSError): - """ - Raised when a command could not be executed - """ + """Raised when a command could not be executed""" class ReadError(OSError): - """ - Raised when an archive cannot be read - """ + """Raised when an archive cannot be read""" class RegistryError(Exception): - """ - Raised when a registry operation with the archiving + """Raised when a registry operation with the archiving and unpacking registries fails """ def copyfileobj(fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr], length: int = 0) -> None: - """ - copy data from file-like object fsrc to file-like object fdst - """ + """copy data from file-like object fsrc to file-like object fdst""" def copyfile(src: StrOrBytesPath, dst: _StrOrBytesPathT, *, follow_symlinks: bool = True) -> _StrOrBytesPathT: - """ - Copy data from src to dst in the most efficient way possible. + """Copy data from src to dst in the most efficient way possible. If follow_symlinks is not set and src is a symbolic link, a new symlink will be created instead of copying the file it points to. """ def copymode(src: StrOrBytesPath, dst: StrOrBytesPath, *, follow_symlinks: bool = True) -> None: - """ - Copy mode bits from src to dst. + """Copy mode bits from src to dst. If follow_symlinks is not set, symlinks aren't followed if and only if both `src` and `dst` are symlinks. If `lchmod` isn't available @@ -102,8 +90,7 @@ def copymode(src: StrOrBytesPath, dst: StrOrBytesPath, *, follow_symlinks: bool """ def copystat(src: StrOrBytesPath, dst: StrOrBytesPath, *, follow_symlinks: bool = True) -> None: - """ - Copy file metadata + """Copy file metadata Copy the permission bits, last access time, last modification time, and flags from `src` to `dst`. On Linux, copystat() also copies the "extended @@ -117,8 +104,7 @@ def copystat(src: StrOrBytesPath, dst: StrOrBytesPath, *, follow_symlinks: bool @overload def copy(src: StrPath, dst: _StrPathT, *, follow_symlinks: bool = True) -> _StrPathT | str: - """ - Copy data and mode bits ("cp src dst"). Return the file's destination. + """Copy data and mode bits ("cp src dst"). Return the file's destination. The destination may be a directory. @@ -133,8 +119,7 @@ def copy(src: StrPath, dst: _StrPathT, *, follow_symlinks: bool = True) -> _StrP def copy(src: BytesPath, dst: _BytesPathT, *, follow_symlinks: bool = True) -> _BytesPathT | bytes: ... @overload def copy2(src: StrPath, dst: _StrPathT, *, follow_symlinks: bool = True) -> _StrPathT | str: - """ - Copy data and metadata. Return the file's destination. + """Copy data and metadata. Return the file's destination. Metadata is copied with copystat(). Please see the copystat function for more information. @@ -148,8 +133,7 @@ def copy2(src: StrPath, dst: _StrPathT, *, follow_symlinks: bool = True) -> _Str @overload def copy2(src: BytesPath, dst: _BytesPathT, *, follow_symlinks: bool = True) -> _BytesPathT | bytes: ... def ignore_patterns(*patterns: StrPath) -> Callable[[Any, list[str]], set[str]]: - """ - Function that can be used as copytree() ignore parameter. + """Function that can be used as copytree() ignore parameter. Patterns is a sequence of glob-style patterns that are used to exclude files @@ -164,8 +148,7 @@ def copytree( ignore_dangling_symlinks: bool = False, dirs_exist_ok: bool = False, ) -> _StrPathT: - """ - Recursively copy a directory tree and return the destination directory. + """Recursively copy a directory tree and return the destination directory. If exception(s) occur, an Error is raised with a list of reasons. @@ -264,8 +247,7 @@ _CopyFn: TypeAlias = Callable[[str, str], object] | Callable[[StrPath, StrPath], # this does not work when dst is (or is within) an existing directory. # (#6832) def move(src: StrPath, dst: _StrPathT, copy_function: _CopyFn = ...) -> _StrPathT | str | MaybeNone: - """ - Recursively move a file or directory to another location. This is + """Recursively move a file or directory to another location. This is similar to the Unix "mv" command. Return the file or directory's destination. @@ -291,17 +273,14 @@ def move(src: StrPath, dst: _StrPathT, copy_function: _CopyFn = ...) -> _StrPath """ class _ntuple_diskusage(NamedTuple): - """ - usage(total, used, free) - """ + """usage(total, used, free)""" total: int used: int free: int def disk_usage(path: FileDescriptorOrPath) -> _ntuple_diskusage: - """ - Return disk usage statistics about the given path. + """Return disk usage statistics about the given path. Returned value is a named tuple with attributes 'total', 'used' and 'free', which are the amount of total, used and free space, in bytes. @@ -320,8 +299,7 @@ if sys.version_info >= (3, 13): dir_fd: int | None = None, follow_symlinks: bool = True, ) -> None: - """ - Change owner user and group of the given path. + """Change owner user and group of the given path. user and group can be the uid/gid or the user/group names, and in that case, they are converted to their respective uid/gid. @@ -355,8 +333,7 @@ if sys.version_info >= (3, 13): else: @overload def chown(path: FileDescriptorOrPath, user: str | int, group: None = None) -> None: - """ - Change owner user and group of the given path. + """Change owner user and group of the given path. user and group can be the uid/gid or the user/group names, and in that case, they are converted to their respective uid/gid. @@ -372,12 +349,19 @@ 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) -> NoReturn: + """Given a command, mode, and a PATH string, return the path which + conforms to the given mode on the PATH, or None if there is no such + file. + + `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result + of os.environ.get("PATH"), or can be overridden with a custom search + path. + """ @overload def which(cmd: StrPath, mode: int = 1, path: StrPath | None = None) -> str | None: - """ - Given a command, mode, and a PATH string, return the path which + """Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. @@ -399,8 +383,7 @@ def make_archive( group: str | None = None, logger: Any | None = None, ) -> str: - """ - Create an archive file (eg. zip or tar). + """Create an archive file (eg. zip or tar). 'base_name' is the name of the file to create, minus any format-specific extension; 'format' is the archive format: one of "zip", "tar", "gztar", @@ -418,8 +401,7 @@ def make_archive( """ def get_archive_formats() -> list[tuple[str, str]]: - """ - Returns a list of supported formats for archiving and unarchiving. + """Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description) """ @@ -428,8 +410,7 @@ def get_archive_formats() -> list[tuple[str, str]]: def register_archive_format( name: str, function: Callable[..., object], extra_args: Sequence[tuple[str, Any] | list[Any]], description: str = "" ) -> None: - """ - Registers an archive format. + """Registers an archive format. name is the name of the format. function is the callable that will be used to create archives. If provided, extra_args is a sequence of @@ -446,8 +427,7 @@ def unregister_archive_format(name: str) -> None: ... def unpack_archive( filename: StrPath, extract_dir: StrPath | None = None, format: str | None = None, *, filter: _TarfileFilter | None = None ) -> None: - """ - Unpack an archive. + """Unpack an archive. `filename` is the name of the archive. @@ -473,8 +453,7 @@ def register_unpack_format( extra_args: Sequence[tuple[str, Any]], description: str = "", ) -> None: - """ - Registers an unpack format. + """Registers an unpack format. `name` is the name of the format. `extensions` is a list of extensions corresponding to the format. @@ -495,21 +474,17 @@ def register_unpack_format( name: str, extensions: list[str], function: Callable[[str, str], object], extra_args: None = None, description: str = "" ) -> None: ... def unregister_unpack_format(name: str) -> None: - """ - Removes the pack format from the registry. - """ + """Removes the pack format from the registry.""" def get_unpack_formats() -> list[tuple[str, list[str], str]]: - """ - Returns a list of supported formats for unpacking. + """Returns a list of supported formats for unpacking. Each element of the returned sequence is a tuple (name, extensions, description) """ def get_terminal_size(fallback: tuple[int, int] = (80, 24)) -> os.terminal_size: - """ - Get the size of the terminal window. + """Get the size of the terminal window. For each of the two dimensions, the environment variable, COLUMNS and LINES respectively, is checked. If the variable is defined and diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/signal.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/signal.pyi index 10b6b64384..cae043159e 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/signal.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/signal.pyi @@ -9,9 +9,7 @@ from typing_extensions import Never, TypeAlias NSIG: int class Signals(IntEnum): - """ - An enumeration. - """ + """An enumeration.""" SIGABRT = 6 SIGFPE = 8 @@ -62,9 +60,7 @@ class Signals(IntEnum): SIGSTKFLT = 16 class Handlers(IntEnum): - """ - An enumeration. - """ + """An enumeration.""" SIG_DFL = 0 SIG_IGN = 1 @@ -76,16 +72,14 @@ _SIGNUM: TypeAlias = int | Signals _HANDLER: TypeAlias = Callable[[int, FrameType | None], Any] | int | Handlers | None def default_int_handler(signalnum: int, frame: FrameType | None, /) -> Never: - """ - The default handler for SIGINT installed by Python. + """The default handler for SIGINT installed by Python. It raises KeyboardInterrupt. """ if sys.version_info >= (3, 10): # arguments changed in 3.10.2 def getsignal(signalnum: _SIGNUM) -> _HANDLER: - """ - Return the current action for the given signal. + """Return the current action for the given signal. The return value can be: SIG_IGN -- if the signal is being ignored @@ -95,8 +89,7 @@ if sys.version_info >= (3, 10): # arguments changed in 3.10.2 """ def signal(signalnum: _SIGNUM, handler: _HANDLER) -> _HANDLER: - """ - Set the action for the given signal. + """Set the action for the given signal. The action can be SIG_DFL, SIG_IGN, or a callable Python object. The previous action is returned. See getsignal() for possible return values. @@ -108,8 +101,7 @@ if sys.version_info >= (3, 10): # arguments changed in 3.10.2 else: def getsignal(signalnum: _SIGNUM, /) -> _HANDLER: - """ - Return the current action for the given signal. + """Return the current action for the given signal. The return value can be: SIG_IGN -- if the signal is being ignored @@ -119,8 +111,7 @@ else: """ def signal(signalnum: _SIGNUM, handler: _HANDLER, /) -> _HANDLER: - """ - Set the action for the given signal. + """Set the action for the given signal. The action can be SIG_DFL, SIG_IGN, or a callable Python object. The previous action is returned. See getsignal() for possible return values. @@ -176,9 +167,7 @@ else: ITIMER_VIRTUAL: int class Sigmasks(IntEnum): - """ - An enumeration. - """ + """An enumeration.""" SIG_BLOCK = 0 SIG_UNBLOCK = 1 @@ -188,38 +177,25 @@ else: SIG_UNBLOCK: Literal[Sigmasks.SIG_UNBLOCK] SIG_SETMASK: Literal[Sigmasks.SIG_SETMASK] def alarm(seconds: int, /) -> int: - """ - Arrange for SIGALRM to arrive after the given number of seconds. - """ + """Arrange for SIGALRM to arrive after the given number of seconds.""" def getitimer(which: int, /) -> tuple[float, float]: - """ - Returns current value of given itimer. - """ + """Returns current value of given itimer.""" def pause() -> None: - """ - Wait until a signal arrives. - """ + """Wait until a signal arrives.""" def pthread_kill(thread_id: int, signalnum: int, /) -> None: - """ - Send a signal to a thread. - """ + """Send a signal to a thread.""" if sys.version_info >= (3, 10): # arguments changed in 3.10.2 def pthread_sigmask(how: int, mask: Iterable[int]) -> set[_SIGNUM]: - """ - Fetch and/or change the signal mask of the calling thread. - """ + """Fetch and/or change the signal mask of the calling thread.""" else: def pthread_sigmask(how: int, mask: Iterable[int], /) -> set[_SIGNUM]: - """ - Fetch and/or change the signal mask of the calling thread. - """ + """Fetch and/or change the signal mask of the calling thread.""" def setitimer(which: int, seconds: float, interval: float = 0.0, /) -> tuple[float, float]: - """ - Sets given itimer (one of ITIMER_REAL, ITIMER_VIRTUAL or ITIMER_PROF). + """Sets given itimer (one of ITIMER_REAL, ITIMER_VIRTUAL or ITIMER_PROF). The timer will fire after value seconds and after that every interval seconds. The itimer can be cleared by setting seconds to zero. @@ -228,24 +204,21 @@ else: """ def siginterrupt(signalnum: int, flag: bool, /) -> None: - """ - Change system call restart behaviour. + """Change system call restart behaviour. If flag is False, system calls will be restarted when interrupted by signal sig, else system calls will be interrupted. """ def sigpending() -> Any: - """ - Examine pending signals. + """Examine pending signals. Returns a set of signal numbers that are pending for delivery to the calling thread. """ if sys.version_info >= (3, 10): # argument changed in 3.10.2 def sigwait(sigset: Iterable[int]) -> _SIGNUM: - """ - Wait for a signal. + """Wait for a signal. Suspend execution of the calling thread until the delivery of one of the signals specified in the signal set sigset. The function accepts the signal @@ -253,8 +226,7 @@ else: """ else: def sigwait(sigset: Iterable[int], /) -> _SIGNUM: - """ - Wait for a signal. + """Wait for a signal. Suspend execution of the calling thread until the delivery of one of the signals specified in the signal set sigset. The function accepts the signal @@ -271,8 +243,7 @@ else: @final class struct_siginfo(structseq[int], tuple[int, int, int, int, int, int, int]): - """ - struct_siginfo: Result from sigwaitinfo or sigtimedwait. + """struct_siginfo: Result from sigwaitinfo or sigtimedwait. This object may be accessed either as a tuple of (si_signo, si_code, si_errno, si_pid, si_uid, si_status, si_band), @@ -284,63 +255,46 @@ else: @property def si_signo(self) -> int: - """ - signal number - """ + """signal number""" @property def si_code(self) -> int: - """ - signal code - """ + """signal code""" @property def si_errno(self) -> int: - """ - errno associated with this signal - """ + """errno associated with this signal""" @property def si_pid(self) -> int: - """ - sending process ID - """ + """sending process ID""" @property def si_uid(self) -> int: - """ - real user ID of sending process - """ + """real user ID of sending process""" @property def si_status(self) -> int: - """ - exit value or signal - """ + """exit value or signal""" @property def si_band(self) -> int: - """ - band event for SIGPOLL - """ + """band event for SIGPOLL""" def sigtimedwait(sigset: Iterable[int], timeout: float, /) -> struct_siginfo | None: - """ - Like sigwaitinfo(), but with a timeout. + """Like sigwaitinfo(), but with a timeout. The timeout is specified in seconds, with floating-point numbers allowed. """ def sigwaitinfo(sigset: Iterable[int], /) -> struct_siginfo: - """ - Wait synchronously until one of the signals in *sigset* is delivered. + """Wait synchronously until one of the signals in *sigset* is delivered. Returns a struct_siginfo containing information about the signal. """ def strsignal(signalnum: _SIGNUM, /) -> str | None: - """ - Return the system description of the given signal. + """Return the system description of the given signal. Returns the description of signal *signalnum*, such as "Interrupt" for :const:`SIGINT`. Returns :const:`None` if *signalnum* has no @@ -348,21 +302,17 @@ def strsignal(signalnum: _SIGNUM, /) -> str | None: """ def valid_signals() -> set[Signals]: - """ - Return a set of valid signal numbers on this platform. + """Return a set of valid signal numbers on this platform. The signal numbers returned by this function can be safely passed to functions like `pthread_sigmask`. """ def raise_signal(signalnum: _SIGNUM, /) -> None: - """ - Send a signal to the executing process. - """ + """Send a signal to the executing process.""" def set_wakeup_fd(fd: int, /, *, warn_on_full_buffer: bool = ...) -> int: - """ - Sets the fd to be written to (with the signal number) when a signal comes in. + """Sets the fd to be written to (with the signal number) when a signal comes in. A library can use this to wakeup select or poll. The previous fd or -1 is returned. @@ -372,6 +322,4 @@ def set_wakeup_fd(fd: int, /, *, warn_on_full_buffer: bool = ...) -> int: if sys.platform == "linux": def pidfd_send_signal(pidfd: int, sig: int, siginfo: None = None, flags: int = ..., /) -> None: - """ - Send a signal to a process referred to by a pid file descriptor. - """ + """Send a signal to a process referred to by a pid file descriptor.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/site.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/site.pyi index 3e593d1041..4acb16ac51 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/site.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/site.pyi @@ -80,47 +80,38 @@ USER_SITE: str | None USER_BASE: str | None def main() -> None: - """ - Add standard site-specific directories to the module search path. + """Add standard site-specific directories to the module search path. This function is called automatically when this module is imported, unless the python interpreter was started with the -S flag. """ def abs_paths() -> None: # undocumented - """ - Set all module __file__ and __cached__ attributes to an absolute path - """ + """Set all module __file__ and __cached__ attributes to an absolute path""" def addpackage(sitedir: StrPath, name: StrPath, known_paths: set[str] | None) -> set[str] | None: # undocumented - """ - Process a .pth file within the site-packages directory: + """Process a .pth file within the site-packages directory: For each line in the file, either combine it with sitedir to a path and add that to known_paths, or execute it if it starts with 'import '. """ def addsitedir(sitedir: str, known_paths: set[str] | None = None) -> None: - """ - Add 'sitedir' argument to sys.path if missing and handle .pth files in + """Add 'sitedir' argument to sys.path if missing and handle .pth files in 'sitedir' """ def addsitepackages(known_paths: set[str] | None, prefixes: Iterable[str] | None = None) -> set[str] | None: # undocumented - """ - Add site-packages to sys.path - """ + """Add site-packages to sys.path""" def addusersitepackages(known_paths: set[str] | None) -> set[str] | None: # undocumented - """ - Add a per user site-package to sys.path + """Add a per user site-package to sys.path Each user has its own python directory with site-packages in the home directory. """ def check_enableusersite() -> bool | None: # undocumented - """ - Check if user site directory is safe for inclusion + """Check if user site directory is safe for inclusion The function tests for the command line flag (including environment var), process uid/gid equal to effective uid/gid. @@ -132,22 +123,19 @@ def check_enableusersite() -> bool | None: # undocumented if sys.version_info >= (3, 13): def gethistoryfile() -> str: # undocumented - """ - Check if the PYTHON_HISTORY environment variable is set and define + """Check if the PYTHON_HISTORY environment variable is set and define it as the .python_history file. If PYTHON_HISTORY is not set, use the default .python_history file. """ def enablerlcompleter() -> None: # undocumented - """ - Enable default readline configuration on interactive prompts, by + """Enable default readline configuration on interactive prompts, by registering a sys.__interactivehook__. """ if sys.version_info >= (3, 13): def register_readline() -> None: # undocumented - """ - Configure readline completion on interactive prompts. + """Configure readline completion on interactive prompts. If the readline module can be imported, the hook will set the Tab key as completion key and register ~/.python_history as history file. @@ -156,18 +144,13 @@ if sys.version_info >= (3, 13): """ def execsitecustomize() -> None: # undocumented - """ - Run custom site specific code, if available. - """ + """Run custom site specific code, if available.""" def execusercustomize() -> None: # undocumented - """ - Run custom user specific code, if available. - """ + """Run custom user specific code, if available.""" def getsitepackages(prefixes: Iterable[str] | None = None) -> list[str]: - """ - Returns a list containing all global site-packages directories. + """Returns a list containing all global site-packages directories. For each directory present in ``prefixes`` (or the global ``PREFIXES``), this function will find its `site-packages` subdirectory depending on the @@ -175,8 +158,7 @@ def getsitepackages(prefixes: Iterable[str] | None = None) -> list[str]: """ def getuserbase() -> str: - """ - Returns the `user base` directory path. + """Returns the `user base` directory path. The `user base` directory can be used to store data. If the global variable ``USER_BASE`` is not initialized yet, this function will also set @@ -184,8 +166,7 @@ def getuserbase() -> str: """ def getusersitepackages() -> str: - """ - Returns the user-specific site-packages directory path. + """Returns the user-specific site-packages directory path. If the global variable ``USER_SITE`` is not initialized yet, this function will also set it. @@ -193,20 +174,16 @@ def getusersitepackages() -> str: def makepath(*paths: StrPath) -> tuple[str, str]: ... # undocumented def removeduppaths() -> set[str]: # undocumented - """ - Remove duplicate entries from sys.path along with making them + """Remove duplicate entries from sys.path along with making them absolute """ def setcopyright() -> None: # undocumented - """ - Set 'copyright' and 'credits' in builtins - """ + """Set 'copyright' and 'credits' in builtins""" def sethelper() -> None: ... # undocumented def setquit() -> None: # undocumented - """ - Define new builtins 'quit' and 'exit'. + """Define new builtins 'quit' and 'exit'. These are objects which make the interpreter exit when called. The repr of each object contains a hint at how it works. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/smtpd.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/smtpd.pyi index e7340bd5c9..133ec1bd7f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/smtpd.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/smtpd.pyi @@ -124,8 +124,7 @@ class SMTPServer(asyncore.dispatcher): ) -> None: ... def handle_accepted(self, conn: socket.socket, addr: Any) -> None: ... def process_message(self, peer: _Address, mailfrom: str, rcpttos: list[str], data: bytes | str, **kwargs: Any) -> str | None: - """ - Override this abstract method to handle messages from the client. + """Override this abstract method to handle messages from the client. peer is a tuple containing (ipaddr, port) of the client that made the socket connection to our smtp port. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/smtplib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/smtplib.pyi index 9934358924..338137be7f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/smtplib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/smtplib.pyi @@ -71,21 +71,17 @@ bCRLF: bytes OLDSTYLE_AUTH: Pattern[str] class SMTPException(OSError): - """ - Base class for all exceptions raised by this module. - """ + """Base class for all exceptions raised by this module.""" class SMTPNotSupportedError(SMTPException): - """ - The command or option is not supported by the SMTP server. + """The command or option is not supported by the SMTP server. This exception is raised when an attempt is made to run a command or a command with an option which is not supported by the server. """ class SMTPServerDisconnected(SMTPException): - """ - Not connected to any SMTP server. + """Not connected to any SMTP server. This exception is raised when the server unexpectedly disconnects, or when an attempt is made to use the SMTP instance before @@ -93,8 +89,7 @@ class SMTPServerDisconnected(SMTPException): """ class SMTPResponseException(SMTPException): - """ - Base class for all exceptions that include an SMTP error code. + """Base class for all exceptions that include an SMTP error code. These exceptions are generated in some instances when the SMTP server returns an error code. The error code is stored in the @@ -108,8 +103,7 @@ class SMTPResponseException(SMTPException): def __init__(self, code: int, msg: bytes | str) -> None: ... class SMTPSenderRefused(SMTPResponseException): - """ - Sender address refused. + """Sender address refused. In addition to the attributes set by on all SMTPResponseException exceptions, this sets 'sender' to the string that the SMTP refused. @@ -121,8 +115,7 @@ class SMTPSenderRefused(SMTPResponseException): def __init__(self, code: int, msg: bytes, sender: str) -> None: ... class SMTPRecipientsRefused(SMTPException): - """ - All recipient addresses refused. + """All recipient addresses refused. The errors for each recipient are accessible through the attribute 'recipients', which is a dictionary of exactly the same sort as @@ -134,38 +127,29 @@ class SMTPRecipientsRefused(SMTPException): def __init__(self, recipients: _SendErrs) -> None: ... class SMTPDataError(SMTPResponseException): - """ - The SMTP server didn't accept the data. - """ + """The SMTP server didn't accept the data.""" class SMTPConnectError(SMTPResponseException): - """ - Error during connection establishment. - """ + """Error during connection establishment.""" class SMTPHeloError(SMTPResponseException): - """ - The server refused our HELO reply. - """ + """The server refused our HELO reply.""" class SMTPAuthenticationError(SMTPResponseException): - """ - Authentication error. + """Authentication error. Most probably the server didn't accept the username/password combination provided. """ def quoteaddr(addrstring: str) -> str: - """ - Quote a subset of the email addresses defined by RFC 821. + """Quote a subset of the email addresses defined by RFC 821. Should be able to handle anything email.utils.parseaddr can handle. """ def quotedata(data: str) -> str: - """ - Quote data for email. + """Quote data for email. Double leading '.', and change Unix newline '\\n', or Mac '\\r' into internet CRLF end-of-line. @@ -178,8 +162,7 @@ class _AuthObject(Protocol): def __call__(self, challenge: bytes, /) -> str: ... class SMTP: - """ - This class manages a connection to an SMTP or ESMTP server. + """This class manages a connection to an SMTP or ESMTP server. SMTP Objects: SMTP objects have the following attributes: helo_resp @@ -230,8 +213,7 @@ class SMTP: timeout: float = ..., source_address: _SourceAddress | None = None, ) -> None: - """ - Initialize a new instance. + """Initialize a new instance. If specified, `host` is the name of the remote host to which to connect. If specified, `port` specifies the port to which to connect. @@ -251,16 +233,14 @@ class SMTP: self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None ) -> None: ... def set_debuglevel(self, debuglevel: int) -> None: - """ - Set the debug output level. + """Set the debug output level. A non-false value results in debug messages for connection and for all messages sent to and received from the server. """ def connect(self, host: str = "localhost", port: int = 0, source_address: _SourceAddress | None = None) -> _Reply: - """ - Connect to a host on a given port. + """Connect to a host on a given port. If the hostname ends with a colon (':') followed by a number, and there is no port specified, that suffix will be stripped off and the @@ -271,18 +251,13 @@ class SMTP: """ def send(self, s: ReadableBuffer | str) -> None: - """ - Send 's' to the server. - """ + """Send 's' to the server.""" def putcmd(self, cmd: str, args: str = "") -> None: - """ - Send a command to the server. - """ + """Send a command to the server.""" def getreply(self) -> _Reply: - """ - Get a reply from the server. + """Get a reply from the server. Returns a tuple consisting of: @@ -296,48 +271,36 @@ class SMTP: """ def docmd(self, cmd: str, args: str = "") -> _Reply: - """ - Send a command, and return its response code. - """ + """Send a command, and return its response code.""" def helo(self, name: str = "") -> _Reply: - """ - SMTP 'helo' command. + """SMTP 'helo' command. Hostname to send for this command defaults to the FQDN of the local host. """ def ehlo(self, name: str = "") -> _Reply: - """ - SMTP 'ehlo' command. + """SMTP 'ehlo' command. Hostname to send for this command defaults to the FQDN of the local host. """ def has_extn(self, opt: str) -> bool: - """ - Does the server support a given SMTP service extension? - """ + """Does the server support a given SMTP service extension?""" def help(self, args: str = "") -> bytes: - """ - SMTP 'help' command. + """SMTP 'help' command. Returns help text from server. """ def rset(self) -> _Reply: - """ - SMTP 'rset' command -- resets session. - """ + """SMTP 'rset' command -- resets session.""" def noop(self) -> _Reply: - """ - SMTP 'noop' command -- doesn't do anything :> - """ + """SMTP 'noop' command -- doesn't do anything :>""" def mail(self, sender: str, options: Sequence[str] = ()) -> _Reply: - """ - SMTP 'mail' command -- begins mail xfer session. + """SMTP 'mail' command -- begins mail xfer session. This method may raise the following exceptions: @@ -347,13 +310,10 @@ class SMTP: """ def rcpt(self, recip: str, options: Sequence[str] = ()) -> _Reply: - """ - SMTP 'rcpt' command -- indicates 1 recipient for this mail. - """ + """SMTP 'rcpt' command -- indicates 1 recipient for this mail.""" def data(self, msg: ReadableBuffer | str) -> _Reply: - """ - SMTP 'DATA' command -- sends message data to server. + """SMTP 'DATA' command -- sends message data to server. Automatically quotes lines beginning with a period per rfc821. Raises SMTPDataError if there is an unexpected reply to the @@ -364,18 +324,13 @@ class SMTP: """ def verify(self, address: str) -> _Reply: - """ - SMTP 'verify' command -- checks for address validity. - """ + """SMTP 'verify' command -- checks for address validity.""" vrfy = verify def expn(self, address: str) -> _Reply: - """ - SMTP 'expn' command -- expands a mailing list. - """ + """SMTP 'expn' command -- expands a mailing list.""" def ehlo_or_helo_if_needed(self) -> None: - """ - Call self.ehlo() and/or self.helo() if needed. + """Call self.ehlo() and/or self.helo() if needed. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. @@ -388,8 +343,7 @@ class SMTP: user: str password: str def auth(self, mechanism: str, authobject: _AuthObject, *, initial_response_ok: bool = True) -> _Reply: - """ - Authentication command - requires response processing. + """Authentication command - requires response processing. 'mechanism' specifies which authentication mechanism is to be used - the valid values are those listed in the 'auth' @@ -410,28 +364,24 @@ class SMTP: @overload def auth_cram_md5(self, challenge: None = None) -> None: - """ - Authobject to use with CRAM-MD5 authentication. Requires self.user + """Authobject to use with CRAM-MD5 authentication. Requires self.user and self.password to be set. """ @overload def auth_cram_md5(self, challenge: ReadableBuffer) -> str: ... def auth_plain(self, challenge: ReadableBuffer | None = None) -> str: - """ - Authobject to use with PLAIN authentication. Requires self.user and + """Authobject to use with PLAIN authentication. Requires self.user and self.password to be set. """ def auth_login(self, challenge: ReadableBuffer | None = None) -> str: - """ - Authobject to use with LOGIN authentication. Requires self.user and + """Authobject to use with LOGIN authentication. Requires self.user and self.password to be set. """ def login(self, user: str, password: str, *, initial_response_ok: bool = True) -> _Reply: - """ - Log in on an SMTP server that requires authentication. + """Log in on an SMTP server that requires authentication. The arguments are: - user: The user name to authenticate with. @@ -459,8 +409,7 @@ class SMTP: """ if sys.version_info >= (3, 12): def starttls(self, *, context: SSLContext | None = None) -> _Reply: - """ - Puts the connection to the SMTP server into TLS mode. + """Puts the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. @@ -478,8 +427,7 @@ class SMTP: """ else: def starttls(self, keyfile: str | None = None, certfile: str | None = None, context: SSLContext | None = None) -> _Reply: - """ - Puts the connection to the SMTP server into TLS mode. + """Puts the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. @@ -504,8 +452,7 @@ class SMTP: mail_options: Sequence[str] = (), rcpt_options: Sequence[str] = (), ) -> _SendErrs: - """ - This command performs an entire mail transaction. + """This command performs an entire mail transaction. The arguments are: - from_addr : The address sending this mail. @@ -575,8 +522,7 @@ class SMTP: mail_options: Sequence[str] = (), rcpt_options: Sequence[str] = (), ) -> _SendErrs: - """ - Converts message to a bytestring and passes it to sendmail. + """Converts message to a bytestring and passes it to sendmail. The arguments are as for sendmail, except that msg is an email.message.Message object. If from_addr is None or to_addrs is @@ -596,18 +542,13 @@ class SMTP: """ def close(self) -> None: - """ - Close the connection to the SMTP server. - """ + """Close the connection to the SMTP server.""" def quit(self) -> _Reply: - """ - Terminate the SMTP session. - """ + """Terminate the SMTP session.""" class SMTP_SSL(SMTP): - """ - This is a subclass derived from SMTP that connects over an SSL + """This is a subclass derived from SMTP that connects over an SSL encrypted socket (to use this class you need a socket module that was compiled with SSL support). If host is not specified, '' (the local host) is used. If port is omitted, the standard SMTP-over-SSL port @@ -646,8 +587,7 @@ class SMTP_SSL(SMTP): LMTP_PORT: int class LMTP(SMTP): - """ - LMTP - Local Mail Transfer Protocol + """LMTP - Local Mail Transfer Protocol The LMTP protocol, which is very similar to ESMTP, is heavily based on the standard SMTP client. It's common to use Unix sockets for @@ -669,6 +609,4 @@ class LMTP(SMTP): source_address: _SourceAddress | None = None, timeout: float = ..., ) -> None: - """ - Initialize a new instance. - """ + """Initialize a new instance.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/sndhdr.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/sndhdr.pyi index 6ea71636c6..0ff6c8aecf 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/sndhdr.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/sndhdr.pyi @@ -34,9 +34,7 @@ from typing import NamedTuple __all__ = ["what", "whathdr"] class SndHeaders(NamedTuple): - """ - SndHeaders(filetype, framerate, nchannels, nframes, sampwidth) - """ + """SndHeaders(filetype, framerate, nchannels, nframes, sampwidth)""" filetype: str framerate: int @@ -45,11 +43,7 @@ class SndHeaders(NamedTuple): sampwidth: int | str def what(filename: StrOrBytesPath) -> SndHeaders | None: - """ - Guess the type of a sound file. - """ + """Guess the type of a sound file.""" def whathdr(filename: StrOrBytesPath) -> SndHeaders | None: - """ - Recognize sound headers. - """ + """Recognize sound headers.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/socket.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/socket.pyi index 784779dd7e..dbfa71419e 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/socket.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/socket.pyi @@ -1126,9 +1126,7 @@ else: class timeout(error): ... class AddressFamily(IntEnum): - """ - An enumeration. - """ + """An enumeration.""" AF_INET = 2 AF_INET6 = 10 @@ -1234,9 +1232,7 @@ if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darw AF_DIVERT = AddressFamily.AF_DIVERT class SocketKind(IntEnum): - """ - An enumeration. - """ + """An enumeration.""" SOCK_STREAM = 1 SOCK_DGRAM = 2 @@ -1257,9 +1253,7 @@ if sys.platform == "linux": SOCK_NONBLOCK = SocketKind.SOCK_NONBLOCK class MsgFlag(IntFlag): - """ - An enumeration. - """ + """An enumeration.""" MSG_CTRUNC = 8 MSG_DONTROUTE = 4 @@ -1322,9 +1316,7 @@ if sys.platform != "win32" and sys.platform != "linux": MSG_EOF = MsgFlag.MSG_EOF class AddressInfo(IntFlag): - """ - An enumeration. - """ + """An enumeration.""" AI_ADDRCONFIG = 32 AI_ALL = 16 @@ -1365,9 +1357,7 @@ class _SendableFile(Protocol): # def fileno(self) -> int: ... class socket(_socket.socket): - """ - A subclass of _socket.socket adding the makefile() method. - """ + """A subclass of _socket.socket adding the makefile() method.""" def __init__( self, family: AddressFamily | int = -1, type: SocketKind | int = -1, proto: int = -1, fileno: int | None = None @@ -1375,16 +1365,14 @@ class socket(_socket.socket): def __enter__(self) -> Self: ... def __exit__(self, *args: Unused) -> None: ... def dup(self) -> Self: - """ - dup() -> socket object + """dup() -> socket object Duplicate the socket. Return a new socket object connected to the same system resource. The new socket is non-inheritable. """ def accept(self) -> tuple[socket, _RetAddress]: - """ - accept() -> (socket object, address info) + """accept() -> (socket object, address info) Wait for an incoming connection. Return a new socket representing the connection, and the address of the client. @@ -1402,8 +1390,7 @@ class socket(_socket.socket): errors: str | None = None, newline: str | None = None, ) -> SocketIO: - """ - makefile(...) -> an I/O stream connected to the socket + """makefile(...) -> an I/O stream connected to the socket The arguments are as for io.open() after the filename, except the only supported mode values are 'r' (default), 'w', 'b', or a combination of @@ -1461,8 +1448,7 @@ class socket(_socket.socket): newline: str | None = None, ) -> TextIOWrapper: ... def sendfile(self, file: _SendableFile, offset: int = 0, count: int | None = None) -> int: - """ - sendfile(file[, offset[, count]]) -> sent + """sendfile(file[, offset[, count]]) -> sent Send a file until EOF is reached by using high-performance os.sendfile() and return the total number of bytes which @@ -1482,29 +1468,20 @@ class socket(_socket.socket): @property def family(self) -> AddressFamily: - """ - Read-only access to the address family for this socket. - """ + """Read-only access to the address family for this socket.""" @property def type(self) -> SocketKind: - """ - Read-only access to the socket type. - """ + """Read-only access to the socket type.""" def get_inheritable(self) -> bool: - """ - Get the inheritable flag of the socket - """ + """Get the inheritable flag of the socket""" def set_inheritable(self, inheritable: bool) -> None: - """ - Set the inheritable flag of the socket - """ + """Set the inheritable flag of the socket""" def fromfd(fd: SupportsIndex, family: AddressFamily | int, type: SocketKind | int, proto: int = 0) -> socket: - """ - fromfd(fd, family, type[, proto]) -> socket object + """fromfd(fd, family, type[, proto]) -> socket object Create a socket object from a duplicate of the given file descriptor. The remaining arguments are the same as for socket(). @@ -1514,15 +1491,13 @@ if sys.platform != "win32": def send_fds( sock: socket, buffers: Iterable[ReadableBuffer], fds: Iterable[int], flags: Unused = 0, address: Unused = None ) -> int: - """ - send_fds(sock, buffers, fds[, flags[, address]]) -> integer + """send_fds(sock, buffers, fds[, flags[, address]]) -> integer Send the list of file descriptors fds over an AF_UNIX socket. """ def recv_fds(sock: socket, bufsize: int, maxfds: int, flags: int = 0) -> tuple[bytes, list[int], int, Any]: - """ - recv_fds(sock, bufsize, maxfds[, flags]) -> (data, list of file + """recv_fds(sock, bufsize, maxfds[, flags]) -> (data, list of file descriptors, msg_flags, address) Receive up to maxfds file descriptors returning the message @@ -1530,17 +1505,27 @@ if sys.platform != "win32": """ if sys.platform == "win32": - def fromshare(info: bytes) -> socket: ... + def fromshare(info: bytes) -> socket: + """fromshare(info) -> socket object + + Create a socket object from the bytes object returned by + socket.share(pid). + """ if sys.platform == "win32": - def socketpair(family: int = ..., type: int = ..., proto: int = 0) -> tuple[socket, socket]: ... + def socketpair(family: int = ..., type: int = ..., proto: int = 0) -> tuple[socket, socket]: + """socketpair([family[, type[, proto]]]) -> (socket object, socket object) + Create a pair of socket objects from the sockets returned by the platform + socketpair() function. + The arguments are the same as for socket() except the default family is AF_UNIX + if defined on the platform; otherwise, the default is AF_INET. + """ else: def socketpair( family: int | AddressFamily | None = None, type: SocketType | int = ..., proto: int = 0 ) -> tuple[socket, socket]: - """ - socketpair([family[, type[, proto]]]) -> (socket object, socket object) + """socketpair([family[, type[, proto]]]) -> (socket object, socket object) Create a pair of socket objects from the sockets returned by the platform socketpair() function. The arguments are the same as for socket() except the default family is AF_UNIX @@ -1548,8 +1533,7 @@ else: """ class SocketIO(RawIOBase): - """ - Raw I/O implementation for stream sockets. + """Raw I/O implementation for stream sockets. This class supports the makefile() method on sockets. It provides the raw I/O interface on top of a socket object. @@ -1557,8 +1541,7 @@ class SocketIO(RawIOBase): def __init__(self, sock: socket, mode: Literal["r", "w", "rw", "rb", "wb", "rwb"]) -> None: ... def readinto(self, b: WriteableBuffer) -> int | None: - """ - Read up to len(b) bytes into the writable buffer *b* and return + """Read up to len(b) bytes into the writable buffer *b* and return the number of bytes read. If the socket is non-blocking and no bytes are available, None is returned. @@ -1567,8 +1550,7 @@ class SocketIO(RawIOBase): """ def write(self, b: ReadableBuffer) -> int | None: - """ - Write the given bytes or bytearray object *b* to the socket + """Write the given bytes or bytearray object *b* to the socket and return the number of bytes written. This can be less than len(b) if not all data could be written. If the socket is non-blocking and no bytes could be written None is returned. @@ -1580,8 +1562,7 @@ class SocketIO(RawIOBase): def mode(self) -> Literal["rb", "wb", "rwb"]: ... def getfqdn(name: str = "") -> str: - """ - Get fully qualified domain name from name. + """Get fully qualified domain name from name. An empty argument is interpreted as meaning the local host. @@ -1599,8 +1580,7 @@ if sys.version_info >= (3, 11): *, all_errors: bool = False, ) -> socket: - """ - Connect to *address* and return the socket object. + """Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional @@ -1618,8 +1598,7 @@ else: def create_connection( address: tuple[str | None, int], timeout: float | None = ..., source_address: _Address | None = None ) -> socket: - """ - Connect to *address* and return the socket object. + """Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional @@ -1632,16 +1611,14 @@ else: """ def has_dualstack_ipv6() -> bool: - """ - Return True if the platform supports creating a SOCK_STREAM socket + """Return True if the platform supports creating a SOCK_STREAM socket which can handle both AF_INET and AF_INET6 (IPv4 / IPv6) connections. """ def create_server( address: _Address, *, family: int = ..., backlog: int | None = None, reuse_port: bool = False, dualstack_ipv6: bool = False ) -> socket: - """ - Convenience function which creates a SOCK_STREAM type socket + """Convenience function which creates a SOCK_STREAM type socket bound to *address* (a 2-tuple (host, port)) and return the socket object. @@ -1663,8 +1640,7 @@ def create_server( def getaddrinfo( host: bytes | str | None, port: bytes | str | int | None, family: int = 0, type: int = 0, proto: int = 0, flags: int = 0 ) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]]: - """ - Resolve host and port into list of address info entries. + """Resolve host and port into list of address info entries. Translate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creating a socket connected to that service. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/socketserver.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/socketserver.pyi index e93d1ebe56..c81647e32b 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/socketserver.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/socketserver.pyi @@ -159,8 +159,7 @@ _AfInet6Address: TypeAlias = tuple[str | bytes | bytearray, int, int, int] # ad # This can possibly be generic at some point: class BaseServer: - """ - Base class for server classes. + """Base class for server classes. Methods for the caller: @@ -209,20 +208,16 @@ class BaseServer: def __init__( self, server_address: _Address, RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler] ) -> None: - """ - Constructor. May be extended, do not override. - """ + """Constructor. May be extended, do not override.""" def handle_request(self) -> None: - """ - Handle one request, possibly blocking. + """Handle one request, possibly blocking. Respects self.timeout. """ def serve_forever(self, poll_interval: float = 0.5) -> None: - """ - Handle one request at a time until shutdown. + """Handle one request at a time until shutdown. Polls for shutdown every poll_interval seconds. Ignores self.timeout. If you need to do periodic tasks, do them in @@ -230,8 +225,7 @@ class BaseServer: """ def shutdown(self) -> None: - """ - Stops the serve_forever loop. + """Stops the serve_forever loop. Blocks until the loop has finished. This must be called while serve_forever() is running in another thread, or it will @@ -239,49 +233,41 @@ class BaseServer: """ def server_close(self) -> None: - """ - Called to clean-up the server. + """Called to clean-up the server. May be overridden. """ def finish_request(self, request: _RequestType, client_address: _RetAddress) -> None: - """ - Finish one request by instantiating RequestHandlerClass. - """ + """Finish one request by instantiating RequestHandlerClass.""" def get_request(self) -> tuple[Any, Any]: ... # Not implemented here, but expected to exist on subclasses def handle_error(self, request: _RequestType, client_address: _RetAddress) -> None: - """ - Handle an error gracefully. May be overridden. + """Handle an error gracefully. May be overridden. The default is to print a traceback and continue. """ def handle_timeout(self) -> None: - """ - Called if no new request arrives within self.timeout. + """Called if no new request arrives within self.timeout. Overridden by ForkingMixIn. """ def process_request(self, request: _RequestType, client_address: _RetAddress) -> None: - """ - Call finish_request. + """Call finish_request. Overridden by ForkingMixIn and ThreadingMixIn. """ def server_activate(self) -> None: - """ - Called by constructor to activate the server. + """Called by constructor to activate the server. May be overridden. """ def verify_request(self, request: _RequestType, client_address: _RetAddress) -> bool: - """ - Verify the request. May be overridden. + """Verify the request. May be overridden. Return True if we should proceed with this request. """ @@ -291,26 +277,20 @@ class BaseServer: self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None ) -> None: ... def service_actions(self) -> None: - """ - Called by the serve_forever() loop. + """Called by the serve_forever() loop. May be overridden by a subclass / Mixin to implement any code that needs to be run during the loop. """ def shutdown_request(self, request: _RequestType) -> None: # undocumented - """ - Called to shutdown and close an individual request. - """ + """Called to shutdown and close an individual request.""" def close_request(self, request: _RequestType) -> None: # undocumented - """ - Called to clean up an individual request. - """ + """Called to clean up an individual request.""" class TCPServer(BaseServer): - """ - Base class for various socket-based server classes. + """Base class for various socket-based server classes. Defaults to synchronous IP stream (i.e., TCP). @@ -369,35 +349,28 @@ class TCPServer(BaseServer): RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler], bind_and_activate: bool = True, ) -> None: - """ - Constructor. May be extended, do not override. - """ + """Constructor. May be extended, do not override.""" def fileno(self) -> int: - """ - Return socket file number. + """Return socket file number. Interface required by selector. """ def get_request(self) -> tuple[_socket, _RetAddress]: - """ - Get the request and client address from the socket. + """Get the request and client address from the socket. May be overridden. """ def server_bind(self) -> None: - """ - Called by constructor to bind the socket. + """Called by constructor to bind the socket. May be overridden. """ class UDPServer(TCPServer): - """ - UDP server class. - """ + """UDP server class.""" max_packet_size: ClassVar[int] def get_request(self) -> tuple[tuple[bytes, _socket], _RetAddress]: ... # type: ignore[override] @@ -411,9 +384,7 @@ if sys.platform != "win32": RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler], bind_and_activate: bool = True, ) -> None: - """ - Constructor. May be extended, do not override. - """ + """Constructor. May be extended, do not override.""" class UnixDatagramServer(UDPServer): server_address: _AfUnixAddress # type: ignore[assignment] @@ -423,64 +394,49 @@ if sys.platform != "win32": RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler], bind_and_activate: bool = True, ) -> None: - """ - Constructor. May be extended, do not override. - """ + """Constructor. May be extended, do not override.""" if sys.platform != "win32": class ForkingMixIn: - """ - Mix-in class to handle each request in a new process. - """ + """Mix-in class to handle each request in a new process.""" timeout: float | None # undocumented active_children: set[int] | None # undocumented max_children: int # undocumented block_on_close: bool def collect_children(self, *, blocking: bool = False) -> None: # undocumented - """ - Internal routine to wait for children that have exited. - """ + """Internal routine to wait for children that have exited.""" def handle_timeout(self) -> None: # undocumented - """ - Wait for zombies after self.timeout seconds of inactivity. + """Wait for zombies after self.timeout seconds of inactivity. May be extended, do not override. """ def service_actions(self) -> None: # undocumented - """ - Collect the zombie child processes regularly in the ForkingMixIn. + """Collect the zombie child processes regularly in the ForkingMixIn. service_actions is called in the BaseServer's serve_forever loop. """ def process_request(self, request: _RequestType, client_address: _RetAddress) -> None: - """ - Fork a new subprocess to process the request. - """ + """Fork a new subprocess to process the request.""" def server_close(self) -> None: ... class ThreadingMixIn: - """ - Mix-in class to handle each request in a new thread. - """ + """Mix-in class to handle each request in a new thread.""" daemon_threads: bool block_on_close: bool def process_request_thread(self, request: _RequestType, client_address: _RetAddress) -> None: # undocumented - """ - Same as in BaseServer but as a thread. + """Same as in BaseServer but as a thread. In addition, exception handling is done here. """ def process_request(self, request: _RequestType, client_address: _RetAddress) -> None: - """ - Start a new thread to process the request. - """ + """Start a new thread to process the request.""" def server_close(self) -> None: ... @@ -499,8 +455,7 @@ if sys.platform != "win32": class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): ... class BaseRequestHandler: - """ - Base class for request handler classes. + """Base class for request handler classes. This class is instantiated for each request to be handled. The constructor sets the instance variables request, client_address @@ -530,9 +485,7 @@ class BaseRequestHandler: def finish(self) -> None: ... class StreamRequestHandler(BaseRequestHandler): - """ - Define self.rfile and self.wfile for stream sockets. - """ + """Define self.rfile and self.wfile for stream sockets.""" rbufsize: ClassVar[int] # undocumented wbufsize: ClassVar[int] # undocumented @@ -543,9 +496,7 @@ class StreamRequestHandler(BaseRequestHandler): wfile: BufferedIOBase class DatagramRequestHandler(BaseRequestHandler): - """ - Define self.rfile and self.wfile for datagram sockets. - """ + """Define self.rfile and self.wfile for datagram sockets.""" packet: bytes # undocumented socket: _socket # undocumented diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/spwd.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/spwd.pyi index 8da40d8e36..c0588267eb 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/spwd.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/spwd.pyi @@ -17,8 +17,7 @@ from typing import Any, Final, final if sys.platform != "win32": @final class struct_spwd(structseq[Any], tuple[str, str, int, int, int, int, int, int, int]): - """ - spwd.struct_spwd: Results from getsp*() routines. + """spwd.struct_spwd: Results from getsp*() routines. This object may be accessed either as a 9-tuple of (sp_namp,sp_pwdp,sp_lstchg,sp_min,sp_max,sp_warn,sp_inact,sp_expire,sp_flag) @@ -40,80 +39,56 @@ if sys.platform != "win32": @property def sp_namp(self) -> str: - """ - login name - """ + """login name""" @property def sp_pwdp(self) -> str: - """ - encrypted password - """ + """encrypted password""" @property def sp_lstchg(self) -> int: - """ - date of last change - """ + """date of last change""" @property def sp_min(self) -> int: - """ - min #days between changes - """ + """min #days between changes""" @property def sp_max(self) -> int: - """ - max #days between changes - """ + """max #days between changes""" @property def sp_warn(self) -> int: - """ - #days before pw expires to warn user about it - """ + """#days before pw expires to warn user about it""" @property def sp_inact(self) -> int: - """ - #days after pw expires until account is disabled - """ + """#days after pw expires until account is disabled""" @property def sp_expire(self) -> int: - """ - #days since 1970-01-01 when account expires - """ + """#days since 1970-01-01 when account expires""" @property def sp_flag(self) -> int: - """ - reserved - """ + """reserved""" # Deprecated aliases below. @property def sp_nam(self) -> str: - """ - login name; deprecated - """ + """login name; deprecated""" @property def sp_pwd(self) -> str: - """ - encrypted password; deprecated - """ + """encrypted password; deprecated""" def getspall() -> list[struct_spwd]: - """ - Return a list of all available shadow password database entries, in arbitrary order. + """Return a list of all available shadow password database entries, in arbitrary order. See `help(spwd)` for more on shadow password database entries. """ def getspnam(arg: str, /) -> struct_spwd: - """ - Return the shadow password database entry for the given user name. + """Return the shadow password database entry for the given user name. See `help(spwd)` for more on shadow password database entries. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/sqlite3/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/sqlite3/__init__.pyi index 56d106053d..7ab9f997d7 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/sqlite3/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/sqlite3/__init__.pyi @@ -1,4 +1,5 @@ """ + The sqlite3 extension module provides a DB-API 2.0 (PEP 249) compliant interface to the SQLite library, and requires SQLite 3.15.2 or newer. @@ -297,9 +298,7 @@ class ProgrammingError(DatabaseError): ... class Warning(Exception): ... class Connection: - """ - SQLite database connection object. - """ + """SQLite database connection object.""" @property def DataError(self) -> type[DataError]: ... @@ -360,15 +359,13 @@ class Connection: ) -> None: ... def close(self) -> None: - """ - Close the database connection. + """Close the database connection. Any pending transaction is not committed implicitly. """ if sys.version_info >= (3, 11): def blobopen(self, table: str, column: str, row: int, /, *, readonly: bool = False, name: str = "main") -> Blob: - """ - Open and return a BLOB object. + """Open and return a BLOB object. table Table name. @@ -383,15 +380,13 @@ class Connection: """ def commit(self) -> None: - """ - Commit any pending transaction to the database. + """Commit any pending transaction to the database. If there is no open transaction, this method is a no-op. """ def create_aggregate(self, name: str, n_arg: int, aggregate_class: Callable[[], _AggregateProtocol]) -> None: - """ - Creates a new aggregate. + """Creates a new aggregate. Note: Passing keyword arguments 'name', 'n_arg' and 'aggregate_class' to _sqlite3.Connection.create_aggregate() is deprecated. Parameters @@ -405,8 +400,7 @@ class Connection: def create_window_function( self, name: str, num_params: Literal[1], aggregate_class: Callable[[], _SingleParamWindowAggregateClass] | None, / ) -> None: - """ - Creates or redefines an aggregate window function. Non-standard. + """Creates or redefines an aggregate window function. Non-standard. name The name of the SQL aggregate window function to be created or @@ -428,15 +422,12 @@ class Connection: ) -> None: ... def create_collation(self, name: str, callback: Callable[[str, str], int | SupportsIndex] | None, /) -> None: - """ - Creates a collation function. - """ + """Creates a collation function.""" def create_function( self, name: str, narg: int, func: Callable[..., _SqliteData] | None, *, deterministic: bool = False ) -> None: - """ - Creates a new function. + """Creates a new function. Note: Passing keyword arguments 'name', 'narg' and 'func' to _sqlite3.Connection.create_function() is deprecated. Parameters @@ -445,51 +436,38 @@ class Connection: @overload def cursor(self, factory: None = None) -> Cursor: - """ - Return a cursor for the connection. - """ + """Return a cursor for the connection.""" @overload def cursor(self, factory: Callable[[Connection], _CursorT]) -> _CursorT: ... def execute(self, sql: str, parameters: _Parameters = ..., /) -> Cursor: - """ - Executes an SQL statement. - """ + """Executes an SQL statement.""" def executemany(self, sql: str, parameters: Iterable[_Parameters], /) -> Cursor: - """ - Repeatedly executes an SQL statement. - """ + """Repeatedly executes an SQL statement.""" def executescript(self, sql_script: str, /) -> Cursor: - """ - Executes multiple SQL statements at once. - """ + """Executes multiple SQL statements at once.""" def interrupt(self) -> None: - """ - Abort any pending database operation. - """ + """Abort any pending database operation.""" if sys.version_info >= (3, 13): def iterdump(self, *, filter: str | None = None) -> Generator[str, None, None]: - """ - Returns iterator to the dump of the database in an SQL text format. + """Returns iterator to the dump of the database in an SQL text format. filter An optional LIKE pattern for database objects to dump """ else: def iterdump(self) -> Generator[str, None, None]: - """ - Returns iterator to the dump of the database in an SQL text format. + """Returns iterator to the dump of the database in an SQL text format. filter An optional LIKE pattern for database objects to dump """ def rollback(self) -> None: - """ - Roll back to the start of any pending transaction. + """Roll back to the start of any pending transaction. If there is no open transaction, this method is a no-op. """ @@ -497,8 +475,7 @@ class Connection: def set_authorizer( self, authorizer_callback: Callable[[int, str | None, str | None, str | None, str | None], int] | None ) -> None: - """ - Set authorizer callback. + """Set authorizer callback. Note: Passing keyword argument 'authorizer_callback' to _sqlite3.Connection.set_authorizer() is deprecated. Parameter @@ -506,8 +483,7 @@ class Connection: """ def set_progress_handler(self, progress_handler: Callable[[], int | None] | None, n: int) -> None: - """ - Set progress handler callback. + """Set progress handler callback. progress_handler A callable that takes no arguments. @@ -525,8 +501,7 @@ class Connection: """ def set_trace_callback(self, trace_callback: Callable[[str], object] | None) -> None: - """ - Set a trace callback called for each SQL statement (passed as unicode). + """Set a trace callback called for each SQL statement (passed as unicode). Note: Passing keyword argument 'trace_callback' to _sqlite3.Connection.set_trace_callback() is deprecated. Parameter @@ -535,19 +510,13 @@ class Connection: # enable_load_extension and load_extension is not available on python distributions compiled # without sqlite3 loadable extension support. see footnotes https://docs.python.org/3/library/sqlite3.html#f1 def enable_load_extension(self, enable: bool, /) -> None: - """ - Enable dynamic loading of SQLite extension modules. - """ + """Enable dynamic loading of SQLite extension modules.""" if sys.version_info >= (3, 12): def load_extension(self, name: str, /, *, entrypoint: str | None = None) -> None: - """ - Load SQLite extension module. - """ + """Load SQLite extension module.""" else: def load_extension(self, name: str, /) -> None: - """ - Load SQLite extension module. - """ + """Load SQLite extension module.""" def backup( self, @@ -558,13 +527,10 @@ class Connection: name: str = "main", sleep: float = 0.25, ) -> None: - """ - Makes a backup of the database. - """ + """Makes a backup of the database.""" if sys.version_info >= (3, 11): def setlimit(self, category: int, limit: int, /) -> int: - """ - Set connection run-time limits. + """Set connection run-time limits. category The limit category to be set. @@ -578,16 +544,14 @@ class Connection: """ def getlimit(self, category: int, /) -> int: - """ - Get connection run-time limits. + """Get connection run-time limits. category The limit category to be queried. """ def serialize(self, *, name: str = "main") -> bytes: - """ - Serialize a database into a byte string. + """Serialize a database into a byte string. name Which database to serialize. @@ -599,8 +563,7 @@ class Connection: """ def deserialize(self, data: ReadableBuffer, /, *, name: str = "main") -> None: - """ - Load a serialized database. + """Load a serialized database. data The serialized database content. @@ -616,29 +579,24 @@ class Connection: """ if sys.version_info >= (3, 12): def getconfig(self, op: int, /) -> bool: - """ - Query a boolean connection configuration option. + """Query a boolean connection configuration option. op The configuration verb; one of the sqlite3.SQLITE_DBCONFIG codes. """ def setconfig(self, op: int, enable: bool = True, /) -> bool: - """ - Set a boolean connection configuration option. + """Set a boolean connection configuration option. op The configuration verb; one of the sqlite3.SQLITE_DBCONFIG codes. """ def __call__(self, sql: str, /) -> _Statement: - """ - Call self as a function. - """ + """Call self as a function.""" def __enter__(self) -> Self: - """ - Called when the connection is used as a context manager. + """Called when the connection is used as a context manager. Returns itself as a convenience to the caller. """ @@ -646,16 +604,13 @@ class Connection: def __exit__( self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None, / ) -> Literal[False]: - """ - Called when the connection is used as a context manager. + """Called when the connection is used as a context manager. If there was any exception, a rollback takes place; otherwise we commit. """ class Cursor: - """ - SQLite database cursor class. - """ + """SQLite database cursor class.""" arraysize: int @property @@ -670,33 +625,22 @@ class Cursor: def rowcount(self) -> int: ... def __init__(self, cursor: Connection, /) -> None: ... def close(self) -> None: - """ - Closes the cursor. - """ + """Closes the cursor.""" def execute(self, sql: str, parameters: _Parameters = (), /) -> Self: - """ - Executes an SQL statement. - """ + """Executes an SQL statement.""" def executemany(self, sql: str, seq_of_parameters: Iterable[_Parameters], /) -> Self: - """ - Repeatedly executes an SQL statement. - """ + """Repeatedly executes an SQL statement.""" def executescript(self, sql_script: str, /) -> Cursor: - """ - Executes multiple SQL statements at once. - """ + """Executes multiple SQL statements at once.""" def fetchall(self) -> list[Any]: - """ - Fetches all rows from the resultset. - """ + """Fetches all rows from the resultset.""" def fetchmany(self, size: int | None = 1) -> list[Any]: - """ - Fetches several rows from the resultset. + """Fetches several rows from the resultset. size The default value is set by the Cursor.arraysize attribute. @@ -704,63 +648,43 @@ class Cursor: # Returns either a row (as created by the row_factory) or None, but # putting None in the return annotation causes annoying false positives. def fetchone(self) -> Any: - """ - Fetches one row from the resultset. - """ + """Fetches one row from the resultset.""" def setinputsizes(self, sizes: Unused, /) -> None: # does nothing - """ - Required by DB-API. Does nothing in sqlite3. - """ + """Required by DB-API. Does nothing in sqlite3.""" def setoutputsize(self, size: Unused, column: Unused = None, /) -> None: # does nothing - """ - Required by DB-API. Does nothing in sqlite3. - """ + """Required by DB-API. Does nothing in sqlite3.""" def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> Any: - """ - Implement next(self). - """ + """Implement next(self).""" @final class PrepareProtocol: - """ - PEP 246 style object adaption protocol type. - """ + """PEP 246 style object adaption protocol type.""" def __init__(self, *args: object, **kwargs: object) -> None: ... class Row(Sequence[Any]): def __new__(cls, cursor: Cursor, data: tuple[Any, ...], /) -> Self: ... def keys(self) -> list[str]: - """ - Returns the keys of the row. - """ + """Returns the keys of the row.""" @overload def __getitem__(self, key: int | str, /) -> Any: - """ - Return self[key]. - """ + """Return self[key].""" @overload def __getitem__(self, key: slice, /) -> tuple[Any, ...]: ... def __hash__(self) -> int: ... def __iter__(self) -> Iterator[Any]: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" # These return NotImplemented for anything that is not a Row. def __eq__(self, value: object, /) -> bool: ... def __ge__(self, value: object, /) -> bool: ... @@ -778,13 +702,10 @@ if sys.version_info >= (3, 11): @final class Blob: def close(self) -> None: - """ - Close the blob. - """ + """Close the blob.""" def read(self, length: int = -1, /) -> bytes: - """ - Read data at the current offset position. + """Read data at the current offset position. length Read length in bytes. @@ -795,21 +716,17 @@ if sys.version_info >= (3, 11): """ def write(self, data: ReadableBuffer, /) -> None: - """ - Write data at the current offset. + """Write data at the current offset. This function cannot change the blob length. Writing beyond the end of the blob will result in an exception being raised. """ def tell(self) -> int: - """ - Return the current access position for the blob. - """ + """Return the current access position for the blob.""" # whence must be one of os.SEEK_SET, os.SEEK_CUR, os.SEEK_END def seek(self, offset: int, origin: int = 0, /) -> None: - """ - Set the current access position to offset. + """Set the current access position to offset. The origin argument defaults to os.SEEK_SET (absolute blob positioning). Other values for origin are os.SEEK_CUR (seek relative to the current position) @@ -817,26 +734,16 @@ if sys.version_info >= (3, 11): """ def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" def __enter__(self) -> Self: - """ - Blob context manager enter. - """ + """Blob context manager enter.""" def __exit__(self, type: object, val: object, tb: object, /) -> Literal[False]: - """ - Blob context manager exit. - """ + """Blob context manager exit.""" def __getitem__(self, key: SupportsIndex | slice, /) -> int: - """ - Return self[key]. - """ + """Return self[key].""" def __setitem__(self, key: SupportsIndex | slice, value: int, /) -> None: - """ - Set self[key] to value. - """ + """Set self[key] to value.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/ssl.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/ssl.pyi index 84e46432a7..5dd23f016c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/ssl.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/ssl.pyi @@ -155,44 +155,32 @@ class _Cipher(TypedDict): symmetric: str class SSLError(OSError): - """ - An error occurred in the SSL implementation. - """ + """An error occurred in the SSL implementation.""" library: str reason: str class SSLZeroReturnError(SSLError): - """ - SSL/TLS session closed cleanly. - """ + """SSL/TLS session closed cleanly.""" class SSLWantReadError(SSLError): - """ - Non-blocking SSL socket needs to read more data + """Non-blocking SSL socket needs to read more data before the requested operation can be completed. """ class SSLWantWriteError(SSLError): - """ - Non-blocking SSL socket needs to write more data + """Non-blocking SSL socket needs to write more data before the requested operation can be completed. """ class SSLSyscallError(SSLError): - """ - System error when attempting SSL operation. - """ + """System error when attempting SSL operation.""" class SSLEOFError(SSLError): - """ - SSL/TLS connection terminated abruptly. - """ + """SSL/TLS connection terminated abruptly.""" class SSLCertVerificationError(SSLError, ValueError): - """ - A certificate could not be verified. - """ + """A certificate could not be verified.""" verify_code: int verify_message: str @@ -220,8 +208,7 @@ def create_default_context( capath: StrOrBytesPath | None = None, cadata: str | ReadableBuffer | None = None, ) -> SSLContext: - """ - Create a SSLContext object with default settings. + """Create a SSLContext object with default settings. NOTE: The protocol and settings may change anytime without prior deprecation. The values represent a fair balance between maximum @@ -241,8 +228,7 @@ if sys.version_info >= (3, 10): capath: StrOrBytesPath | None = None, cadata: str | ReadableBuffer | None = None, ) -> SSLContext: - """ - Create a SSLContext object for Python stdlib modules + """Create a SSLContext object for Python stdlib modules All Python stdlib modules shall use this function to create SSLContext objects in order to keep common settings in one place. The configuration @@ -263,8 +249,7 @@ else: capath: StrOrBytesPath | None = None, cadata: str | ReadableBuffer | None = None, ) -> SSLContext: - """ - Create a SSLContext object for Python stdlib modules + """Create a SSLContext object for Python stdlib modules All Python stdlib modules shall use this function to create SSLContext objects in order to keep common settings in one place. The configuration @@ -276,8 +261,7 @@ _create_default_https_context: Callable[..., SSLContext] if sys.version_info < (3, 12): def match_hostname(cert: _PeerCertRetDictType, hostname: str) -> None: - """ - Verify that *cert* (in decoded format as returned by + """Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed. @@ -291,8 +275,7 @@ if sys.version_info < (3, 12): """ def cert_time_to_seconds(cert_time: str) -> int: - """ - Return the time in seconds since the Epoch, given the timestring + """Return the time in seconds since the Epoch, given the timestring representing the "notBefore" or "notAfter" date from a certificate in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale). @@ -306,8 +289,7 @@ if sys.version_info >= (3, 10): def get_server_certificate( addr: tuple[str, int], ssl_version: int = ..., ca_certs: str | None = None, timeout: float = ... ) -> str: - """ - Retrieve the certificate from the server at the specified address, + """Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version' is specified, use it in the connection attempt. @@ -316,29 +298,24 @@ if sys.version_info >= (3, 10): else: def get_server_certificate(addr: tuple[str, int], ssl_version: int = ..., ca_certs: str | None = None) -> str: - """ - Retrieve the certificate from the server at the specified address, + """Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version' is specified, use it in the connection attempt. """ def DER_cert_to_PEM_cert(der_cert_bytes: ReadableBuffer) -> str: - """ - Takes a certificate in binary DER format and returns the + """Takes a certificate in binary DER format and returns the PEM version of it as a string. """ def PEM_cert_to_DER_cert(pem_cert_string: str) -> bytes: - """ - Takes a certificate in ASCII PEM format and returns the + """Takes a certificate in ASCII PEM format and returns the DER-encoded version of it as a byte sequence """ class DefaultVerifyPaths(NamedTuple): - """ - DefaultVerifyPaths(cafile, capath, openssl_cafile_env, openssl_cafile, openssl_capath_env, openssl_capath) - """ + """DefaultVerifyPaths(cafile, capath, openssl_cafile_env, openssl_cafile, openssl_capath_env, openssl_capath)""" cafile: str capath: str @@ -348,14 +325,10 @@ class DefaultVerifyPaths(NamedTuple): openssl_capath: str def get_default_verify_paths() -> DefaultVerifyPaths: - """ - Return paths to default cafile and capath. - """ + """Return paths to default cafile and capath.""" class VerifyMode(enum.IntEnum): - """ - An enumeration. - """ + """An enumeration.""" CERT_NONE = 0 CERT_OPTIONAL = 1 @@ -366,9 +339,7 @@ CERT_OPTIONAL: VerifyMode CERT_REQUIRED: VerifyMode class VerifyFlags(enum.IntFlag): - """ - An enumeration. - """ + """An enumeration.""" VERIFY_DEFAULT = 0 VERIFY_CRL_CHECK_LEAF = 4 @@ -390,9 +361,7 @@ if sys.version_info >= (3, 10): VERIFY_X509_PARTIAL_CHAIN: VerifyFlags class _SSLMethod(enum.IntEnum): - """ - An enumeration. - """ + """An enumeration.""" PROTOCOL_SSLv23 = 2 PROTOCOL_SSLv2 = ... @@ -415,9 +384,7 @@ PROTOCOL_TLS_CLIENT: _SSLMethod PROTOCOL_TLS_SERVER: _SSLMethod class Options(enum.IntFlag): - """ - An enumeration. - """ + """An enumeration.""" OP_ALL = 2147483728 OP_NO_SSLv2 = 0 @@ -464,9 +431,7 @@ HAS_NEVER_CHECK_COMMON_NAME: bool CHANNEL_BINDING_TYPES: list[str] class AlertDescription(enum.IntEnum): - """ - An enumeration. - """ + """An enumeration.""" ALERT_DESCRIPTION_ACCESS_DENIED = 49 ALERT_DESCRIPTION_BAD_CERTIFICATE = 42 @@ -533,27 +498,19 @@ class _ASN1ObjectBase(NamedTuple): oid: str class _ASN1Object(_ASN1ObjectBase): - """ - ASN.1 object identifier lookup - """ + """ASN.1 object identifier lookup""" def __new__(cls, oid: str) -> Self: ... @classmethod def fromnid(cls, nid: int) -> Self: - """ - Create _ASN1Object from OpenSSL numeric ID - """ + """Create _ASN1Object from OpenSSL numeric ID""" @classmethod def fromname(cls, name: str) -> Self: - """ - Create _ASN1Object from short name, long name or OID - """ + """Create _ASN1Object from short name, long name or OID""" class Purpose(_ASN1Object, enum.Enum): - """ - SSLContext purpose flags with X509v3 Extended Key Usage objects - """ + """SSLContext purpose flags with X509v3 Extended Key Usage objects""" # Normally this class would inherit __new__ from _ASN1Object, but # because this is an enum, the inherited __new__ is replaced at runtime with @@ -563,8 +520,7 @@ class Purpose(_ASN1Object, enum.Enum): CLIENT_AUTH = (130, "clientAuth", "TLS Web Client Authentication", "1.3.6.1.5.5.7.3.1") # pyright: ignore[reportCallIssue] class SSLSocket(socket.socket): - """ - This class implements a subtype of socket.socket that wraps + """This class implements a subtype of socket.socket that wraps the underlying OS socket in an SSL context when necessary, and provides read and write methods over that channel. """ @@ -575,20 +531,16 @@ class SSLSocket(socket.socket): session: SSLSession | None @property def session_reused(self) -> bool | None: - """ - Was the client session reused during handshake - """ + """Was the client session reused during handshake""" def __init__(self, *args: Any, **kwargs: Any) -> None: ... def connect(self, addr: socket._Address) -> None: - """ - Connects to remote ADDR, and then wraps the connection in + """Connects to remote ADDR, and then wraps the connection in an SSL channel. """ def connect_ex(self, addr: socket._Address) -> int: - """ - Connects to remote ADDR, and then wraps the connection in + """Connects to remote ADDR, and then wraps the connection in an SSL channel. """ @@ -606,26 +558,21 @@ class SSLSocket(socket.socket): def sendto(self, data: ReadableBuffer, flags_or_addr: int, addr: socket._Address) -> int: ... def shutdown(self, how: int) -> None: ... def read(self, len: int = 1024, buffer: bytearray | None = None) -> bytes: - """ - Read up to LEN bytes and return them. + """Read up to LEN bytes and return them. Return zero-length string on EOF. """ def write(self, data: ReadableBuffer) -> int: - """ - Write DATA to the underlying SSL channel. Returns + """Write DATA to the underlying SSL channel. Returns number of bytes of DATA actually transmitted. """ def do_handshake(self, block: bool = False) -> None: # block is undocumented - """ - Start the SSL/TLS handshake. - """ + """Start the SSL/TLS handshake.""" @overload def getpeercert(self, binary_form: Literal[False] = False) -> _PeerCertRetDictType | None: - """ - Returns a formatted version of the data in the certificate provided + """Returns a formatted version of the data in the certificate provided by the other end of the SSL channel. Return None if no certificate was provided, {} if a certificate was @@ -637,74 +584,61 @@ class SSLSocket(socket.socket): @overload def getpeercert(self, binary_form: bool) -> _PeerCertRetType: ... def cipher(self) -> tuple[str, str, int] | None: - """ - Return the currently selected cipher as a 3-tuple ``(name, + """Return the currently selected cipher as a 3-tuple ``(name, ssl_version, secret_bits)``. """ def shared_ciphers(self) -> list[tuple[str, str, int]] | None: - """ - Return a list of ciphers shared by the client during the handshake or + """Return a list of ciphers shared by the client during the handshake or None if this is not a valid server connection. """ def compression(self) -> str | None: - """ - Return the current compression algorithm in use, or ``None`` if + """Return the current compression algorithm in use, or ``None`` if compression was not negotiated or not supported by one of the peers. """ def get_channel_binding(self, cb_type: str = "tls-unique") -> bytes | None: - """ - Get channel binding data for current connection. Raise ValueError + """Get channel binding data for current connection. Raise ValueError if the requested `cb_type` is not supported. Return bytes of the data or None if the data is not available (e.g. before the handshake). """ def selected_alpn_protocol(self) -> str | None: - """ - Return the currently selected ALPN protocol as a string, or ``None`` + """Return the currently selected ALPN protocol as a string, or ``None`` if a next protocol was not negotiated or if ALPN is not supported by one of the peers. """ if sys.version_info >= (3, 10): @deprecated("Deprecated in 3.10. Use ALPN instead.") def selected_npn_protocol(self) -> str | None: - """ - Return the currently selected NPN protocol as a string, or ``None`` + """Return the currently selected NPN protocol as a string, or ``None`` if a next protocol was not negotiated or if NPN is not supported by one of the peers. """ else: def selected_npn_protocol(self) -> str | None: - """ - Return the currently selected NPN protocol as a string, or ``None`` + """Return the currently selected NPN protocol as a string, or ``None`` if a next protocol was not negotiated or if NPN is not supported by one of the peers. """ def accept(self) -> tuple[SSLSocket, socket._RetAddress]: - """ - Accepts a new connection from a remote client, and returns + """Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client. """ def unwrap(self) -> socket.socket: - """ - Start the SSL shutdown handshake. - """ + """Start the SSL shutdown handshake.""" def version(self) -> str | None: - """ - Return a string identifying the protocol version used by the + """Return a string identifying the protocol version used by the current SSL channel. """ def pending(self) -> int: - """ - Return the number of bytes that can be read immediately. - """ + """Return the number of bytes that can be read immediately.""" def verify_client_post_handshake(self) -> None: ... # These methods always raise `NotImplementedError`: @@ -713,8 +647,7 @@ class SSLSocket(socket.socket): def sendmsg(self, *args: Never, **kwargs: Never) -> Never: ... # type: ignore[override] if sys.version_info >= (3, 13): def get_verified_chain(self) -> list[bytes]: - """ - Returns verified certificate chain provided by the other + """Returns verified certificate chain provided by the other end of the SSL channel as a list of DER-encoded bytes. If certificate verification was disabled method acts the same as @@ -722,15 +655,12 @@ class SSLSocket(socket.socket): """ def get_unverified_chain(self) -> list[bytes]: - """ - Returns raw certificate chain provided by the other + """Returns raw certificate chain provided by the other end of the SSL channel as a list of DER-encoded bytes. """ class TLSVersion(enum.IntEnum): - """ - An enumeration. - """ + """An enumeration.""" MINIMUM_SUPPORTED = -2 MAXIMUM_SUPPORTED = -1 @@ -741,8 +671,7 @@ class TLSVersion(enum.IntEnum): TLSv1_3 = 772 class SSLContext(_SSLContext): - """ - An SSLContext holds various SSL-related configuration options and + """An SSLContext holds various SSL-related configuration options and data, such as certificates and possibly a private key. """ @@ -779,8 +708,7 @@ class SSLContext(_SSLContext): ) -> None: ... @overload def get_ca_certs(self, binary_form: Literal[False] = False) -> list[_PeerCertRetDictType]: - """ - Returns a list of dicts with information of loaded CA certs. + """Returns a list of dicts with information of loaded CA certs. If the optional argument is True, returns a DER-encoded copy of the CA certificate. @@ -825,8 +753,7 @@ class SSLContext(_SSLContext): ) -> SSLObject: ... class SSLObject: - """ - This class implements an interface on top of a low-level SSL object as + """This class implements an interface on top of a low-level SSL object as implemented by OpenSSL. This object captures the state of an SSL connection but does not provide any network IO itself. IO needs to be performed through separate "BIO" objects which are OpenSSL's IO abstraction layer. @@ -844,35 +771,28 @@ class SSLObject: context: SSLContext @property def server_side(self) -> bool: - """ - Whether this is a server-side socket. - """ + """Whether this is a server-side socket.""" @property def server_hostname(self) -> str | None: - """ - The currently set server hostname (for SNI), or ``None`` if no + """The currently set server hostname (for SNI), or ``None`` if no server hostname is set. """ session: SSLSession | None @property def session_reused(self) -> bool: - """ - Was the client session reused during handshake - """ + """Was the client session reused during handshake""" def __init__(self, *args: Any, **kwargs: Any) -> None: ... def read(self, len: int = 1024, buffer: bytearray | None = None) -> bytes: - """ - Read up to 'len' bytes from the SSL object and return them. + """Read up to 'len' bytes from the SSL object and return them. If 'buffer' is provided, read into this buffer and return the number of bytes read. """ def write(self, data: ReadableBuffer) -> int: - """ - Write 'data' to the SSL object and return the number of bytes + """Write 'data' to the SSL object and return the number of bytes written. The 'data' argument must support the buffer interface. @@ -880,8 +800,7 @@ class SSLObject: @overload def getpeercert(self, binary_form: Literal[False] = False) -> _PeerCertRetDictType | None: - """ - Returns a formatted version of the data in the certificate provided + """Returns a formatted version of the data in the certificate provided by the other end of the SSL channel. Return None if no certificate was provided, {} if a certificate was @@ -893,69 +812,55 @@ class SSLObject: @overload def getpeercert(self, binary_form: bool) -> _PeerCertRetType: ... def selected_alpn_protocol(self) -> str | None: - """ - Return the currently selected ALPN protocol as a string, or ``None`` + """Return the currently selected ALPN protocol as a string, or ``None`` if a next protocol was not negotiated or if ALPN is not supported by one of the peers. """ if sys.version_info >= (3, 10): @deprecated("Deprecated in 3.10. Use ALPN instead.") def selected_npn_protocol(self) -> str | None: - """ - Return the currently selected NPN protocol as a string, or ``None`` + """Return the currently selected NPN protocol as a string, or ``None`` if a next protocol was not negotiated or if NPN is not supported by one of the peers. """ else: def selected_npn_protocol(self) -> str | None: - """ - Return the currently selected NPN protocol as a string, or ``None`` + """Return the currently selected NPN protocol as a string, or ``None`` if a next protocol was not negotiated or if NPN is not supported by one of the peers. """ def cipher(self) -> tuple[str, str, int] | None: - """ - Return the currently selected cipher as a 3-tuple ``(name, + """Return the currently selected cipher as a 3-tuple ``(name, ssl_version, secret_bits)``. """ def shared_ciphers(self) -> list[tuple[str, str, int]] | None: - """ - Return a list of ciphers shared by the client during the handshake or + """Return a list of ciphers shared by the client during the handshake or None if this is not a valid server connection. """ def compression(self) -> str | None: - """ - Return the current compression algorithm in use, or ``None`` if + """Return the current compression algorithm in use, or ``None`` if compression was not negotiated or not supported by one of the peers. """ def pending(self) -> int: - """ - Return the number of bytes that can be read immediately. - """ + """Return the number of bytes that can be read immediately.""" def do_handshake(self) -> None: - """ - Start the SSL/TLS handshake. - """ + """Start the SSL/TLS handshake.""" def unwrap(self) -> None: - """ - Start the SSL shutdown handshake. - """ + """Start the SSL shutdown handshake.""" def version(self) -> str | None: - """ - Return a string identifying the protocol version used by the + """Return a string identifying the protocol version used by the current SSL channel. """ def get_channel_binding(self, cb_type: str = "tls-unique") -> bytes | None: - """ - Get channel binding data for current connection. Raise ValueError + """Get channel binding data for current connection. Raise ValueError if the requested `cb_type` is not supported. Return bytes of the data or None if the data is not available (e.g. before the handshake). """ @@ -963,8 +868,7 @@ class SSLObject: def verify_client_post_handshake(self) -> None: ... if sys.version_info >= (3, 13): def get_verified_chain(self) -> list[bytes]: - """ - Returns verified certificate chain provided by the other + """Returns verified certificate chain provided by the other end of the SSL channel as a list of DER-encoded bytes. If certificate verification was disabled method acts the same as @@ -972,15 +876,12 @@ class SSLObject: """ def get_unverified_chain(self) -> list[bytes]: - """ - Returns raw certificate chain provided by the other + """Returns raw certificate chain provided by the other end of the SSL channel as a list of DER-encoded bytes. """ class SSLErrorNumber(enum.IntEnum): - """ - An enumeration. - """ + """An enumeration.""" SSL_ERROR_EOF = 8 SSL_ERROR_INVALID_ERROR_CODE = 10 diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/statistics.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/statistics.pyi index b44b13b977..5f2576d7ff 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/statistics.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/statistics.pyi @@ -1,4 +1,5 @@ """ + Basic statistics module. This module provides functions for calculating statistics of data, including @@ -150,8 +151,7 @@ class StatisticsError(ValueError): ... if sys.version_info >= (3, 11): def fmean(data: Iterable[SupportsFloat], weights: Iterable[SupportsFloat] | None = None) -> float: - """ - Convert data to floats and compute the arithmetic mean. + """Convert data to floats and compute the arithmetic mean. This runs faster than the mean() function and it always returns a float. If the input dataset is empty, it raises a StatisticsError. @@ -162,8 +162,7 @@ if sys.version_info >= (3, 11): else: def fmean(data: Iterable[SupportsFloat]) -> float: - """ - Convert data to floats and compute the arithmetic mean. + """Convert data to floats and compute the arithmetic mean. This runs faster than the mean() function and it always returns a float. If the input dataset is empty, it raises a StatisticsError. @@ -173,8 +172,7 @@ else: """ def geometric_mean(data: Iterable[SupportsFloat]) -> float: - """ - Convert data to floats and compute the geometric mean. + """Convert data to floats and compute the geometric mean. Raises a StatisticsError if the input dataset is empty or if it contains a negative value. @@ -189,8 +187,7 @@ def geometric_mean(data: Iterable[SupportsFloat]) -> float: """ def mean(data: Iterable[_NumberT]) -> _NumberT: - """ - Return the sample arithmetic mean of data. + """Return the sample arithmetic mean of data. >>> mean([1, 2, 3, 4, 4]) 2.8 @@ -208,8 +205,7 @@ def mean(data: Iterable[_NumberT]) -> _NumberT: if sys.version_info >= (3, 10): def harmonic_mean(data: Iterable[_NumberT], weights: Iterable[_Number] | None = None) -> _NumberT: - """ - Return the harmonic mean of data. + """Return the harmonic mean of data. The harmonic mean is the reciprocal of the arithmetic mean of the reciprocals of the data. It can be used for averaging ratios or @@ -234,8 +230,7 @@ if sys.version_info >= (3, 10): else: def harmonic_mean(data: Iterable[_NumberT]) -> _NumberT: - """ - Return the harmonic mean of data. + """Return the harmonic mean of data. The harmonic mean, sometimes called the subcontrary mean, is the reciprocal of the arithmetic mean of the reciprocals of the data, @@ -257,8 +252,7 @@ else: """ def median(data: Iterable[_NumberT]) -> _NumberT: - """ - Return the median (middle value) of numeric data. + """Return the median (middle value) of numeric data. When the number of data points is odd, return the middle data point. When the number of data points is even, the median is interpolated by @@ -271,8 +265,7 @@ def median(data: Iterable[_NumberT]) -> _NumberT: """ def median_low(data: Iterable[SupportsRichComparisonT]) -> SupportsRichComparisonT: - """ - Return the low median of numeric data. + """Return the low median of numeric data. When the number of data points is odd, the middle value is returned. When it is even, the smaller of the two middle values is returned. @@ -284,8 +277,7 @@ def median_low(data: Iterable[SupportsRichComparisonT]) -> SupportsRichCompariso """ def median_high(data: Iterable[SupportsRichComparisonT]) -> SupportsRichComparisonT: - """ - Return the high median of data. + """Return the high median of data. When the number of data points is odd, the middle value is returned. When it is even, the larger of the two middle values is returned. @@ -298,8 +290,7 @@ def median_high(data: Iterable[SupportsRichComparisonT]) -> SupportsRichComparis if sys.version_info >= (3, 11): def median_grouped(data: Iterable[SupportsFloat], interval: SupportsFloat = 1.0) -> float: - """ - Estimates the median for numeric data binned around the midpoints + """Estimates the median for numeric data binned around the midpoints of consecutive, fixed-width intervals. The *data* can be any iterable of numeric data with each value being @@ -343,8 +334,7 @@ if sys.version_info >= (3, 11): else: def median_grouped(data: Iterable[_NumberT], interval: _NumberT | float = 1) -> _NumberT | float: - """ - Return the 50th percentile (median) of grouped continuous data. + """Return the 50th percentile (median) of grouped continuous data. >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5]) 3.7 @@ -371,8 +361,7 @@ else: """ def mode(data: Iterable[_HashableT]) -> _HashableT: - """ - Return the most common data point from discrete or nominal data. + """Return the most common data point from discrete or nominal data. ``mode`` assumes discrete data, and returns a single value. This is the standard treatment of the mode as commonly taught in schools: @@ -395,8 +384,7 @@ def mode(data: Iterable[_HashableT]) -> _HashableT: """ def multimode(data: Iterable[_HashableT]) -> list[_HashableT]: - """ - Return a list of the most frequently occurring values. + """Return a list of the most frequently occurring values. Will return more than one result if there are multiple modes or an empty list if *data* is empty. @@ -410,8 +398,7 @@ def multimode(data: Iterable[_HashableT]) -> list[_HashableT]: """ def pstdev(data: Iterable[_NumberT], mu: _NumberT | None = None) -> _NumberT: - """ - Return the square root of the population variance. + """Return the square root of the population variance. See ``pvariance`` for arguments and other details. @@ -420,8 +407,7 @@ def pstdev(data: Iterable[_NumberT], mu: _NumberT | None = None) -> _NumberT: """ def pvariance(data: Iterable[_NumberT], mu: _NumberT | None = None) -> _NumberT: - """ - Return the population variance of ``data``. + """Return the population variance of ``data``. data should be a sequence or iterable of Real-valued numbers, with at least one value. The optional argument mu, if given, should be the mean of @@ -456,8 +442,7 @@ def pvariance(data: Iterable[_NumberT], mu: _NumberT | None = None) -> _NumberT: """ def quantiles(data: Iterable[_NumberT], *, n: int = 4, method: Literal["inclusive", "exclusive"] = "exclusive") -> list[_NumberT]: - """ - Divide *data* into *n* continuous intervals with equal probability. + """Divide *data* into *n* continuous intervals with equal probability. Returns a list of (n - 1) cut points separating the intervals. @@ -474,8 +459,7 @@ def quantiles(data: Iterable[_NumberT], *, n: int = 4, method: Literal["inclusiv """ def stdev(data: Iterable[_NumberT], xbar: _NumberT | None = None) -> _NumberT: - """ - Return the square root of the sample variance. + """Return the square root of the sample variance. See ``variance`` for arguments and other details. @@ -484,8 +468,7 @@ def stdev(data: Iterable[_NumberT], xbar: _NumberT | None = None) -> _NumberT: """ def variance(data: Iterable[_NumberT], xbar: _NumberT | None = None) -> _NumberT: - """ - Return the sample variance of data. + """Return the sample variance of data. data should be an iterable of Real-valued numbers, with at least two values. The optional argument xbar, if given, should be the mean of @@ -523,31 +506,22 @@ def variance(data: Iterable[_NumberT], xbar: _NumberT | None = None) -> _NumberT """ class NormalDist: - """ - Normal distribution of a random variable - """ + """Normal distribution of a random variable""" def __init__(self, mu: float = 0.0, sigma: float = 1.0) -> None: - """ - NormalDist where mu is the mean and sigma is the standard deviation. - """ + """NormalDist where mu is the mean and sigma is the standard deviation.""" @property def mean(self) -> float: - """ - Arithmetic mean of the normal distribution. - """ + """Arithmetic mean of the normal distribution.""" @property def median(self) -> float: - """ - Return the median of the normal distribution - """ + """Return the median of the normal distribution""" @property def mode(self) -> float: - """ - Return the mode of the normal distribution + """Return the mode of the normal distribution The mode is the value x where which the probability density function (pdf) takes its maximum value. @@ -555,40 +529,27 @@ class NormalDist: @property def stdev(self) -> float: - """ - Standard deviation of the normal distribution. - """ + """Standard deviation of the normal distribution.""" @property def variance(self) -> float: - """ - Square of the standard deviation. - """ + """Square of the standard deviation.""" @classmethod def from_samples(cls, data: Iterable[SupportsFloat]) -> Self: - """ - Make a normal distribution instance from sample data. - """ + """Make a normal distribution instance from sample data.""" def samples(self, n: SupportsIndex, *, seed: _Seed | None = None) -> list[float]: - """ - Generate *n* samples for a given mean and standard deviation. - """ + """Generate *n* samples for a given mean and standard deviation.""" def pdf(self, x: float) -> float: - """ - Probability density function. P(x <= X < x+dx) / dx - """ + """Probability density function. P(x <= X < x+dx) / dx""" def cdf(self, x: float) -> float: - """ - Cumulative distribution function. P(X <= x) - """ + """Cumulative distribution function. P(X <= x)""" def inv_cdf(self, p: float) -> float: - """ - Inverse cumulative distribution function. x : P(X <= x) = p + """Inverse cumulative distribution function. x : P(X <= x) = p Finds the value of the random variable such that the probability of the variable being less than or equal to that value equals the given @@ -599,8 +560,7 @@ class NormalDist: """ def overlap(self, other: NormalDist) -> float: - """ - Compute the overlapping coefficient (OVL) between two normal distributions. + """Compute the overlapping coefficient (OVL) between two normal distributions. Measures the agreement between two normal probability distributions. Returns a value between 0.0 and 1.0 giving the overlapping area in @@ -613,8 +573,7 @@ class NormalDist: """ def quantiles(self, n: int = 4) -> list[float]: - """ - Divide into *n* continuous intervals with equal probability. + """Divide into *n* continuous intervals with equal probability. Returns a list of (n - 1) cut points separating the intervals. @@ -624,21 +583,17 @@ class NormalDist: """ def zscore(self, x: float) -> float: - """ - Compute the Standard Score. (x - mean) / stdev + """Compute the Standard Score. (x - mean) / stdev Describes *x* in terms of the number of standard deviations above or below the mean of the normal distribution. """ def __eq__(x1, x2: object) -> bool: - """ - Two NormalDist objects are equal if their mu and sigma are both equal. - """ + """Two NormalDist objects are equal if their mu and sigma are both equal.""" def __add__(x1, x2: float | NormalDist) -> NormalDist: - """ - Add a constant or another NormalDist instance. + """Add a constant or another NormalDist instance. If *other* is a constant, translate mu by the constant, leaving sigma unchanged. @@ -649,8 +604,7 @@ class NormalDist: """ def __sub__(x1, x2: float | NormalDist) -> NormalDist: - """ - Subtract a constant or another NormalDist instance. + """Subtract a constant or another NormalDist instance. If *other* is a constant, translate by the constant mu, leaving sigma unchanged. @@ -661,45 +615,34 @@ class NormalDist: """ def __mul__(x1, x2: float) -> NormalDist: - """ - Multiply both mu and sigma by a constant. + """Multiply both mu and sigma by a constant. Used for rescaling, perhaps to change measurement units. Sigma is scaled with the absolute value of the constant. """ def __truediv__(x1, x2: float) -> NormalDist: - """ - Divide both mu and sigma by a constant. + """Divide both mu and sigma by a constant. Used for rescaling, perhaps to change measurement units. Sigma is scaled with the absolute value of the constant. """ def __pos__(x1) -> NormalDist: - """ - Return a copy of the instance. - """ + """Return a copy of the instance.""" def __neg__(x1) -> NormalDist: - """ - Negates mu while keeping sigma the same. - """ + """Negates mu while keeping sigma the same.""" __radd__ = __add__ def __rsub__(x1, x2: float | NormalDist) -> NormalDist: - """ - Subtract a NormalDist from a constant or another NormalDist. - """ + """Subtract a NormalDist from a constant or another NormalDist.""" __rmul__ = __mul__ def __hash__(self) -> int: - """ - NormalDist objects hash equal if their mu and sigma are both equal. - """ + """NormalDist objects hash equal if their mu and sigma are both equal.""" if sys.version_info >= (3, 12): def correlation(x: Sequence[_Number], y: Sequence[_Number], /, *, method: Literal["linear", "ranked"] = "linear") -> float: - """ - Pearson's correlation coefficient + """Pearson's correlation coefficient Return the Pearson's correlation coefficient for two inputs. Pearson's correlation coefficient *r* takes values between -1 and +1. It measures @@ -724,8 +667,7 @@ if sys.version_info >= (3, 12): elif sys.version_info >= (3, 10): def correlation(x: Sequence[_Number], y: Sequence[_Number], /) -> float: - """ - Pearson's correlation coefficient + """Pearson's correlation coefficient Return the Pearson's correlation coefficient for two inputs. Pearson's correlation coefficient *r* takes values between -1 and +1. It measures the @@ -743,8 +685,7 @@ elif sys.version_info >= (3, 10): if sys.version_info >= (3, 10): def covariance(x: Sequence[_Number], y: Sequence[_Number], /) -> float: - """ - Covariance + """Covariance Return the sample covariance of two inputs *x* and *y*. Covariance is a measure of the joint variability of two inputs. @@ -761,9 +702,7 @@ if sys.version_info >= (3, 10): """ class LinearRegression(NamedTuple): - """ - LinearRegression(slope, intercept) - """ + """LinearRegression(slope, intercept)""" slope: float intercept: float @@ -772,8 +711,7 @@ if sys.version_info >= (3, 11): def linear_regression( regressor: Sequence[_Number], dependent_variable: Sequence[_Number], /, *, proportional: bool = False ) -> LinearRegression: - """ - Slope and intercept for simple linear regression. + """Slope and intercept for simple linear regression. Return the slope and intercept of simple linear regression parameters estimated using ordinary least squares. Simple linear @@ -812,8 +750,7 @@ if sys.version_info >= (3, 11): elif sys.version_info >= (3, 10): def linear_regression(regressor: Sequence[_Number], dependent_variable: Sequence[_Number], /) -> LinearRegression: - """ - Slope and intercept for simple linear regression. + """Slope and intercept for simple linear regression. Return the slope and intercept of simple linear regression parameters estimated using ordinary least squares. Simple linear @@ -854,8 +791,7 @@ if sys.version_info >= (3, 13): "cosine", ] def kde(data: Sequence[float], h: float, kernel: _Kernel = "normal", *, cumulative: bool = False) -> Callable[[float], float]: - """ - Kernel Density Estimation: Create a continuous probability density + """Kernel Density Estimation: Create a continuous probability density function or cumulative distribution function from discrete samples. The basic idea is to smooth the data using a kernel function @@ -956,8 +892,7 @@ if sys.version_info >= (3, 13): def kde_random( data: Sequence[float], h: float, kernel: _Kernel = "normal", *, seed: _Seed | None = None ) -> Callable[[], float]: - """ - Return a function that makes a random selection from the estimated + """Return a function that makes a random selection from the estimated probability density function created by kde(data, h, kernel). Providing a *seed* allows reproducible selections within a single diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/string/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/string/__init__.pyi index 0155500382..7dc9eb1efa 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/string/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/string/__init__.pyi @@ -47,8 +47,7 @@ printable: LiteralString whitespace: LiteralString def capwords(s: StrOrLiteralStr, sep: StrOrLiteralStr | None = None) -> StrOrLiteralStr: - """ - capwords(s [,sep]) -> string + """capwords(s [,sep]) -> string Split the argument into words using split, capitalize each word using capitalize, and join the capitalized words using @@ -59,9 +58,7 @@ def capwords(s: StrOrLiteralStr, sep: StrOrLiteralStr | None = None) -> StrOrLit """ class Template: - """ - A string class for supporting $-substitutions. - """ + """A string class for supporting $-substitutions.""" template: str delimiter: ClassVar[str] diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/string/templatelib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/string/templatelib.pyi index 9bdd209b2e..1026ae7833 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/string/templatelib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/string/templatelib.pyi @@ -10,40 +10,28 @@ __all__ = ["Interpolation", "Template"] @final class Template: # TODO: consider making `Template` generic on `TypeVarTuple` - """ - Template object - """ + """Template object""" strings: tuple[str, ...] interpolations: tuple[Interpolation, ...] def __new__(cls, *args: str | Interpolation) -> Template: ... def __iter__(self) -> Iterator[str | Interpolation]: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __add__(self, other: Template | str) -> Template: - """ - Return self+value. - """ + """Return self+value.""" def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" @property def values(self) -> tuple[Any, ...]: # Tuple of interpolation values, which can have any type - """ - Values of interpolations - """ + """Values of interpolations""" @final class Interpolation: - """ - Interpolation object - """ + """Interpolation object""" value: Any # TODO: consider making `Interpolation` generic in runtime expression: str @@ -56,6 +44,4 @@ class Interpolation: cls, value: Any, expression: str = "", conversion: Literal["a", "r", "s"] | None = None, format_spec: str = "" ) -> Interpolation: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/subprocess.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/subprocess.pyi index a232778620..d592f1a58c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/subprocess.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/subprocess.pyi @@ -110,8 +110,7 @@ if sys.version_info >= (3, 11): _USE_POSIX_SPAWN: Final[bool] class CompletedProcess(Generic[_T]): - """ - A process that has finished running. + """A process that has finished running. This is returned by run(). @@ -131,13 +130,10 @@ class CompletedProcess(Generic[_T]): stderr: _T def __init__(self, args: _CMD, returncode: int, stdout: _T | None = None, stderr: _T | None = None) -> None: ... def check_returncode(self) -> None: - """ - Raise CalledProcessError if the exit code is non-zero. - """ + """Raise CalledProcessError if the exit code is non-zero.""" def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ @@ -178,8 +174,7 @@ if sys.version_info >= (3, 11): pipesize: int = -1, process_group: int | None = None, ) -> CompletedProcess[str]: - """ - Run command with arguments and return a CompletedProcess instance. + """Run command with arguments and return a CompletedProcess instance. The returned instance will have attributes args, returncode, stdout and stderr. By default, stdout and stderr are not captured, and those attributes @@ -415,8 +410,7 @@ elif sys.version_info >= (3, 10): umask: int = -1, pipesize: int = -1, ) -> CompletedProcess[str]: - """ - Run command with arguments and return a CompletedProcess instance. + """Run command with arguments and return a CompletedProcess instance. The returned instance will have attributes args, returncode, stdout and stderr. By default, stdout and stderr are not captured, and those attributes @@ -646,8 +640,7 @@ else: extra_groups: Iterable[str | int] | None = None, umask: int = -1, ) -> CompletedProcess[str]: - """ - Run command with arguments and return a CompletedProcess instance. + """Run command with arguments and return a CompletedProcess instance. The returned instance will have attributes args, returncode, stdout and stderr. By default, stdout and stderr are not captured, and those attributes @@ -869,8 +862,7 @@ if sys.version_info >= (3, 11): pipesize: int = -1, process_group: int | None = None, ) -> int: - """ - Run command with arguments. Wait for command to complete or + """Run command with arguments. Wait for command to complete or for timeout seconds, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: @@ -908,8 +900,7 @@ elif sys.version_info >= (3, 10): umask: int = -1, pipesize: int = -1, ) -> int: - """ - Run command with arguments. Wait for command to complete or + """Run command with arguments. Wait for command to complete or timeout, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: @@ -945,8 +936,7 @@ else: extra_groups: Iterable[str | int] | None = None, umask: int = -1, ) -> int: - """ - Run command with arguments. Wait for command to complete or + """Run command with arguments. Wait for command to complete or timeout, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: @@ -986,8 +976,7 @@ if sys.version_info >= (3, 11): pipesize: int = -1, process_group: int | None = None, ) -> int: - """ - Run command with arguments. Wait for command to complete. If + """Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. @@ -1027,8 +1016,7 @@ elif sys.version_info >= (3, 10): umask: int = -1, pipesize: int = -1, ) -> int: - """ - Run command with arguments. Wait for command to complete. If + """Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. @@ -1066,8 +1054,7 @@ else: extra_groups: Iterable[str | int] | None = None, umask: int = -1, ) -> int: - """ - Run command with arguments. Wait for command to complete. If + """Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. @@ -1110,8 +1097,7 @@ if sys.version_info >= (3, 11): pipesize: int = -1, process_group: int | None = None, ) -> str: - """ - Run command with arguments and return its output. + """Run command with arguments and return its output. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode @@ -1335,8 +1321,7 @@ elif sys.version_info >= (3, 10): umask: int = -1, pipesize: int = -1, ) -> str: - """ - Run command with arguments and return its output. + """Run command with arguments and return its output. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode @@ -1553,8 +1538,7 @@ else: extra_groups: Iterable[str | int] | None = None, umask: int = -1, ) -> str: - """ - Run command with arguments and return its output. + """Run command with arguments and return its output. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode @@ -1743,8 +1727,7 @@ DEVNULL: Final[int] class SubprocessError(Exception): ... class TimeoutExpired(SubprocessError): - """ - This exception is raised when the timeout expires while waiting for a + """This exception is raised when the timeout expires while waiting for a child process. Attributes: @@ -1763,8 +1746,7 @@ class TimeoutExpired(SubprocessError): stderr: bytes | None class CalledProcessError(SubprocessError): - """ - Raised when run() is called with check=True and the process + """Raised when run() is called with check=True and the process returns a non-zero exit status. Attributes: @@ -1785,8 +1767,7 @@ class CalledProcessError(SubprocessError): ) -> None: ... class Popen(Generic[AnyStr]): - """ - Execute a child program in a new process. + """Execute a child program in a new process. For a complete description of the arguments see the Python documentation. @@ -1883,9 +1864,7 @@ class Popen(Generic[AnyStr]): pipesize: int = -1, process_group: int | None = None, ) -> None: - """ - Create new Popen instance. - """ + """Create new Popen instance.""" @overload def __init__( @@ -2075,9 +2054,7 @@ class Popen(Generic[AnyStr]): umask: int = -1, pipesize: int = -1, ) -> None: - """ - Create new Popen instance. - """ + """Create new Popen instance.""" @overload def __init__( @@ -2260,9 +2237,7 @@ class Popen(Generic[AnyStr]): extra_groups: Iterable[str | int] | None = None, umask: int = -1, ) -> None: - """ - Create new Popen instance. - """ + """Create new Popen instance.""" @overload def __init__( @@ -2412,21 +2387,17 @@ class Popen(Generic[AnyStr]): ) -> None: ... def poll(self) -> int | None: - """ - Check if child process has terminated. Set and return returncode + """Check if child process has terminated. Set and return returncode attribute. """ def wait(self, timeout: float | None = None) -> int: - """ - Wait for child process to terminate; returns self.returncode. - """ + """Wait for child process to terminate; returns self.returncode.""" # morally the members of the returned tuple should be optional # TODO: this should allow ReadableBuffer for Popen[bytes], but adding # overloads for that runs into a mypy bug (python/mypy#14070). def communicate(self, input: AnyStr | None = None, timeout: float | None = None) -> tuple[AnyStr, AnyStr]: - """ - Interact with process: Send data to stdin and close it. + """Interact with process: Send data to stdin and close it. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. @@ -2444,19 +2415,13 @@ class Popen(Generic[AnyStr]): """ def send_signal(self, sig: int) -> None: - """ - Send a signal to the process. - """ + """Send a signal to the process.""" def terminate(self) -> None: - """ - Terminate the process with SIGTERM - """ + """Terminate the process with SIGTERM""" def kill(self) -> None: - """ - Kill the process with SIGKILL - """ + """Kill the process with SIGKILL""" def __enter__(self) -> Self: ... def __exit__( @@ -2464,8 +2429,7 @@ class Popen(Generic[AnyStr]): ) -> None: ... def __del__(self) -> None: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ @@ -2473,8 +2437,7 @@ class Popen(Generic[AnyStr]): # The result really is always a str. if sys.version_info >= (3, 11): def getstatusoutput(cmd: _CMD, *, encoding: str | None = None, errors: str | None = None) -> tuple[int, str]: - """ - Return (exitcode, output) of executing cmd in a shell. + """Return (exitcode, output) of executing cmd in a shell. Execute the string 'cmd' in a shell with 'check_output' and return a 2-tuple (status, output). The locale encoding is used @@ -2496,8 +2459,7 @@ if sys.version_info >= (3, 11): """ def getoutput(cmd: _CMD, *, encoding: str | None = None, errors: str | None = None) -> str: - """ - Return output (stdout or stderr) of executing cmd in a shell. + """Return output (stdout or stderr) of executing cmd in a shell. Like getstatusoutput(), except the exit status is ignored and the return value is a string containing the command's output. Example: @@ -2509,8 +2471,7 @@ if sys.version_info >= (3, 11): else: def getstatusoutput(cmd: _CMD) -> tuple[int, str]: - """ - Return (exitcode, output) of executing cmd in a shell. + """Return (exitcode, output) of executing cmd in a shell. Execute the string 'cmd' in a shell with 'check_output' and return a 2-tuple (status, output). The locale encoding is used @@ -2532,8 +2493,7 @@ else: """ def getoutput(cmd: _CMD) -> str: - """ - Return output (stdout or stderr) of executing cmd in a shell. + """Return output (stdout or stderr) of executing cmd in a shell. Like getstatusoutput(), except the exit status is ignored and the return value is a string containing the command's output. Example: @@ -2544,8 +2504,7 @@ else: """ def list2cmdline(seq: Iterable[StrOrBytesPath]) -> str: # undocumented - """ - Translate a sequence of arguments into a command line + """Translate a sequence of arguments into a command line string, using the same rules as the MS C runtime: 1) Arguments are delimited by white space, which is either a diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/sunau.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/sunau.pyi index bb9d14c93a..6cd23f4e09 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/sunau.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/sunau.pyi @@ -128,9 +128,7 @@ AUDIO_FILE_ENCODING_ALAW_8: int AUDIO_UNKNOWN_SIZE: int class _sunau_params(NamedTuple): - """ - _sunau_params(nchannels, sampwidth, framerate, nframes, comptype, compname) - """ + """_sunau_params(nchannels, sampwidth, framerate, nframes, comptype, compname)""" nchannels: int sampwidth: int diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/symtable.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/symtable.pyi index 3f47305923..36280e42ca 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/symtable.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/symtable.pyi @@ -14,8 +14,7 @@ if sys.version_info >= (3, 13): __all__ += ["SymbolTableType"] def symtable(code: str, filename: str, compile_type: str) -> SymbolTable: - """ - Return the toplevel *SymbolTable* for the source code. + """Return the toplevel *SymbolTable* for the source code. *filename* is the name of the file with the code and *compile_type* is the *compile()* mode argument. @@ -37,29 +36,24 @@ class SymbolTable: def __init__(self, raw_table: Any, filename: str) -> None: ... if sys.version_info >= (3, 13): def get_type(self) -> SymbolTableType: - """ - Return the type of the symbol table. + """Return the type of the symbol table. The value returned is one of the values in the ``SymbolTableType`` enumeration. """ else: def get_type(self) -> str: - """ - Return the type of the symbol table. + """Return the type of the symbol table. The value returned is one of the values in the ``SymbolTableType`` enumeration. """ def get_id(self) -> int: - """ - Return an identifier for the table. - """ + """Return an identifier for the table.""" def get_name(self) -> str: - """ - Return the table's name. + """Return the table's name. This corresponds to the name of the class, function or 'top' if the table is for a class, function or @@ -67,171 +61,122 @@ class SymbolTable: """ def get_lineno(self) -> int: - """ - Return the number of the first line in the + """Return the number of the first line in the block for the table. """ def is_optimized(self) -> bool: - """ - Return *True* if the locals in the table + """Return *True* if the locals in the table are optimizable. """ def is_nested(self) -> bool: - """ - Return *True* if the block is a nested class + """Return *True* if the block is a nested class or function. """ def has_children(self) -> bool: - """ - Return *True* if the block has nested namespaces. - """ + """Return *True* if the block has nested namespaces.""" def get_identifiers(self) -> dict_keys[str, int]: - """ - Return a view object containing the names of symbols in the table. - """ + """Return a view object containing the names of symbols in the table.""" def lookup(self, name: str) -> Symbol: - """ - Lookup a *name* in the table. + """Lookup a *name* in the table. Returns a *Symbol* instance. """ def get_symbols(self) -> list[Symbol]: - """ - Return a list of *Symbol* instances for + """Return a list of *Symbol* instances for names in the table. """ def get_children(self) -> list[SymbolTable]: - """ - Return a list of the nested symbol tables. - """ + """Return a list of the nested symbol tables.""" class Function(SymbolTable): def get_parameters(self) -> tuple[str, ...]: - """ - Return a tuple of parameters to the function. - """ + """Return a tuple of parameters to the function.""" def get_locals(self) -> tuple[str, ...]: - """ - Return a tuple of locals in the function. - """ + """Return a tuple of locals in the function.""" def get_globals(self) -> tuple[str, ...]: - """ - Return a tuple of globals in the function. - """ + """Return a tuple of globals in the function.""" def get_frees(self) -> tuple[str, ...]: - """ - Return a tuple of free variables in the function. - """ + """Return a tuple of free variables in the function.""" def get_nonlocals(self) -> tuple[str, ...]: - """ - Return a tuple of nonlocals in the function. - """ + """Return a tuple of nonlocals in the function.""" class Class(SymbolTable): @deprecated("deprecated in Python 3.14, will be removed in Python 3.16") def get_methods(self) -> tuple[str, ...]: - """ - Return a tuple of methods declared in the class. - """ + """Return a tuple of methods declared in the class.""" class Symbol: def __init__( self, name: str, flags: int, namespaces: Sequence[SymbolTable] | None = None, *, module_scope: bool = False ) -> None: ... def is_nonlocal(self) -> bool: - """ - Return *True* if the symbol is nonlocal. - """ + """Return *True* if the symbol is nonlocal.""" def get_name(self) -> str: - """ - Return a name of a symbol. - """ + """Return a name of a symbol.""" def is_referenced(self) -> bool: - """ - Return *True* if the symbol is used in + """Return *True* if the symbol is used in its block. """ def is_parameter(self) -> bool: - """ - Return *True* if the symbol is a parameter. - """ + """Return *True* if the symbol is a parameter.""" if sys.version_info >= (3, 14): def is_type_parameter(self) -> bool: - """ - Return *True* if the symbol is a type parameter. - """ + """Return *True* if the symbol is a type parameter.""" def is_global(self) -> bool: - """ - Return *True* if the symbol is global. - """ + """Return *True* if the symbol is global.""" def is_declared_global(self) -> bool: - """ - Return *True* if the symbol is declared global + """Return *True* if the symbol is declared global with a global statement. """ def is_local(self) -> bool: - """ - Return *True* if the symbol is local. - """ + """Return *True* if the symbol is local.""" def is_annotated(self) -> bool: - """ - Return *True* if the symbol is annotated. - """ + """Return *True* if the symbol is annotated.""" def is_free(self) -> bool: - """ - Return *True* if a referenced symbol is + """Return *True* if a referenced symbol is not assigned to. """ if sys.version_info >= (3, 14): def is_free_class(self) -> bool: - """ - Return *True* if a class-scoped symbol is free from + """Return *True* if a class-scoped symbol is free from the perspective of a method. """ def is_imported(self) -> bool: - """ - Return *True* if the symbol is created from + """Return *True* if the symbol is created from an import statement. """ def is_assigned(self) -> bool: - """ - Return *True* if a symbol is assigned to. - """ + """Return *True* if a symbol is assigned to.""" if sys.version_info >= (3, 14): def is_comp_iter(self) -> bool: - """ - Return *True* if the symbol is a comprehension iteration variable. - """ + """Return *True* if the symbol is a comprehension iteration variable.""" def is_comp_cell(self) -> bool: - """ - Return *True* if the symbol is a cell in an inlined comprehension. - """ + """Return *True* if the symbol is a cell in an inlined comprehension.""" def is_namespace(self) -> bool: - """ - Returns *True* if name binding introduces new namespace. + """Returns *True* if name binding introduces new namespace. If the name is used as the target of a function or class statement, this will be true. @@ -243,13 +188,10 @@ class Symbol: """ def get_namespaces(self) -> Sequence[SymbolTable]: - """ - Return a list of namespaces bound to this name - """ + """Return a list of namespaces bound to this name""" def get_namespace(self) -> SymbolTable: - """ - Return the single namespace bound to this name. + """Return the single namespace bound to this name. Raises ValueError if the name is bound to multiple namespaces or no namespace. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/sys/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/sys/__init__.pyi index a2137a959c..0fdc5de862 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/sys/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/sys/__init__.pyi @@ -175,8 +175,7 @@ flags: _flags @final @type_check_only class _flags(_UninstantiableStructseq, tuple[int, ...]): - """ - sys.flags + """sys.flags Flags provided through command line arguments or environment vars. """ @@ -226,105 +225,71 @@ class _flags(_UninstantiableStructseq, tuple[int, ...]): @property def debug(self) -> int: - """ - -d - """ + """-d""" @property def inspect(self) -> int: - """ - -i - """ + """-i""" @property def interactive(self) -> int: - """ - -i - """ + """-i""" @property def optimize(self) -> int: - """ - -O or -OO - """ + """-O or -OO""" @property def dont_write_bytecode(self) -> int: - """ - -B - """ + """-B""" @property def no_user_site(self) -> int: - """ - -s - """ + """-s""" @property def no_site(self) -> int: - """ - -S - """ + """-S""" @property def ignore_environment(self) -> int: - """ - -E - """ + """-E""" @property def verbose(self) -> int: - """ - -v - """ + """-v""" @property def bytes_warning(self) -> int: - """ - -b - """ + """-b""" @property def quiet(self) -> int: - """ - -q - """ + """-q""" @property def hash_randomization(self) -> int: - """ - -R - """ + """-R""" @property def isolated(self) -> int: - """ - -I - """ + """-I""" @property def dev_mode(self) -> bool: - """ - -X dev - """ + """-X dev""" @property def utf8_mode(self) -> int: - """ - -X utf8 - """ + """-X utf8""" if sys.version_info >= (3, 10): @property def warn_default_encoding(self) -> int: - """ - -X warn_default_encoding - """ + """-X warn_default_encoding""" if sys.version_info >= (3, 11): @property def safe_path(self) -> bool: - """ - -P - """ + """-P""" # Whether or not this exists on lower versions of Python # may depend on which patch release you're using # (it was backported to all Python versions on 3.8+ as a security fix) @@ -332,9 +297,7 @@ class _flags(_UninstantiableStructseq, tuple[int, ...]): # and present in all versions of 3.11 and later. @property def int_max_str_digits(self) -> int: - """ - -X int_max_str_digits - """ + """-X int_max_str_digits""" float_info: _float_info @@ -342,8 +305,7 @@ float_info: _float_info @final @type_check_only class _float_info(structseq[float], tuple[float, int, int, float, int, int, int, int, float, int, int]): - """ - sys.float_info + """sys.float_info A named tuple holding information about the float type. It contains low level information about the precision and internal representation. Please study @@ -367,69 +329,47 @@ class _float_info(structseq[float], tuple[float, int, int, float, int, int, int, @property def max(self) -> float: # DBL_MAX - """ - DBL_MAX -- maximum representable finite float - """ + """DBL_MAX -- maximum representable finite float""" @property def max_exp(self) -> int: # DBL_MAX_EXP - """ - DBL_MAX_EXP -- maximum int e such that radix**(e-1) is representable - """ + """DBL_MAX_EXP -- maximum int e such that radix**(e-1) is representable""" @property def max_10_exp(self) -> int: # DBL_MAX_10_EXP - """ - DBL_MAX_10_EXP -- maximum int e such that 10**e is representable - """ + """DBL_MAX_10_EXP -- maximum int e such that 10**e is representable""" @property def min(self) -> float: # DBL_MIN - """ - DBL_MIN -- Minimum positive normalized float - """ + """DBL_MIN -- Minimum positive normalized float""" @property def min_exp(self) -> int: # DBL_MIN_EXP - """ - DBL_MIN_EXP -- minimum int e such that radix**(e-1) is a normalized float - """ + """DBL_MIN_EXP -- minimum int e such that radix**(e-1) is a normalized float""" @property def min_10_exp(self) -> int: # DBL_MIN_10_EXP - """ - DBL_MIN_10_EXP -- minimum int e such that 10**e is a normalized float - """ + """DBL_MIN_10_EXP -- minimum int e such that 10**e is a normalized float""" @property def dig(self) -> int: # DBL_DIG - """ - DBL_DIG -- maximum number of decimal digits that can be faithfully represented in a float - """ + """DBL_DIG -- maximum number of decimal digits that can be faithfully represented in a float""" @property def mant_dig(self) -> int: # DBL_MANT_DIG - """ - DBL_MANT_DIG -- mantissa digits - """ + """DBL_MANT_DIG -- mantissa digits""" @property def epsilon(self) -> float: # DBL_EPSILON - """ - DBL_EPSILON -- Difference between 1 and the next representable float - """ + """DBL_EPSILON -- Difference between 1 and the next representable float""" @property def radix(self) -> int: # FLT_RADIX - """ - FLT_RADIX -- radix of exponent - """ + """FLT_RADIX -- radix of exponent""" @property def rounds(self) -> int: # FLT_ROUNDS - """ - FLT_ROUNDS -- rounding mode used for arithmetic operations - """ + """FLT_ROUNDS -- rounding mode used for arithmetic operations""" hash_info: _hash_info @@ -437,8 +377,7 @@ hash_info: _hash_info @final @type_check_only class _hash_info(structseq[Any | int], tuple[int, int, int, int, int, str, int, int, int]): - """ - hash_info + """hash_info A named tuple providing parameters used for computing hashes. The attributes are read only. @@ -449,57 +388,39 @@ class _hash_info(structseq[Any | int], tuple[int, int, int, int, int, str, int, @property def width(self) -> int: - """ - width of the type used for hashing, in bits - """ + """width of the type used for hashing, in bits""" @property def modulus(self) -> int: - """ - prime number giving the modulus on which the hash function is based - """ + """prime number giving the modulus on which the hash function is based""" @property def inf(self) -> int: - """ - value to be used for hash of a positive infinity - """ + """value to be used for hash of a positive infinity""" @property def nan(self) -> int: - """ - value to be used for hash of a nan - """ + """value to be used for hash of a nan""" @property def imag(self) -> int: - """ - multiplier used for the imaginary part of a complex number - """ + """multiplier used for the imaginary part of a complex number""" @property def algorithm(self) -> str: - """ - name of the algorithm for hashing of str, bytes and memoryviews - """ + """name of the algorithm for hashing of str, bytes and memoryviews""" @property def hash_bits(self) -> int: - """ - internal output size of hash algorithm - """ + """internal output size of hash algorithm""" @property def seed_bits(self) -> int: - """ - seed size of hash algorithm - """ + """seed size of hash algorithm""" @property def cutoff(self) -> int: # undocumented - """ - small string optimization cutoff - """ + """small string optimization cutoff""" implementation: _implementation @@ -522,8 +443,7 @@ int_info: _int_info @final @type_check_only class _int_info(structseq[int], tuple[int, int, int, int]): - """ - sys.int_info + """sys.int_info A named tuple that holds information about Python's internal representation of integers. The attributes are read only. @@ -534,27 +454,19 @@ class _int_info(structseq[int], tuple[int, int, int, int]): @property def bits_per_digit(self) -> int: - """ - size of a digit in bits - """ + """size of a digit in bits""" @property def sizeof_digit(self) -> int: - """ - size in bytes of the C type used to represent a digit - """ + """size in bytes of the C type used to represent a digit""" @property def default_max_str_digits(self) -> int: - """ - maximum string conversion digits limitation - """ + """maximum string conversion digits limitation""" @property def str_digits_check_threshold(self) -> int: - """ - minimum positive value for int_max_str_digits - """ + """minimum positive value for int_max_str_digits""" _ThreadInfoName: TypeAlias = Literal["nt", "pthread", "pthread-stubs", "solaris"] _ThreadInfoLock: TypeAlias = Literal["semaphore", "mutex+cond"] | None @@ -563,8 +475,7 @@ _ThreadInfoLock: TypeAlias = Literal["semaphore", "mutex+cond"] | None @final @type_check_only class _thread_info(_UninstantiableStructseq, tuple[_ThreadInfoName, _ThreadInfoLock, str | None]): - """ - sys.thread_info + """sys.thread_info A named tuple holding information about the thread implementation. """ @@ -574,21 +485,15 @@ class _thread_info(_UninstantiableStructseq, tuple[_ThreadInfoName, _ThreadInfoL @property def name(self) -> _ThreadInfoName: - """ - name of the thread implementation - """ + """name of the thread implementation""" @property def lock(self) -> _ThreadInfoLock: - """ - name of the lock implementation - """ + """name of the lock implementation""" @property def version(self) -> str | None: - """ - name and version of the thread library - """ + """name and version of the thread library""" thread_info: _thread_info _ReleaseLevel: TypeAlias = Literal["alpha", "beta", "candidate", "final"] @@ -597,8 +502,7 @@ _ReleaseLevel: TypeAlias = Literal["alpha", "beta", "candidate", "final"] @final @type_check_only class _version_info(_UninstantiableStructseq, tuple[int, int, int, _ReleaseLevel, int]): - """ - sys.version_info + """sys.version_info Version information as a named tuple. """ @@ -608,39 +512,28 @@ class _version_info(_UninstantiableStructseq, tuple[int, int, int, _ReleaseLevel @property def major(self) -> int: - """ - Major release number - """ + """Major release number""" @property def minor(self) -> int: - """ - Minor release number - """ + """Minor release number""" @property def micro(self) -> int: - """ - Patch release number - """ + """Patch release number""" @property def releaselevel(self) -> _ReleaseLevel: - """ - 'alpha', 'beta', 'candidate', or 'final' - """ + """'alpha', 'beta', 'candidate', or 'final'""" @property def serial(self) -> int: - """ - Serial release number - """ + """Serial release number""" version_info: _version_info def call_tracing(func: Callable[..., _T], args: Any, /) -> _T: - """ - Call func(*args), while tracing is enabled. + """Call func(*args), while tracing is enabled. The tracing state is saved, and restored afterwards. This is intended to be called from a debugger from a checkpoint, to recursively debug @@ -650,26 +543,20 @@ def call_tracing(func: Callable[..., _T], args: Any, /) -> _T: if sys.version_info >= (3, 13): @deprecated("Deprecated in Python 3.13; use _clear_internal_caches() instead.") def _clear_type_cache() -> None: - """ - Clear the internal type lookup cache. - """ + """Clear the internal type lookup cache.""" else: def _clear_type_cache() -> None: - """ - Clear the internal type lookup cache. - """ + """Clear the internal type lookup cache.""" def _current_frames() -> dict[int, FrameType]: - """ - Return a dict mapping each thread's thread id to its current stack frame. + """Return a dict mapping each thread's thread id to its current stack frame. This function should be used for specialized purposes only. """ def _getframe(depth: int = 0, /) -> FrameType: - """ - Return a frame object from the call stack. + """Return a frame object from the call stack. If optional integer depth is given, return the frame object that many calls below the top of the stack. If that is deeper than the call @@ -682,8 +569,7 @@ def _getframe(depth: int = 0, /) -> FrameType: if sys.version_info >= (3, 12): def _getframemodulename(depth: int = 0) -> str | None: - """ - Return the name of the module for a calling frame. + """Return the name of the module for a calling frame. The default depth returns the module containing the call to this API. A more typical use in a library will pass a depth of 1 to get the user's @@ -693,26 +579,20 @@ if sys.version_info >= (3, 12): """ def _debugmallocstats() -> None: - """ - Print summary info to stderr about the state of pymalloc's structures. + """Print summary info to stderr about the state of pymalloc's structures. In Py_DEBUG mode, also perform some expensive internal consistency checks. """ def __displayhook__(object: object, /) -> None: - """ - Print an object to sys.stdout and also save it in builtins._ - """ + """Print an object to sys.stdout and also save it in builtins._""" def __excepthook__(exctype: type[BaseException], value: BaseException, traceback: TracebackType | None, /) -> None: - """ - Handle an exception by displaying it with a traceback on sys.stderr. - """ + """Handle an exception by displaying it with a traceback on sys.stderr.""" def exc_info() -> OptExcInfo: - """ - Return current exception information: (type, value, traceback). + """Return current exception information: (type, value, traceback). Return information about the most recent exception caught by an except clause in the current stack frame or in an older stack frame. @@ -720,8 +600,7 @@ def exc_info() -> OptExcInfo: if sys.version_info >= (3, 11): def exception() -> BaseException | None: - """ - Return the current exception. + """Return the current exception. Return the most recent exception caught by an except clause in the current stack frame or in an older stack frame, or None @@ -729,8 +608,7 @@ if sys.version_info >= (3, 11): """ def exit(status: _ExitCode = None, /) -> NoReturn: - """ - Exit the interpreter by raising SystemExit(status). + """Exit the interpreter by raising SystemExit(status). If the status is omitted or None, it defaults to zero (i.e., success). If the status is an integer, it will be used as the system exit status. @@ -739,36 +617,26 @@ def exit(status: _ExitCode = None, /) -> NoReturn: """ def getallocatedblocks() -> int: - """ - Return the number of memory blocks currently allocated. - """ + """Return the number of memory blocks currently allocated.""" def getdefaultencoding() -> str: - """ - Return the current default encoding used by the Unicode implementation. - """ + """Return the current default encoding used by the Unicode implementation.""" if sys.platform != "win32": def getdlopenflags() -> int: - """ - Return the current value of the flags that are used for dlopen calls. + """Return the current value of the flags that are used for dlopen calls. The flag constants are defined in the os module. """ def getfilesystemencoding() -> str: - """ - Return the encoding used to convert Unicode filenames to OS filenames. - """ + """Return the encoding used to convert Unicode filenames to OS filenames.""" def getfilesystemencodeerrors() -> str: - """ - Return the error mode used Unicode to OS filename conversion. - """ + """Return the error mode used Unicode to OS filename conversion.""" def getrefcount(object: Any, /) -> int: - """ - Return the reference count of object. + """Return the reference count of object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to @@ -776,8 +644,7 @@ def getrefcount(object: Any, /) -> int: """ def getrecursionlimit() -> int: - """ - Return the current value of the recursion limit. + """Return the current value of the recursion limit. The recursion limit is the maximum depth of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow @@ -785,42 +652,35 @@ def getrecursionlimit() -> int: """ def getsizeof(obj: object, default: int = ...) -> int: - """ - getsizeof(object [, default]) -> int + """getsizeof(object [, default]) -> int Return the size of object in bytes. """ def getswitchinterval() -> float: - """ - Return the current thread switch interval; see sys.setswitchinterval(). - """ + """Return the current thread switch interval; see sys.setswitchinterval().""" def getprofile() -> ProfileFunction | None: - """ - Return the profiling function set with sys.setprofile. + """Return the profiling function set with sys.setprofile. See the profiler chapter in the library manual. """ def setprofile(function: ProfileFunction | None, /) -> None: - """ - Set the profiling function. + """Set the profiling function. It will be called on each function call and return. See the profiler chapter in the library manual. """ def gettrace() -> TraceFunction | None: - """ - Return the global debug tracing function set with sys.settrace. + """Return the global debug tracing function set with sys.settrace. See the debugger chapter in the library manual. """ def settrace(function: TraceFunction | None, /) -> None: - """ - Set the global debug tracing function. + """Set the global debug tracing function. It will be called on each function call. See the debugger chapter in the library manual. @@ -851,11 +711,22 @@ if sys.platform == "win32": @property def platform_version(self) -> tuple[int, int, int]: ... - def getwindowsversion() -> _WinVersion: ... + def getwindowsversion() -> _WinVersion: + """Return info about the running version of Windows as a named tuple. + + The members are named: major, minor, build, platform, service_pack, + service_pack_major, service_pack_minor, suite_mask, product_type and + platform_version. For backward compatibility, only the first 5 items + are available by indexing. All elements are numbers, except + service_pack and platform_type which are strings, and platform_version + which is a 3-tuple. Platform is always 2. Product_type may be 1 for a + workstation, 2 for a domain controller, 3 for a server. + Platform_version is a 3-tuple containing a version number that is + intended for identifying the OS rather than feature detection. + """ def intern(string: str, /) -> str: - """ - ``Intern'' the given string. + """``Intern'' the given string. This enters the string in the (global) table of interned strings whose purpose is to speed up dictionary lookups. Return the string itself or @@ -864,36 +735,25 @@ def intern(string: str, /) -> str: if sys.version_info >= (3, 13): def _is_gil_enabled() -> bool: - """ - Return True if the GIL is currently enabled and False otherwise. - """ + """Return True if the GIL is currently enabled and False otherwise.""" def _clear_internal_caches() -> None: - """ - Clear all internal performance-related caches. - """ + """Clear all internal performance-related caches.""" def _is_interned(string: str, /) -> bool: - """ - Return True if the given string is "interned". - """ + """Return True if the given string is "interned".""" def is_finalizing() -> bool: - """ - Return True if Python is exiting. - """ + """Return True if Python is exiting.""" def breakpointhook(*args: Any, **kwargs: Any) -> Any: - """ - This hook function is called by built-in breakpoint(). - """ + """This hook function is called by built-in breakpoint().""" __breakpointhook__ = breakpointhook # Contains the original value of breakpointhook if sys.platform != "win32": def setdlopenflags(flags: int, /) -> None: - """ - Set the flags used by the interpreter for dlopen calls. + """Set the flags used by the interpreter for dlopen calls. This is used, for example, when the interpreter loads extension modules. Among other things, this will enable a lazy resolving of @@ -905,8 +765,7 @@ if sys.platform != "win32": """ def setrecursionlimit(limit: int, /) -> None: - """ - Set the maximum depth of the Python interpreter stack to n. + """Set the maximum depth of the Python interpreter stack to n. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. The highest possible limit is platform- @@ -914,8 +773,7 @@ def setrecursionlimit(limit: int, /) -> None: """ def setswitchinterval(interval: float, /) -> None: - """ - Set the ideal thread switching delay inside the Python interpreter. + """Set the ideal thread switching delay inside the Python interpreter. The actual frequency of switching threads can be lower if the interpreter executes long sequences of uninterruptible code @@ -939,8 +797,7 @@ class UnraisableHookArgs(Protocol): unraisablehook: Callable[[UnraisableHookArgs], Any] def __unraisablehook__(unraisable: UnraisableHookArgs, /) -> Any: - """ - Handle an unraisable exception. + """Handle an unraisable exception. The unraisable argument has the following attributes: @@ -952,14 +809,10 @@ def __unraisablehook__(unraisable: UnraisableHookArgs, /) -> Any: """ def addaudithook(hook: Callable[[str, tuple[Any, ...]], Any]) -> None: - """ - Adds a new audit hook callback. - """ + """Adds a new audit hook callback.""" def audit(event: str, /, *args: Any) -> None: - """ - Passes the event to any audit hooks that are attached. - """ + """Passes the event to any audit hooks that are attached.""" _AsyncgenHook: TypeAlias = Callable[[AsyncGenerator[Any, Any]], None] | None @@ -976,30 +829,33 @@ class _asyncgen_hooks(structseq[_AsyncgenHook], tuple[_AsyncgenHook, _AsyncgenHo def finalizer(self) -> _AsyncgenHook: ... def get_asyncgen_hooks() -> _asyncgen_hooks: - """ - Return the installed asynchronous generators hooks. + """Return the installed asynchronous generators hooks. This returns a namedtuple of the form (firstiter, finalizer). """ def set_asyncgen_hooks(firstiter: _AsyncgenHook = ..., finalizer: _AsyncgenHook = ...) -> None: - """ - set_asyncgen_hooks([firstiter] [, finalizer]) + """set_asyncgen_hooks([firstiter] [, finalizer]) Set a finalizer for async generators objects. """ if sys.platform == "win32": - def _enablelegacywindowsfsencoding() -> None: ... + def _enablelegacywindowsfsencoding() -> None: + """Changes the default filesystem encoding to mbcs:replace. + + This is done for consistency with earlier versions of Python. See PEP + 529 for more information. + + This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING + environment variable before launching Python. + """ def get_coroutine_origin_tracking_depth() -> int: - """ - Check status of origin tracking for coroutine objects in this thread. - """ + """Check status of origin tracking for coroutine objects in this thread.""" def set_coroutine_origin_tracking_depth(depth: int) -> None: - """ - Enable or disable origin tracking for coroutine objects in this thread. + """Enable or disable origin tracking for coroutine objects in this thread. Coroutine objects will track 'depth' frames of traceback information about where they came from, available in their cr_origin attribute. @@ -1010,60 +866,44 @@ def set_coroutine_origin_tracking_depth(depth: int) -> None: # The following two functions were added in 3.11.0, 3.10.7, and 3.9.14, # as part of the response to CVE-2020-10735 def set_int_max_str_digits(maxdigits: int) -> None: - """ - Set the maximum string digits limit for non-binary int<->str conversions. - """ + """Set the maximum string digits limit for non-binary int<->str conversions.""" def get_int_max_str_digits() -> int: - """ - Return the maximum string digits limit for non-binary int<->str conversions. - """ + """Return the maximum string digits limit for non-binary int<->str conversions.""" if sys.version_info >= (3, 12): if sys.version_info >= (3, 13): def getunicodeinternedsize(*, _only_immortal: bool = False) -> int: - """ - Return the number of elements of the unicode interned dictionary - """ + """Return the number of elements of the unicode interned dictionary""" else: def getunicodeinternedsize() -> int: - """ - Return the number of elements of the unicode interned dictionary - """ + """Return the number of elements of the unicode interned dictionary""" def deactivate_stack_trampoline() -> None: - """ - Deactivate the current stack profiler trampoline backend. + """Deactivate the current stack profiler trampoline backend. If no stack profiler is activated, this function has no effect. """ def is_stack_trampoline_active() -> bool: - """ - Return *True* if a stack profiler trampoline is active. - """ + """Return *True* if a stack profiler trampoline is active.""" # It always exists, but raises on non-linux platforms: if sys.platform == "linux": def activate_stack_trampoline(backend: str, /) -> None: - """ - Activate stack profiler trampoline *backend*. - """ + """Activate stack profiler trampoline *backend*.""" else: - def activate_stack_trampoline(backend: str, /) -> NoReturn: ... - + def activate_stack_trampoline(backend: str, /) -> NoReturn: + """Activate stack profiler trampoline *backend*.""" from . import _monitoring monitoring = _monitoring if sys.version_info >= (3, 14): def is_remote_debug_enabled() -> bool: - """ - Return True if remote debugging is enabled, False otherwise. - """ + """Return True if remote debugging is enabled, False otherwise.""" def remote_exec(pid: int, script: StrOrBytesPath) -> None: - """ - Executes a file containing Python code in a given remote Python process. + """Executes a file containing Python code in a given remote Python process. This function returns immediately, and the code will be executed by the target process's main thread at the next available opportunity, similarly diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/sysconfig.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/sysconfig.pyi index 8d85c936fb..8307f1bb3c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/sysconfig.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/sysconfig.pyi @@ -23,8 +23,7 @@ __all__ = [ @overload @deprecated("SO is deprecated, use EXT_SUFFIX. Support is removed in Python 3.11") def get_config_var(name: Literal["SO"]) -> Any: - """ - Return the value of a single variable using the dictionary returned by + """Return the value of a single variable using the dictionary returned by 'get_config_vars()'. Equivalent to get_config_vars().get(name) @@ -34,8 +33,7 @@ def get_config_var(name: Literal["SO"]) -> Any: def get_config_var(name: str) -> Any: ... @overload def get_config_vars() -> dict[str, Any]: - """ - With no arguments, return a dictionary of all configuration + """With no arguments, return a dictionary of all configuration variables relevant for the current platform. On Unix, this means every variable defined in Python's installed Makefile; @@ -48,29 +46,23 @@ def get_config_vars() -> dict[str, Any]: @overload def get_config_vars(arg: str, /, *args: str) -> list[Any]: ... def get_scheme_names() -> tuple[str, ...]: - """ - Return a tuple containing the schemes names. - """ + """Return a tuple containing the schemes names.""" if sys.version_info >= (3, 10): def get_default_scheme() -> str: ... def get_preferred_scheme(key: Literal["prefix", "home", "user"]) -> str: ... def get_path_names() -> tuple[str, ...]: - """ - Return a tuple containing the paths names. - """ + """Return a tuple containing the paths names.""" def get_path(name: str, scheme: str = ..., vars: dict[str, Any] | None = None, expand: bool = True) -> str: - """ - Return a path corresponding to the scheme. + """Return a path corresponding to the scheme. ``scheme`` is the install scheme name. """ def get_paths(scheme: str = ..., vars: dict[str, Any] | None = None, expand: bool = True) -> dict[str, str]: - """ - Return a mapping containing an install scheme. + """Return a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform. @@ -78,8 +70,7 @@ def get_paths(scheme: str = ..., vars: dict[str, Any] | None = None, expand: boo def get_python_version() -> str: ... def get_platform() -> str: - """ - Return a string that identifies the current platform. + """Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and @@ -107,8 +98,7 @@ else: 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]: - """ - Parse a config.h-style file. + """Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is @@ -116,11 +106,7 @@ def parse_config_h(fp: IO[Any], vars: dict[str, Any] | None = None) -> dict[str, """ def get_config_h_filename() -> str: - """ - Return the path of pyconfig.h. - """ + """Return the path of pyconfig.h.""" def get_makefile_filename() -> str: - """ - Return the path of the Makefile. - """ + """Return the path of the Makefile.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/syslog.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/syslog.pyi index 2171d9b4dc..8300ab0f7c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/syslog.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/syslog.pyi @@ -47,34 +47,23 @@ if sys.platform != "win32": LOG_REMOTEAUTH: Final = 104 def LOG_MASK(pri: int, /) -> int: - """ - Calculates the mask for the individual priority pri. - """ + """Calculates the mask for the individual priority pri.""" def LOG_UPTO(pri: int, /) -> int: - """ - Calculates the mask for all priorities up to and including pri. - """ + """Calculates the mask for all priorities up to and including pri.""" def closelog() -> None: - """ - Reset the syslog module values and call the system library closelog(). - """ + """Reset the syslog module values and call the system library closelog().""" def openlog(ident: str = ..., logoption: int = ..., facility: int = ...) -> None: - """ - Set logging options of subsequent syslog() calls. - """ + """Set logging options of subsequent syslog() calls.""" def setlogmask(maskpri: int, /) -> int: - """ - Set the priority mask to maskpri and return the previous mask value. - """ + """Set the priority mask to maskpri and return the previous mask value.""" @overload def syslog(priority: int, message: str) -> None: - """ - syslog([priority=LOG_INFO,] message) + """syslog([priority=LOG_INFO,] message) Send the string message to the system logger. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/tabnanny.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/tabnanny.pyi index 41601718f1..a02a23bd59 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/tabnanny.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/tabnanny.pyi @@ -20,8 +20,7 @@ verbose: int filename_only: int class NannyNag(Exception): - """ - Raised by process_tokens() if detecting an ambiguous indent. + """Raised by process_tokens() if detecting an ambiguous indent. Captured and handled in check(). """ @@ -31,8 +30,7 @@ class NannyNag(Exception): def get_line(self) -> str: ... def check(file: StrOrBytesPath) -> None: - """ - check(file_or_dir) + """check(file_or_dir) If file_or_dir is a directory and not a symbolic link, then recursively descend the directory tree named by file_or_dir, checking all .py files diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/tarfile.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/tarfile.pyi index 86344ad09c..b8bd5b8ea4 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/tarfile.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/tarfile.pyi @@ -116,9 +116,7 @@ class ExFileObject(io.BufferedReader): def __init__(self, tarfile: TarFile, tarinfo: TarInfo) -> None: ... class TarFile: - """ - The TarFile Class provides an interface to tar archives. - """ + """The TarFile Class provides an interface to tar archives.""" OPEN_METH: ClassVar[Mapping[str, str]] name: StrOrBytesPath | None @@ -155,8 +153,7 @@ class TarFile: copybufsize: int | None = None, # undocumented stream: bool = False, ) -> None: - """ - Open an (uncompressed) tar archive 'name'. 'mode' is either 'r' to + """Open an (uncompressed) tar archive 'name'. 'mode' is either 'r' to read from an existing archive, 'a' to append data to an existing file or 'w' to create a new file overwriting an existing one. 'mode' defaults to 'r'. @@ -181,8 +178,7 @@ class TarFile: errorlevel: int | None = None, copybufsize: int | None = None, # undocumented ) -> None: - """ - Open an (uncompressed) tar archive 'name'. 'mode' is either 'r' to + """Open an (uncompressed) tar archive 'name'. 'mode' is either 'r' to read from an existing archive, 'a' to append data to an existing file or 'w' to create a new file overwriting an existing one. 'mode' defaults to 'r'. @@ -196,9 +192,7 @@ class TarFile: self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... def __iter__(self) -> Iterator[TarInfo]: - """ - Provide an iterator object. - """ + """Provide an iterator object.""" @overload @classmethod @@ -219,8 +213,7 @@ class TarFile: debug: int | None = ..., errorlevel: int | None = ..., ) -> Self: - """ - Open a tar archive for reading, writing or appending. Return + """Open a tar archive for reading, writing or appending. Return an appropriate TarFile class. mode: @@ -283,8 +276,7 @@ class TarFile: options: Mapping[int, int] | None = None, zstd_dict: ZstdDict | None = None, ) -> Self: - """ - Open a tar archive for reading, writing or appending. Return + """Open a tar archive for reading, writing or appending. Return an appropriate TarFile class. mode: @@ -465,8 +457,7 @@ class TarFile: options: Mapping[int, int] | None = None, zstd_dict: ZstdDict | None = None, ) -> Self: - """ - Open a tar archive for reading, writing or appending. Return + """Open a tar archive for reading, writing or appending. Return an appropriate TarFile class. mode: @@ -662,9 +653,7 @@ class TarFile: debug: int | None = ..., errorlevel: int | None = ..., ) -> Self: - """ - Open uncompressed tar archive name for reading or writing. - """ + """Open uncompressed tar archive name for reading or writing.""" @overload @classmethod @@ -684,8 +673,7 @@ class TarFile: debug: int | None = ..., errorlevel: int | None = ..., ) -> Self: - """ - Open gzip compressed tar archive name for reading or writing. + """Open gzip compressed tar archive name for reading or writing. Appending is not allowed. """ @@ -725,8 +713,7 @@ class TarFile: debug: int | None = ..., errorlevel: int | None = ..., ) -> Self: - """ - Open bzip2 compressed tar archive name for reading or writing. + """Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed. """ @@ -765,8 +752,7 @@ class TarFile: debug: int | None = ..., errorlevel: int | None = ..., ) -> Self: - """ - Open lzma compressed tar archive name for reading or writing. + """Open lzma compressed tar archive name for reading or writing. Appending is not allowed. """ if sys.version_info >= (3, 14): @@ -790,8 +776,7 @@ class TarFile: debug: int | None = ..., errorlevel: int | None = ..., ) -> Self: - """ - Open zstd compressed tar archive name for reading or writing. + """Open zstd compressed tar archive name for reading or writing. Appending is not allowed. """ @@ -817,36 +802,31 @@ class TarFile: ) -> Self: ... def getmember(self, name: str) -> TarInfo: - """ - Return a TarInfo object for member 'name'. If 'name' can not be + """Return a TarInfo object for member 'name'. If 'name' can not be found in the archive, KeyError is raised. If a member occurs more than once in the archive, its last occurrence is assumed to be the most up-to-date version. """ def getmembers(self) -> _list[TarInfo]: - """ - Return the members of the archive as a list of TarInfo objects. The + """Return the members of the archive as a list of TarInfo objects. The list has the same order as the members in the archive. """ def getnames(self) -> _list[str]: - """ - Return the members of the archive as a list of their names. It has + """Return the members of the archive as a list of their names. It has the same order as the list returned by getmembers(). """ def list(self, verbose: bool = True, *, members: _list[TarInfo] | None = None) -> None: - """ - Print a table of contents to sys.stdout. If 'verbose' is False, only + """Print a table of contents to sys.stdout. If 'verbose' is False, only the names of the members are printed. If it is True, an 'ls -l'-like output is produced. 'members' is optional and must be a subset of the list returned by getmembers(). """ def next(self) -> TarInfo | None: - """ - Return the next member of the archive as a TarInfo object, when + """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ @@ -860,8 +840,7 @@ class TarFile: numeric_owner: bool = False, filter: _TarfileFilter | None = ..., ) -> None: - """ - Extract all members from the archive to the current working + """Extract all members from the archive to the current working directory and set owner, modification time and permissions on directories afterwards. 'path' specifies a different directory to extract to. 'members' is optional and must be a subset of the @@ -883,8 +862,7 @@ class TarFile: numeric_owner: bool = False, filter: _TarfileFilter | None = ..., ) -> None: - """ - Extract a member from the archive to the current working directory, + """Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. 'member' may be a filename or a TarInfo object. You can specify a different directory using 'path'. File attributes (owner, @@ -907,8 +885,7 @@ class TarFile: filter_function: _FilterFunction | None = None, extraction_root: str | None = None, ) -> None: # undocumented - """ - Extract the filtered TarInfo object tarinfo to a physical + """Extract the filtered TarInfo object tarinfo to a physical file called targetpath. filter_function is only used when extracting a *different* @@ -916,8 +893,7 @@ class TarFile: """ def extractfile(self, member: str | TarInfo) -> IO[bytes] | None: - """ - Extract a member from the archive as a file object. 'member' may be + """Extract a member from the archive as a file object. 'member' may be a filename or a TarInfo object. If 'member' is a regular file or a link, an io.BufferedReader object is returned. For all other existing members, None is returned. If 'member' does not appear @@ -925,37 +901,27 @@ class TarFile: """ def makedir(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: # undocumented - """ - Make a directory called targetpath. - """ + """Make a directory called targetpath.""" def makefile(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: # undocumented - """ - Make a file called targetpath. - """ + """Make a file called targetpath.""" def makeunknown(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: # undocumented - """ - Make a file from a TarInfo object with an unknown type + """Make a file from a TarInfo object with an unknown type at targetpath. """ def makefifo(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: # undocumented - """ - Make a fifo called targetpath. - """ + """Make a fifo called targetpath.""" def makedev(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: # undocumented - """ - Make a character or block device called targetpath. - """ + """Make a character or block device called targetpath.""" def makelink(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented def makelink_with_filter( self, tarinfo: TarInfo, targetpath: StrOrBytesPath, filter_function: _FilterFunction, extraction_root: str ) -> None: # undocumented - """ - Make a (symbolic) link called targetpath. If it cannot be created + """Make a (symbolic) link called targetpath. If it cannot be created (platform limitation), we try to make a copy of the referenced file instead of a link. @@ -964,22 +930,17 @@ class TarFile: """ def chown(self, tarinfo: TarInfo, targetpath: StrOrBytesPath, numeric_owner: bool) -> None: # undocumented - """ - Set owner of targetpath according to tarinfo. If numeric_owner + """Set owner of targetpath according to tarinfo. If numeric_owner is True, use .gid/.uid instead of .gname/.uname. If numeric_owner is False, fall back to .gid/.uid when the search based on name fails. """ def chmod(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: # undocumented - """ - Set file permissions of targetpath according to tarinfo. - """ + """Set file permissions of targetpath according to tarinfo.""" def utime(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: # undocumented - """ - Set modification time of targetpath according to tarinfo. - """ + """Set modification time of targetpath according to tarinfo.""" def add( self, @@ -989,8 +950,7 @@ class TarFile: *, filter: Callable[[TarInfo], TarInfo | None] | None = None, ) -> None: - """ - Add the file 'name' to the archive. 'name' may be any type of file + """Add the file 'name' to the archive. 'name' may be any type of file (directory, fifo, symbolic link, etc.). If given, 'arcname' specifies an alternative name for the file in the archive. Directories are added recursively by default. This can be avoided by @@ -1001,8 +961,7 @@ class TarFile: """ def addfile(self, tarinfo: TarInfo, fileobj: SupportsRead[bytes] | None = None) -> None: - """ - Add the TarInfo object 'tarinfo' to the archive. If 'tarinfo' represents + """Add the TarInfo object 'tarinfo' to the archive. If 'tarinfo' represents a non zero-size regular file, the 'fileobj' argument should be a binary file, and tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects directly, or by using gettarinfo(). @@ -1011,8 +970,7 @@ class TarFile: def gettarinfo( self, name: StrOrBytesPath | None = None, arcname: str | None = None, fileobj: IO[bytes] | None = None ) -> TarInfo: - """ - Create a TarInfo object from the result of os.stat or equivalent + """Create a TarInfo object from the result of os.stat or equivalent on an existing file. The file is either named by 'name', or specified as a file object 'fileobj' with a file descriptor. If given, 'arcname' specifies an alternative name for the file in the @@ -1022,50 +980,36 @@ class TarFile: """ def close(self) -> None: - """ - Close the TarFile. In write-mode, two finishing zero blocks are + """Close the TarFile. In write-mode, two finishing zero blocks are appended to the archive. """ open = TarFile.open def is_tarfile(name: StrOrBytesPath | IO[bytes]) -> bool: - """ - Return True if name points to a tar archive that we + """Return True if name points to a tar archive that we are able to handle, else return False. 'name' should be a string, file, or file-like object. """ class TarError(Exception): - """ - Base exception. - """ + """Base exception.""" class ReadError(TarError): - """ - Exception for unreadable tar archives. - """ + """Exception for unreadable tar archives.""" class CompressionError(TarError): - """ - Exception for unavailable compression methods. - """ + """Exception for unavailable compression methods.""" class StreamError(TarError): - """ - Exception for unsupported operations on stream-like TarFiles. - """ + """Exception for unsupported operations on stream-like TarFiles.""" class ExtractError(TarError): - """ - General exception for extract errors. - """ + """General exception for extract errors.""" class HeaderError(TarError): - """ - Base exception for header errors. - """ + """Base exception for header errors.""" class FilterError(TarError): # This attribute is only set directly on the subclasses, but the documentation guarantees @@ -1095,8 +1039,7 @@ def tar_filter(member: TarInfo, dest_path: str) -> TarInfo: ... def data_filter(member: TarInfo, dest_path: str) -> TarInfo: ... class TarInfo: - """ - Informational class which holds the details about an + """Informational class which holds the details about an archive member given by a tar header block. TarInfo objects are returned by TarFile.getmember(), TarFile.getmembers() and TarFile.gettarinfo() and are @@ -1122,8 +1065,7 @@ class TarInfo: gname: str pax_headers: Mapping[str, str] def __init__(self, name: str = "") -> None: - """ - Construct a TarInfo object. name is the optional name + """Construct a TarInfo object. name is the optional name of the member. """ if sys.version_info >= (3, 13): @@ -1138,22 +1080,17 @@ class TarInfo: @classmethod def frombuf(cls, buf: bytes | bytearray, encoding: str, errors: str) -> Self: - """ - Construct a TarInfo object from a 512 byte bytes object. - """ + """Construct a TarInfo object from a 512 byte bytes object.""" @classmethod def fromtarfile(cls, tarfile: TarFile) -> Self: - """ - Return the next TarInfo object from TarFile object + """Return the next TarInfo object from TarFile object tarfile. """ @property def linkpath(self) -> str: - """ - In pax headers, "linkname" is called "linkpath". - """ + """In pax headers, "linkname" is called "linkpath".""" @linkpath.setter def linkpath(self, linkname: str) -> None: ... @@ -1170,85 +1107,54 @@ class TarInfo: gname: str = ..., deep: bool = True, ) -> Self: - """ - Return a deep copy of self with the given attributes replaced. - """ + """Return a deep copy of self with the given attributes replaced.""" def get_info(self) -> Mapping[str, str | int | bytes | Mapping[str, str]]: - """ - Return the TarInfo's attributes as a dictionary. - """ + """Return the TarInfo's attributes as a dictionary.""" def tobuf(self, format: int | None = 2, encoding: str | None = "utf-8", errors: str = "surrogateescape") -> bytes: - """ - Return a tar header as a string of 512 byte blocks. - """ + """Return a tar header as a string of 512 byte blocks.""" def create_ustar_header(self, info: Mapping[str, str | int | bytes | Mapping[str, str]], encoding: str, errors: str) -> bytes: - """ - Return the object as a ustar header block. - """ + """Return the object as a ustar header block.""" def create_gnu_header(self, info: Mapping[str, str | int | bytes | Mapping[str, str]], encoding: str, errors: str) -> bytes: - """ - Return the object as a GNU header block sequence. - """ + """Return the object as a GNU header block sequence.""" def create_pax_header(self, info: Mapping[str, str | int | bytes | Mapping[str, str]], encoding: str) -> bytes: - """ - Return the object as a ustar header block. If it cannot be + """Return the object as a ustar header block. If it cannot be represented this way, prepend a pax extended header sequence with supplement information. """ @classmethod def create_pax_global_header(cls, pax_headers: Mapping[str, str]) -> bytes: - """ - Return the object as a pax global header block sequence. - """ + """Return the object as a pax global header block sequence.""" def isfile(self) -> bool: - """ - Return True if the Tarinfo object is a regular file. - """ + """Return True if the Tarinfo object is a regular file.""" def isreg(self) -> bool: - """ - Return True if the Tarinfo object is a regular file. - """ + """Return True if the Tarinfo object is a regular file.""" def issparse(self) -> bool: ... def isdir(self) -> bool: - """ - Return True if it is a directory. - """ + """Return True if it is a directory.""" def issym(self) -> bool: - """ - Return True if it is a symbolic link. - """ + """Return True if it is a symbolic link.""" def islnk(self) -> bool: - """ - Return True if it is a hard link. - """ + """Return True if it is a hard link.""" def ischr(self) -> bool: - """ - Return True if it is a character device. - """ + """Return True if it is a character device.""" def isblk(self) -> bool: - """ - Return True if it is a block device. - """ + """Return True if it is a block device.""" def isfifo(self) -> bool: - """ - Return True if it is a FIFO. - """ + """Return True if it is a FIFO.""" def isdev(self) -> bool: - """ - Return True if it is one of character device, block device or FIFO. - """ + """Return True if it is one of character device, block device or FIFO.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/telnetlib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/telnetlib.pyi index 097a0955ae..a35c3a5c12 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/telnetlib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/telnetlib.pyi @@ -120,8 +120,7 @@ EXOPL: bytes NOOPT: bytes class Telnet: - """ - Telnet interface class. + """Telnet interface class. An instance of this class represents a connection to a telnet server. The instance is initially not connected; the open() @@ -176,8 +175,7 @@ class Telnet: host: str | None # undocumented sock: socket.socket | None # undocumented def __init__(self, host: str | None = None, port: int = 0, timeout: float = ...) -> None: - """ - Constructor. + """Constructor. When called without arguments, create an unconnected instance. With a hostname argument, it connects the instance; port number @@ -185,8 +183,7 @@ class Telnet: """ def open(self, host: str, port: int = 0, timeout: float = ...) -> None: - """ - Connect to a host. + """Connect to a host. The optional second argument is the port number, which defaults to the standard telnet port (23). @@ -195,46 +192,36 @@ class Telnet: """ def msg(self, msg: str, *args: Any) -> None: - """ - Print a debug message, when the debug level is > 0. + """Print a debug message, when the debug level is > 0. If extra arguments are present, they are substituted in the message using the standard string formatting operator. """ def set_debuglevel(self, debuglevel: int) -> None: - """ - Set the debug level. + """Set the debug level. The higher it is, the more debug output you get (on sys.stdout). """ def close(self) -> None: - """ - Close the connection. - """ + """Close the connection.""" def get_socket(self) -> socket.socket: - """ - Return the socket object used internally. - """ + """Return the socket object used internally.""" def fileno(self) -> int: - """ - Return the fileno() of the socket object used internally. - """ + """Return the fileno() of the socket object used internally.""" def write(self, buffer: bytes) -> None: - """ - Write a string to the socket, doubling any IAC characters. + """Write a string to the socket, doubling any IAC characters. Can block if the connection is blocked. May raise OSError if the connection is closed. """ def read_until(self, match: bytes, timeout: float | None = None) -> bytes: - """ - Read until a given string is encountered or until timeout. + """Read until a given string is encountered or until timeout. When no match is found, return whatever is available instead, possibly the empty string. Raise EOFError if the connection @@ -242,21 +229,17 @@ class Telnet: """ def read_all(self) -> bytes: - """ - Read all data until EOF; block until connection closed. - """ + """Read all data until EOF; block until connection closed.""" def read_some(self) -> bytes: - """ - Read at least one byte of cooked data unless EOF is hit. + """Read at least one byte of cooked data unless EOF is hit. Return b'' if EOF is hit. Block if no data is immediately available. """ def read_very_eager(self) -> bytes: - """ - Read everything that's possible without blocking in I/O (eager). + """Read everything that's possible without blocking in I/O (eager). Raise EOFError if connection closed and no cooked data available. Return b'' if no cooked data available otherwise. @@ -264,8 +247,7 @@ class Telnet: """ def read_eager(self) -> bytes: - """ - Read readily available data. + """Read readily available data. Raise EOFError if connection closed and no cooked data available. Return b'' if no cooked data available otherwise. @@ -273,8 +255,7 @@ class Telnet: """ def read_lazy(self) -> bytes: - """ - Process and return data that's already in the queues (lazy). + """Process and return data that's already in the queues (lazy). Raise EOFError if connection closed and no data available. Return b'' if no cooked data available otherwise. Don't block @@ -282,16 +263,14 @@ class Telnet: """ def read_very_lazy(self) -> bytes: - """ - Return any data available in the cooked queue (very lazy). + """Return any data available in the cooked queue (very lazy). Raise EOFError if connection closed and no data available. Return b'' if no cooked data available otherwise. Don't block. """ def read_sb_data(self) -> bytes: - """ - Return any data available in the SB ... SE queue. + """Return any data available in the SB ... SE queue. Return b'' if no SB ... SE available. Should only be called after seeing a SB or SE command. When a new SB command is @@ -299,59 +278,45 @@ class Telnet: """ def set_option_negotiation_callback(self, callback: Callable[[socket.socket, bytes, bytes], object] | None) -> None: - """ - Provide a callback function called after each receipt of a telnet option. - """ + """Provide a callback function called after each receipt of a telnet option.""" def process_rawq(self) -> None: - """ - Transfer from raw queue to cooked queue. + """Transfer from raw queue to cooked queue. Set self.eof when connection is closed. Don't block unless in the midst of an IAC sequence. """ def rawq_getchar(self) -> bytes: - """ - Get next char from raw queue. + """Get next char from raw queue. Block if no data is immediately available. Raise EOFError when connection is closed. """ def fill_rawq(self) -> None: - """ - Fill raw queue from exactly one recv() system call. + """Fill raw queue from exactly one recv() system call. Block if no data is immediately available. Set self.eof when connection is closed. """ def sock_avail(self) -> bool: - """ - Test whether data is available on the socket. - """ + """Test whether data is available on the socket.""" def interact(self) -> None: - """ - Interaction function, emulates a very dumb telnet client. - """ + """Interaction function, emulates a very dumb telnet client.""" def mt_interact(self) -> None: - """ - Multithreaded version of interact(). - """ + """Multithreaded version of interact().""" def listener(self) -> None: - """ - Helper for mt_interact() -- this executes in the other thread. - """ + """Helper for mt_interact() -- this executes in the other thread.""" def expect( self, list: MutableSequence[Pattern[bytes] | bytes] | Sequence[Pattern[bytes]], timeout: float | None = None ) -> tuple[int, Match[bytes] | None, bytes]: - """ - Read until one from a list of a regular expressions matches. + """Read until one from a list of a regular expressions matches. The first argument is a list of regular expressions, either compiled (re.Pattern instances) or uncompiled (strings). @@ -377,6 +342,4 @@ class Telnet: self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... def __del__(self) -> None: - """ - Destructor -- close the connection. - """ + """Destructor -- close the connection.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/tempfile.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/tempfile.pyi index 3f3d357aa8..607376b692 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/tempfile.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/tempfile.pyi @@ -79,8 +79,7 @@ if sys.version_info >= (3, 12): errors: str | None = None, delete_on_close: bool = True, ) -> _TemporaryFileWrapper[str]: - """ - Create and return a temporary file. + """Create and return a temporary file. Arguments: 'prefix', 'suffix', 'dir' -- as for mkstemp. 'mode' -- the mode argument to io.open (default "w+b"). @@ -146,8 +145,7 @@ else: *, errors: str | None = None, ) -> _TemporaryFileWrapper[str]: - """ - Create and return a temporary file. + """Create and return a temporary file. Arguments: 'prefix', 'suffix', 'dir' -- as for mkstemp. 'mode' -- the mode argument to io.open (default "w+b"). @@ -210,8 +208,7 @@ else: *, errors: str | None = None, ) -> io.TextIOWrapper: - """ - Create and return a temporary file. + """Create and return a temporary file. Arguments: 'prefix', 'suffix', 'dir' -- as for mkstemp. 'mode' -- the mode argument to io.open (default "w+b"). @@ -298,8 +295,7 @@ else: ) -> IO[Any]: ... class _TemporaryFileWrapper(IO[AnyStr]): - """ - Temporary file wrapper + """Temporary file wrapper This class provides a wrapper around files opened for temporary use. In particular, it seeks to automatically @@ -318,9 +314,7 @@ class _TemporaryFileWrapper(IO[AnyStr]): def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ... def __getattr__(self, name: str) -> Any: ... def close(self) -> None: - """ - Close the temporary file, possibly deleting it. - """ + """Close the temporary file, possibly deleting it.""" # These methods don't exist directly on this object, but # are delegated to the underlying IO object through __getattr__. # We need to add them here so that this class is concrete. @@ -369,8 +363,7 @@ else: # It does not actually derive from IO[AnyStr], but it does mostly behave # like one. class SpooledTemporaryFile(IO[AnyStr], _SpooledTemporaryFileBase): - """ - Temporary file wrapper, specialized to switch from BytesIO + """Temporary file wrapper, specialized to switch from BytesIO or StringIO to a real file when it exceeds a certain size or when a fileno is needed. """ @@ -499,20 +492,16 @@ class SpooledTemporaryFile(IO[AnyStr], _SpooledTemporaryFileBase): def seekable(self) -> bool: ... def writable(self) -> bool: ... def __next__(self) -> AnyStr: # type: ignore[override] - """ - Implement next(self). - """ + """Implement next(self).""" def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ class TemporaryDirectory(Generic[AnyStr]): - """ - Create and return a temporary directory. This has the same + """Create and return a temporary directory. This has the same behavior as mkdtemp but can be used as a context manager. For example: @@ -587,8 +576,7 @@ class TemporaryDirectory(Generic[AnyStr]): def __enter__(self) -> AnyStr: ... def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ @@ -598,8 +586,7 @@ class TemporaryDirectory(Generic[AnyStr]): def mkstemp( suffix: str | None = None, prefix: str | None = None, dir: StrPath | None = None, text: bool = False ) -> tuple[int, str]: - """ - User-callable function to create and return a unique temporary + """User-callable function to create and return a unique temporary file. The return value is a pair (fd, name) where fd is the file descriptor returned by os.open, and name is the filename. @@ -635,8 +622,7 @@ def mkstemp( # The overloads overlap, but they should still work fine. @overload def mkdtemp(suffix: str | None = None, prefix: str | None = None, dir: StrPath | None = None) -> str: - """ - User-callable function to create and return a unique temporary + """User-callable function to create and return a unique temporary directory. The return value is the pathname of the directory. Arguments are as for mkstemp, except that the 'text' argument is @@ -651,8 +637,7 @@ def mkdtemp(suffix: str | None = None, prefix: str | None = None, dir: StrPath | @overload def mkdtemp(suffix: bytes | None = None, prefix: bytes | None = None, dir: BytesPath | None = None) -> bytes: ... def mktemp(suffix: str = "", prefix: str = "tmp", dir: StrPath | None = None) -> str: - """ - User-callable function to return a unique temporary file name. The + """User-callable function to return a unique temporary file name. The file is not created. Arguments are similar to mkstemp, except that the 'text' argument is @@ -666,21 +651,13 @@ def mktemp(suffix: str = "", prefix: str = "tmp", dir: StrPath | None = None) -> """ def gettempdirb() -> bytes: - """ - Returns tempfile.tempdir as bytes. - """ + """Returns tempfile.tempdir as bytes.""" def gettempprefixb() -> bytes: - """ - The default prefix for temporary directories as bytes. - """ + """The default prefix for temporary directories as bytes.""" def gettempdir() -> str: - """ - Returns tempfile.tempdir as str. - """ + """Returns tempfile.tempdir as str.""" def gettempprefix() -> str: - """ - The default prefix for temporary directories as string. - """ + """The default prefix for temporary directories as string.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/termios.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/termios.pyi index 735301197b..1b537fa184 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/termios.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/termios.pyi @@ -302,8 +302,7 @@ if sys.platform != "win32": NSWTCH: int def tcgetattr(fd: FileDescriptorLike, /) -> _AttrReturn: - """ - Get the tty attributes for file descriptor fd. + """Get the tty attributes for file descriptor fd. Returns a list [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] where cc is a list of the tty special characters (each a string of @@ -314,8 +313,7 @@ if sys.platform != "win32": """ def tcsetattr(fd: FileDescriptorLike, when: int, attributes: _Attr, /) -> None: - """ - Set the tty attributes for file descriptor fd. + """Set the tty attributes for file descriptor fd. The attributes to be set are taken from the attributes argument, which is a list like the one returned by tcgetattr(). The when argument @@ -326,21 +324,17 @@ if sys.platform != "win32": """ def tcsendbreak(fd: FileDescriptorLike, duration: int, /) -> None: - """ - Send a break on file descriptor fd. + """Send a break on file descriptor fd. A zero duration sends a break for 0.25-0.5 seconds; a nonzero duration has a system dependent meaning. """ def tcdrain(fd: FileDescriptorLike, /) -> None: - """ - Wait until all output written to file descriptor fd has been transmitted. - """ + """Wait until all output written to file descriptor fd has been transmitted.""" def tcflush(fd: FileDescriptorLike, queue: int, /) -> None: - """ - Discard queued data on file descriptor fd. + """Discard queued data on file descriptor fd. The queue selector specifies which queue: termios.TCIFLUSH for the input queue, termios.TCOFLUSH for the output queue, or termios.TCIOFLUSH for @@ -348,8 +342,7 @@ if sys.platform != "win32": """ def tcflow(fd: FileDescriptorLike, action: int, /) -> None: - """ - Suspend or resume input or output on file descriptor fd. + """Suspend or resume input or output on file descriptor fd. The action argument can be termios.TCOOFF to suspend output, termios.TCOON to restart output, termios.TCIOFF to suspend input, @@ -357,15 +350,13 @@ if sys.platform != "win32": """ if sys.version_info >= (3, 11): def tcgetwinsize(fd: FileDescriptorLike, /) -> tuple[int, int]: - """ - Get the tty winsize for file descriptor fd. + """Get the tty winsize for file descriptor fd. Returns a tuple (ws_row, ws_col). """ def tcsetwinsize(fd: FileDescriptorLike, winsize: tuple[int, int], /) -> None: - """ - Set the tty winsize for file descriptor fd. + """Set the tty winsize for file descriptor fd. The winsize to be set is taken from the winsize argument, which is a two-item tuple (ws_row, ws_col) like the one returned by tcgetwinsize(). diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/textwrap.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/textwrap.pyi index b45b74b57f..71d877a3c6 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/textwrap.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/textwrap.pyi @@ -8,8 +8,7 @@ from re import Pattern __all__ = ["TextWrapper", "wrap", "fill", "dedent", "indent", "shorten"] class TextWrapper: - """ - Object for wrapping/filling text. The public interface consists of + """Object for wrapping/filling text. The public interface consists of the wrap() and fill() methods; the other methods are just there for subclasses to override in order to tweak the default behaviour. If you want to completely replace the main wrapping algorithm, @@ -95,8 +94,7 @@ class TextWrapper: ) -> None: ... # Private methods *are* part of the documented API for subclasses. def _munge_whitespace(self, text: str) -> str: - """ - _munge_whitespace(text : string) -> string + """_munge_whitespace(text : string) -> string Munge whitespace in text: expand tabs and convert all other whitespace characters to spaces. Eg. " foo\\tbar\\n\\nbaz" @@ -104,8 +102,7 @@ class TextWrapper: """ def _split(self, text: str) -> list[str]: - """ - _split(text : string) -> [string] + """_split(text : string) -> [string] Split the text to wrap into indivisible chunks. Chunks are not quite the same as words; see _wrap_chunks() for full @@ -121,8 +118,7 @@ class TextWrapper: """ def _fix_sentence_endings(self, chunks: list[str]) -> None: - """ - _fix_sentence_endings(chunks : [string]) + """_fix_sentence_endings(chunks : [string]) Correct for sentence endings buried in 'chunks'. Eg. when the original text contains "... foo.\\nBar ...", munge_whitespace() @@ -132,8 +128,7 @@ class TextWrapper: """ def _handle_long_word(self, reversed_chunks: list[str], cur_line: list[str], cur_len: int, width: int) -> None: - """ - _handle_long_word(chunks : [string], + """_handle_long_word(chunks : [string], cur_line : [string], cur_len : int, width : int) @@ -142,8 +137,7 @@ class TextWrapper: """ def _wrap_chunks(self, chunks: list[str]) -> list[str]: - """ - _wrap_chunks(chunks : [string]) -> [string] + """_wrap_chunks(chunks : [string]) -> [string] Wrap a sequence of text chunks and return a list of lines of length 'self.width' or less. (If 'break_long_words' is false, @@ -158,8 +152,7 @@ class TextWrapper: def _split_chunks(self, text: str) -> list[str]: ... def wrap(self, text: str) -> list[str]: - """ - wrap(text : string) -> [string] + """wrap(text : string) -> [string] Reformat the single paragraph in 'text' so it fits in lines of no more than 'self.width' columns, and return a list of wrapped @@ -169,8 +162,7 @@ class TextWrapper: """ def fill(self, text: str) -> str: - """ - fill(text : string) -> string + """fill(text : string) -> string Reformat the single paragraph in 'text' to fit in lines of no more than 'self.width' columns, and return a new string @@ -193,8 +185,7 @@ def wrap( max_lines: int | None = None, placeholder: str = " [...]", ) -> list[str]: - """ - Wrap a single paragraph of text, returning a list of wrapped lines. + """Wrap a single paragraph of text, returning a list of wrapped lines. Reformat the single paragraph in 'text' so it fits in lines of no more than 'width' columns, and return a list of wrapped lines. By @@ -220,8 +211,7 @@ def fill( max_lines: int | None = None, placeholder: str = " [...]", ) -> str: - """ - Fill a single paragraph of text, returning a new string. + """Fill a single paragraph of text, returning a new string. Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire @@ -246,8 +236,7 @@ def shorten( # Omit `max_lines: int = None`, it is forced to 1 here. placeholder: str = " [...]", ) -> str: - """ - Collapse and truncate the given text to fit in the given width. + """Collapse and truncate the given text to fit in the given width. The text first has its whitespace collapsed. If it then fits in the *width*, it is returned as is. Otherwise, as many words @@ -260,8 +249,7 @@ def shorten( """ def dedent(text: str) -> str: - """ - Remove any common leading whitespace from every line in `text`. + """Remove any common leading whitespace from every line in `text`. This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code @@ -275,8 +263,7 @@ def dedent(text: str) -> str: """ def indent(text: str, prefix: str, predicate: Callable[[str], bool] | None = None) -> str: - """ - Adds 'prefix' to the beginning of selected lines in 'text'. + """Adds 'prefix' to the beginning of selected lines in 'text'. If 'predicate' is provided, 'prefix' will only be added to the lines where 'predicate(line)' is True. If 'predicate' is not provided, diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/threading.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/threading.pyi index 96098cd7e1..4c43e8555c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/threading.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/threading.pyi @@ -50,8 +50,7 @@ if sys.version_info >= (3, 12): _profile_hook: ProfileFunction | None def active_count() -> int: - """ - Return the number of Thread objects currently alive. + """Return the number of Thread objects currently alive. The returned count is equal to the length of the list returned by enumerate(). @@ -59,15 +58,13 @@ def active_count() -> int: @deprecated("Use active_count() instead") def activeCount() -> int: - """ - Return the number of Thread objects currently alive. + """Return the number of Thread objects currently alive. This function is deprecated, use active_count() instead. """ def current_thread() -> Thread: - """ - Return the current Thread object, corresponding to the caller's thread of control. + """Return the current Thread object, corresponding to the caller's thread of control. If the caller's thread of control was not created through the threading module, a dummy thread object with limited functionality is returned. @@ -75,15 +72,13 @@ def current_thread() -> Thread: @deprecated("Use current_thread() instead") def currentThread() -> Thread: - """ - Return the current Thread object, corresponding to the caller's thread of control. + """Return the current Thread object, corresponding to the caller's thread of control. This function is deprecated, use current_thread() instead. """ def get_ident() -> int: - """ - Return a non-zero integer that uniquely identifies the current thread + """Return a non-zero integer that uniquely identifies the current thread amongst other threads that exist simultaneously. This may be used to identify per-thread resources. Even though on some platforms threads identities may appear to be @@ -93,8 +88,7 @@ def get_ident() -> int: """ def enumerate() -> list[Thread]: - """ - Return a list of all Thread objects currently alive. + """Return a list of all Thread objects currently alive. The list includes daemonic threads, dummy thread objects created by current_thread(), and the main thread. It excludes terminated threads and @@ -102,24 +96,21 @@ def enumerate() -> list[Thread]: """ def main_thread() -> Thread: - """ - Return the main thread object. + """Return the main thread object. In normal conditions, the main thread is the thread from which the Python interpreter was started. """ def settrace(func: TraceFunction) -> None: - """ - Set a trace function for all threads started from the threading module. + """Set a trace function for all threads started from the threading module. The func will be passed to sys.settrace() for each thread, before its run() method is called. """ def setprofile(func: ProfileFunction | None) -> None: - """ - Set a profile function for all threads started from the threading module. + """Set a profile function for all threads started from the threading module. The func will be passed to sys.setprofile() for each thread, before its run() method is called. @@ -127,8 +118,7 @@ def setprofile(func: ProfileFunction | None) -> None: if sys.version_info >= (3, 12): def setprofile_all_threads(func: ProfileFunction | None) -> None: - """ - Set a profile function for all threads started from the threading module + """Set a profile function for all threads started from the threading module and all Python threads that are currently executing. The func will be passed to sys.setprofile() for each thread, before its @@ -136,8 +126,7 @@ if sys.version_info >= (3, 12): """ def settrace_all_threads(func: TraceFunction) -> None: - """ - Set a trace function for all threads started from the threading module + """Set a trace function for all threads started from the threading module and all Python threads that are currently executing. The func will be passed to sys.settrace() for each thread, before its run() @@ -146,18 +135,13 @@ if sys.version_info >= (3, 12): if sys.version_info >= (3, 10): def gettrace() -> TraceFunction | None: - """ - Get the trace function as set by threading.settrace(). - """ + """Get the trace function as set by threading.settrace().""" def getprofile() -> ProfileFunction | None: - """ - Get the profiler function as set by threading.setprofile(). - """ + """Get the profiler function as set by threading.setprofile().""" def stack_size(size: int = 0, /) -> int: - """ - Return the thread stack size used when creating new threads. The + """Return the thread stack size used when creating new threads. The optional size argument specifies the stack size (in bytes) to be used for subsequently created threads, and must be 0 (use platform or configured default) or a positive integer value of at least 32,768 (32k). @@ -181,8 +165,7 @@ ThreadError = _thread.error local = _thread._local class Thread: - """ - A class that represents a thread of control. + """A class that represents a thread of control. This class can be safely subclassed in a limited fashion. There are two ways to specify the activity: by passing a callable object to the constructor, or @@ -192,8 +175,7 @@ class Thread: name: str @property def ident(self) -> int | None: - """ - Thread identifier of this thread or None if it has not been started. + """Thread identifier of this thread or None if it has not been started. This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is @@ -212,8 +194,7 @@ class Thread: daemon: bool | None = None, context: ContextVar[Any] | None = None, ) -> None: - """ - This constructor should always be called with keyword arguments. Arguments are: + """This constructor should always be called with keyword arguments. Arguments are: *group* should be None; reserved for future extension when a ThreadGroup class is implemented. @@ -252,8 +233,7 @@ class Thread: *, daemon: bool | None = None, ) -> None: - """ - This constructor should always be called with keyword arguments. Arguments are: + """This constructor should always be called with keyword arguments. Arguments are: *group* should be None; reserved for future extension when a ThreadGroup class is implemented. @@ -283,8 +263,7 @@ class Thread: """ def start(self) -> None: - """ - Start the thread's activity. + """Start the thread's activity. It must be called at most once per thread object. It arranges for the object's run() method to be invoked in a separate thread of control. @@ -294,8 +273,7 @@ class Thread: """ def run(self) -> None: - """ - Method representing the thread's activity. + """Method representing the thread's activity. You may override this method in a subclass. The standard run() method invokes the callable object passed to the object's constructor as the @@ -304,8 +282,7 @@ class Thread: """ def join(self, timeout: float | None = None) -> None: - """ - Wait until the thread terminates. + """Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates -- either normally or through an unhandled exception @@ -330,16 +307,14 @@ class Thread: @property def native_id(self) -> int | None: # only available on some platforms - """ - Native integral thread ID of this thread, or None if it has not been started. + """Native integral thread ID of this thread, or None if it has not been started. This is a non-negative integer. See the get_native_id() function. This represents the Thread ID as reported by the kernel. """ def is_alive(self) -> bool: - """ - Return whether the thread is alive. + """Return whether the thread is alive. This method returns True just before the run() method starts until just after the run() method terminates. See also the module function @@ -348,32 +323,28 @@ class Thread: @deprecated("Get the daemon attribute instead") def isDaemon(self) -> bool: - """ - Return whether this thread is a daemon. + """Return whether this thread is a daemon. This method is deprecated, use the daemon attribute instead. """ @deprecated("Set the daemon attribute instead") def setDaemon(self, daemonic: bool) -> None: - """ - Set whether this thread is a daemon. + """Set whether this thread is a daemon. This method is deprecated, use the .daemon property instead. """ @deprecated("Use the name attribute instead") def getName(self) -> str: - """ - Return a string used for identification purposes only. + """Return a string used for identification purposes only. This method is deprecated, use the name attribute instead. """ @deprecated("Use the name attribute instead") def setName(self, name: str) -> None: - """ - Set the name string for this thread. + """Set the name string for this thread. This method is deprecated, use the name attribute instead. """ @@ -387,8 +358,7 @@ Lock = _thread.LockType # Python implementation of RLock. @final class _RLock: - """ - This class implements reentrant lock objects. + """This class implements reentrant lock objects. A reentrant lock must be released by the thread that acquired it. Once a thread has acquired a reentrant lock, the same thread may acquire it @@ -398,8 +368,7 @@ class _RLock: _count: int def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: - """ - Acquire a lock, blocking or non-blocking. + """Acquire a lock, blocking or non-blocking. When invoked without arguments: if this thread already owns the lock, increment the recursion level by one, and return immediately. Otherwise, @@ -425,8 +394,7 @@ class _RLock: """ def release(self) -> None: - """ - Release a lock, decrementing the recursion level. + """Release a lock, decrementing the recursion level. If after the decrement it is zero, reset the lock to unlocked (not owned by any thread), and if any other threads are blocked waiting for the @@ -445,15 +413,12 @@ class _RLock: if sys.version_info >= (3, 14): def locked(self) -> bool: - """ - Return whether this object is locked. - """ + """Return whether this object is locked.""" RLock = _thread.RLock # Actually a function at runtime. class Condition: - """ - Class that implements a condition variable. + """Class that implements a condition variable. A condition variable allows one or more threads to wait until they are notified by another thread. @@ -471,8 +436,7 @@ class Condition: def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... def wait(self, timeout: float | None = None) -> bool: - """ - Wait until notified or until a timeout occurs. + """Wait until notified or until a timeout occurs. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. @@ -495,8 +459,7 @@ class Condition: """ def wait_for(self, predicate: Callable[[], _T], timeout: float | None = None) -> _T: - """ - Wait until a condition evaluates to True. + """Wait until a condition evaluates to True. predicate should be a callable which result will be interpreted as a boolean value. A timeout may be provided giving the maximum time to @@ -504,8 +467,7 @@ class Condition: """ def notify(self, n: int = 1) -> None: - """ - Wake up one or more threads waiting on this condition, if any. + """Wake up one or more threads waiting on this condition, if any. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. @@ -515,8 +477,7 @@ class Condition: """ def notify_all(self) -> None: - """ - Wake up all threads waiting on this condition. + """Wake up all threads waiting on this condition. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. @@ -524,15 +485,13 @@ class Condition: @deprecated("Use notify_all() instead") def notifyAll(self) -> None: - """ - Wake up all threads waiting on this condition. + """Wake up all threads waiting on this condition. This method is deprecated, use notify_all() instead. """ class Semaphore: - """ - This class implements semaphore objects. + """This class implements semaphore objects. Semaphores manage a counter representing the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method @@ -544,8 +503,7 @@ class Semaphore: def __init__(self, value: int = 1) -> None: ... def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... def acquire(self, blocking: bool = True, timeout: float | None = None) -> bool: - """ - Acquire a semaphore, decrementing the internal counter by one. + """Acquire a semaphore, decrementing the internal counter by one. When invoked without arguments: if the internal counter is larger than zero on entry, decrement it by one and return immediately. If it is zero @@ -569,8 +527,7 @@ class Semaphore: """ def __enter__(self, blocking: bool = True, timeout: float | None = None) -> bool: - """ - Acquire a semaphore, decrementing the internal counter by one. + """Acquire a semaphore, decrementing the internal counter by one. When invoked without arguments: if the internal counter is larger than zero on entry, decrement it by one and return immediately. If it is zero @@ -594,16 +551,14 @@ class Semaphore: """ def release(self, n: int = 1) -> None: - """ - Release a semaphore, incrementing the internal counter by one or more. + """Release a semaphore, incrementing the internal counter by one or more. When the counter is zero on entry and another thread is waiting for it to become larger than zero again, wake up that thread. """ class BoundedSemaphore(Semaphore): - """ - Implements a bounded semaphore. + """Implements a bounded semaphore. A bounded semaphore checks to make sure its current value doesn't exceed its initial value. If it does, ValueError is raised. In most situations @@ -619,8 +574,7 @@ class BoundedSemaphore(Semaphore): """ class Event: - """ - Class implementing event objects. + """Class implementing event objects. Events manage a flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is @@ -628,37 +582,31 @@ class Event: """ def is_set(self) -> bool: - """ - Return true if and only if the internal flag is true. - """ + """Return true if and only if the internal flag is true.""" @deprecated("Use is_set() instead") def isSet(self) -> bool: - """ - Return true if and only if the internal flag is true. + """Return true if and only if the internal flag is true. This method is deprecated, use is_set() instead. """ def set(self) -> None: - """ - Set the internal flag to true. + """Set the internal flag to true. All threads waiting for it to become true are awakened. Threads that call wait() once the flag is true will not block at all. """ def clear(self) -> None: - """ - Reset the internal flag to false. + """Reset the internal flag to false. Subsequently, threads calling wait() will block until set() is called to set the internal flag to true again. """ def wait(self, timeout: float | None = None) -> bool: - """ - Block until the internal flag is true. + """Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until @@ -676,8 +624,7 @@ excepthook = _excepthook ExceptHookArgs = _ExceptHookArgs class Timer(Thread): - """ - Call a function after a specified number of seconds: + """Call a function after a specified number of seconds: t = Timer(30.0, f, args=None, kwargs=None) t.start() @@ -698,13 +645,10 @@ class Timer(Thread): kwargs: Mapping[str, Any] | None = None, ) -> None: ... def cancel(self) -> None: - """ - Stop the timer if it hasn't finished yet. - """ + """Stop the timer if it hasn't finished yet.""" class Barrier: - """ - Implements a Barrier. + """Implements a Barrier. Useful for synchronizing a fixed number of threads at known synchronization points. Threads block on 'wait()' and are simultaneously awoken once they @@ -713,25 +657,18 @@ class Barrier: @property def parties(self) -> int: - """ - Return the number of threads required to trip the barrier. - """ + """Return the number of threads required to trip the barrier.""" @property def n_waiting(self) -> int: - """ - Return the number of threads currently waiting at the barrier. - """ + """Return the number of threads currently waiting at the barrier.""" @property def broken(self) -> bool: - """ - Return True if the barrier is in a broken state. - """ + """Return True if the barrier is in a broken state.""" def __init__(self, parties: int, action: Callable[[], None] | None = None, timeout: float | None = None) -> None: - """ - Create a barrier, initialised to 'parties' threads. + """Create a barrier, initialised to 'parties' threads. 'action' is a callable which, when supplied, will be called by one of the threads after they have all entered the barrier and just prior to @@ -740,8 +677,7 @@ class Barrier: """ def wait(self, timeout: float | None = None) -> int: - """ - Wait for the barrier. + """Wait for the barrier. When the specified number of threads have started waiting, they are all simultaneously awoken. If an 'action' was provided for the barrier, one @@ -750,16 +686,14 @@ class Barrier: """ def reset(self) -> None: - """ - Reset the barrier to the initial state. + """Reset the barrier to the initial state. Any threads currently waiting will get the BrokenBarrier exception raised. """ def abort(self) -> None: - """ - Place the barrier into a 'broken' state. + """Place the barrier into a 'broken' state. Useful in case of error. Any currently waiting threads and threads attempting to 'wait()' will have BrokenBarrierError raised. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/time.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/time.pyi index 7b61315512..b9b45175f6 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/time.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/time.pyi @@ -65,8 +65,7 @@ if sys.platform == "linux": # https://github.com/python/typeshed/pull/6560#discussion_r767162532 @final class struct_time(structseq[Any | int], _TimeTuple): - """ - The time value as returned by gmtime(), localtime(), and strptime(), and + """The time value as returned by gmtime(), localtime(), and strptime(), and accepted by asctime(), mktime() and strftime(). May be considered as a sequence of 9 integers. @@ -81,73 +80,50 @@ class struct_time(structseq[Any | int], _TimeTuple): @property def tm_year(self) -> int: - """ - year, for example, 1993 - """ + """year, for example, 1993""" @property def tm_mon(self) -> int: - """ - month of year, range [1, 12] - """ + """month of year, range [1, 12]""" @property def tm_mday(self) -> int: - """ - day of month, range [1, 31] - """ + """day of month, range [1, 31]""" @property def tm_hour(self) -> int: - """ - hours, range [0, 23] - """ + """hours, range [0, 23]""" @property def tm_min(self) -> int: - """ - minutes, range [0, 59] - """ + """minutes, range [0, 59]""" @property def tm_sec(self) -> int: - """ - seconds, range [0, 61]) - """ + """seconds, range [0, 61])""" @property def tm_wday(self) -> int: - """ - day of week, range [0, 6], Monday is 0 - """ + """day of week, range [0, 6], Monday is 0""" @property def tm_yday(self) -> int: - """ - day of year, range [1, 366] - """ + """day of year, range [1, 366]""" @property def tm_isdst(self) -> int: - """ - 1 if summer time is in effect, 0 if not, and -1 if unknown - """ + """1 if summer time is in effect, 0 if not, and -1 if unknown""" # These final two properties only exist if a 10- or 11-item sequence was passed to the constructor. @property def tm_zone(self) -> str: - """ - abbreviation of timezone name - """ + """abbreviation of timezone name""" @property def tm_gmtoff(self) -> int: - """ - offset from UTC in seconds - """ + """offset from UTC in seconds""" def asctime(time_tuple: _TimeTuple | struct_time = ..., /) -> str: - """ - asctime([tuple]) -> string + """asctime([tuple]) -> string Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'. When the time tuple is not present, current time as returned by localtime() @@ -155,8 +131,7 @@ def asctime(time_tuple: _TimeTuple | struct_time = ..., /) -> str: """ def ctime(seconds: float | None = None, /) -> str: - """ - ctime(seconds) -> string + """ctime(seconds) -> string Convert a time in seconds since the Epoch to a string in local time. This is equivalent to asctime(localtime(seconds)). When the time tuple is @@ -164,8 +139,7 @@ def ctime(seconds: float | None = None, /) -> str: """ def gmtime(seconds: float | None = None, /) -> struct_time: - """ - gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min, + """gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst) Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a. @@ -176,8 +150,7 @@ def gmtime(seconds: float | None = None, /) -> struct_time: """ def localtime(seconds: float | None = None, /) -> struct_time: - """ - localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min, + """localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min, tm_sec,tm_wday,tm_yday,tm_isdst) Convert seconds since the Epoch to a time tuple expressing local time. @@ -185,8 +158,7 @@ def localtime(seconds: float | None = None, /) -> struct_time: """ def mktime(time_tuple: _TimeTuple | struct_time, /) -> float: - """ - mktime(tuple) -> floating-point number + """mktime(tuple) -> floating-point number Convert a time tuple in local time to seconds since the Epoch. Note that mktime(gmtime(0)) will not generally return zero for most @@ -195,16 +167,14 @@ def mktime(time_tuple: _TimeTuple | struct_time, /) -> float: """ def sleep(seconds: float, /) -> None: - """ - sleep(seconds) + """sleep(seconds) Delay execution for a given number of seconds. The argument may be a floating-point number for subsecond precision. """ def strftime(format: str, time_tuple: _TimeTuple | struct_time = ..., /) -> str: - """ - strftime(format[, tuple]) -> string + """strftime(format[, tuple]) -> string Convert a time tuple to a string according to a format specification. See the library reference manual for formatting codes. When the time tuple @@ -232,8 +202,7 @@ def strftime(format: str, time_tuple: _TimeTuple | struct_time = ..., /) -> str: """ def strptime(data_string: str, format: str = "%a %b %d %H:%M:%S %Y", /) -> struct_time: - """ - strptime(string, format) -> struct_time + """strptime(string, format) -> struct_time Parse a string to a time tuple according to a format specification. See the library reference manual for formatting codes (same as @@ -261,8 +230,7 @@ def strptime(data_string: str, format: str = "%a %b %d %H:%M:%S %Y", /) -> struc """ def time() -> float: - """ - time() -> floating-point number + """time() -> floating-point number Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them. @@ -270,8 +238,7 @@ def time() -> float: if sys.platform != "win32": def tzset() -> None: # Unix only - """ - tzset() + """tzset() Initialize, or reinitialize, the local timezone to the value stored in os.environ['TZ']. The TZ environment variable should be specified in @@ -291,113 +258,95 @@ class _ClockInfo(Protocol): resolution: float def get_clock_info(name: Literal["monotonic", "perf_counter", "process_time", "time", "thread_time"], /) -> _ClockInfo: - """ - get_clock_info(name: str) -> dict + """get_clock_info(name: str) -> dict Get information of the specified clock. """ def monotonic() -> float: - """ - monotonic() -> float + """monotonic() -> float Monotonic clock, cannot go backward. """ def perf_counter() -> float: - """ - perf_counter() -> float + """perf_counter() -> float Performance counter for benchmarking. """ def process_time() -> float: - """ - process_time() -> float + """process_time() -> float Process time for profiling: sum of the kernel and user-space CPU time. """ if sys.platform != "win32": def clock_getres(clk_id: int, /) -> float: # Unix only - """ - clock_getres(clk_id) -> floating-point number + """clock_getres(clk_id) -> floating-point number Return the resolution (precision) of the specified clock clk_id. """ def clock_gettime(clk_id: int, /) -> float: # Unix only - """ - Return the time of the specified clock clk_id as a float. - """ + """Return the time of the specified clock clk_id as a float.""" def clock_settime(clk_id: int, time: float, /) -> None: # Unix only - """ - clock_settime(clk_id, time) + """clock_settime(clk_id, time) Set the time of the specified clock clk_id. """ if sys.platform != "win32": def clock_gettime_ns(clk_id: int, /) -> int: - """ - Return the time of the specified clock clk_id as nanoseconds (int). - """ + """Return the time of the specified clock clk_id as nanoseconds (int).""" def clock_settime_ns(clock_id: int, time: int, /) -> int: - """ - clock_settime_ns(clk_id, time) + """clock_settime_ns(clk_id, time) Set the time of the specified clock clk_id with nanoseconds. """ if sys.platform == "linux": def pthread_getcpuclockid(thread_id: int, /) -> int: - """ - pthread_getcpuclockid(thread_id) -> int + """pthread_getcpuclockid(thread_id) -> int Return the clk_id of a thread's CPU time clock. """ def monotonic_ns() -> int: - """ - monotonic_ns() -> int + """monotonic_ns() -> int Monotonic clock, cannot go backward, as nanoseconds. """ def perf_counter_ns() -> int: - """ - perf_counter_ns() -> int + """perf_counter_ns() -> int Performance counter for benchmarking as nanoseconds. """ def process_time_ns() -> int: - """ - process_time() -> int + """process_time() -> int Process time for profiling as nanoseconds: sum of the kernel and user-space CPU time. """ def time_ns() -> int: - """ - time_ns() -> int + """time_ns() -> int Return the current time in nanoseconds since the Epoch. """ def thread_time() -> float: - """ - thread_time() -> float + """thread_time() -> float Thread time for profiling: sum of the kernel and user-space CPU time. """ def thread_time_ns() -> int: - """ - thread_time() -> int + """thread_time() -> int Thread time for profiling as nanoseconds: sum of the kernel and user-space CPU time. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/timeit.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/timeit.pyi index e9a21f1465..93d8a10335 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/timeit.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/timeit.pyi @@ -59,8 +59,7 @@ _Stmt: TypeAlias = str | Callable[[], object] default_timer: _Timer class Timer: - """ - Class for timing execution speed of small code snippets. + """Class for timing execution speed of small code snippets. The constructor takes a statement to be timed, an additional statement used for setup, and a timer function. Both statements @@ -80,13 +79,10 @@ class Timer: def __init__( self, stmt: _Stmt = "pass", setup: _Stmt = "pass", timer: _Timer = ..., globals: dict[str, Any] | None = None ) -> None: - """ - Constructor. See class doc string. - """ + """Constructor. See class doc string.""" def print_exc(self, file: IO[str] | None = None) -> None: - """ - Helper to print a traceback from the timed code. + """Helper to print a traceback from the timed code. Typical use: @@ -104,8 +100,7 @@ class Timer: """ def timeit(self, number: int = 1000000) -> float: - """ - Time 'number' executions of the main statement. + """Time 'number' executions of the main statement. To be precise, this executes the setup statement once, and then returns the time it takes to execute the main statement @@ -116,8 +111,7 @@ class Timer: """ def repeat(self, repeat: int = 5, number: int = 1000000) -> list[float]: - """ - Call timeit() a few times. + """Call timeit() a few times. This is a convenience function that calls the timeit() repeatedly, returning a list of results. The first argument @@ -138,8 +132,7 @@ class Timer: """ def autorange(self, callback: Callable[[int, float], object] | None = None) -> tuple[int, float]: - """ - Return the number of loops and time taken so that total time >= 0.2. + """Return the number of loops and time taken so that total time >= 0.2. Calls the timeit method with increasing numbers from the sequence 1, 2, 5, 10, 20, 50, ... until the time taken is at least 0.2 @@ -152,9 +145,7 @@ class Timer: def timeit( stmt: _Stmt = "pass", setup: _Stmt = "pass", timer: _Timer = ..., number: int = 1000000, globals: dict[str, Any] | None = None ) -> float: - """ - Convenience function to create Timer object and call timeit method. - """ + """Convenience function to create Timer object and call timeit method.""" def repeat( stmt: _Stmt = "pass", @@ -164,13 +155,10 @@ def repeat( number: int = 1000000, globals: dict[str, Any] | None = None, ) -> list[float]: - """ - Convenience function to create Timer object and call repeat method. - """ + """Convenience function to create Timer object and call repeat method.""" def main(args: Sequence[str] | None = None, *, _wrap_timer: Callable[[_Timer], _Timer] | None = None) -> None: - """ - Main program, used when run as a script. + """Main program, used when run as a script. The optional 'args' argument specifies the command line to be parsed, defaulting to sys.argv[1:]. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/__init__.pyi index b8af851744..fc35af7267 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/__init__.pyi @@ -235,9 +235,7 @@ if sys.version_info >= (3, 11): if sys.version_info >= (3, 11): class EventType(StrEnum): - """ - An enumeration. - """ + """An enumeration.""" Activate = "36" ButtonPress = "4" @@ -281,9 +279,7 @@ if sys.version_info >= (3, 11): else: class EventType(str, Enum): - """ - An enumeration. - """ + """An enumeration.""" Activate = "36" ButtonPress = "4" @@ -330,8 +326,7 @@ _W = TypeVar("_W", bound=Misc) _W_co = TypeVar("_W_co", covariant=True, bound=Misc, default=Misc) class Event(Generic[_W_co]): - """ - Container for the properties of an event. + """Container for the properties of an event. Instances of this type are generated if one of the following events occurs: @@ -394,31 +389,27 @@ class Event(Generic[_W_co]): delta: int if sys.version_info >= (3, 14): def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ def NoDefaultRoot() -> None: - """ - Inhibit setting of default root window. + """Inhibit setting of default root window. Call this function to inhibit that the first instance of Tk is used for windows without an explicit parent window. """ class Variable: - """ - Class to define value holders for e.g. buttons. + """Class to define value holders for e.g. buttons. Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations that constrain the type of the value returned from get(). """ def __init__(self, master: Misc | None = None, value=None, name: str | None = None) -> None: - """ - Construct a variable + """Construct a variable MASTER can be given as master widget. VALUE is an optional value (defaults to "") @@ -429,18 +420,13 @@ class Variable: """ def set(self, value) -> None: - """ - Set the variable to VALUE. - """ + """Set the variable to VALUE.""" initialize = set def get(self): - """ - Return value of variable. - """ + """Return value of variable.""" def trace_add(self, mode: Literal["array", "read", "write", "unset"], callback: Callable[[str, str, str], object]) -> str: - """ - Define a trace callback for the variable. + """Define a trace callback for the variable. Mode is one of "read", "write", "unset", or a list or tuple of such strings. @@ -451,8 +437,7 @@ class Variable: """ def trace_remove(self, mode: Literal["array", "read", "write", "unset"], cbname: str) -> None: - """ - Delete the trace callback for a variable. + """Delete the trace callback for a variable. Mode is one of "read", "write", "unset" or a list or tuple of such strings. Must be same as were specified in trace_add(). @@ -460,14 +445,11 @@ class Variable: """ def trace_info(self) -> list[tuple[tuple[Literal["array", "read", "write", "unset"], ...], str]]: - """ - Return all trace callback information. - """ + """Return all trace callback information.""" @deprecated("use trace_add() instead of trace()") def trace(self, mode, callback): - """ - Define a trace callback for the variable. + """Define a trace callback for the variable. MODE is one of "r", "w", "u" for read, write, undefine. CALLBACK must be a function which is called when @@ -481,8 +463,7 @@ class Variable: @deprecated("use trace_add() instead of trace_variable()") def trace_variable(self, mode, callback): - """ - Define a trace callback for the variable. + """Define a trace callback for the variable. MODE is one of "r", "w", "u" for read, write, undefine. CALLBACK must be a function which is called when @@ -496,8 +477,7 @@ class Variable: @deprecated("use trace_remove() instead of trace_vdelete()") def trace_vdelete(self, mode, cbname) -> None: - """ - Delete the trace callback for a variable. + """Delete the trace callback for a variable. MODE is one of "r", "w", "u" for read, write, undefine. CBNAME is the name of the callback returned from trace_variable or trace. @@ -508,8 +488,7 @@ class Variable: @deprecated("use trace_info() instead of trace_vinfo()") def trace_vinfo(self): - """ - Return all trace callback information. + """Return all trace callback information. This deprecated method wraps a deprecated Tcl method removed in Tcl 9.0. Use trace_info() instead. @@ -517,19 +496,14 @@ class Variable: def __eq__(self, other: object) -> bool: ... def __del__(self) -> None: - """ - Unset the variable in Tcl. - """ + """Unset the variable in Tcl.""" __hash__: ClassVar[None] # type: ignore[assignment] class StringVar(Variable): - """ - Value holder for strings variables. - """ + """Value holder for strings variables.""" def __init__(self, master: Misc | None = None, value: str | None = None, name: str | None = None) -> None: - """ - Construct a string variable. + """Construct a string variable. MASTER can be given as master widget. VALUE is an optional value (defaults to "") @@ -540,23 +514,16 @@ class StringVar(Variable): """ def set(self, value: str) -> None: - """ - Set the variable to VALUE. - """ + """Set the variable to VALUE.""" initialize = set def get(self) -> str: - """ - Return value of variable as string. - """ + """Return value of variable as string.""" class IntVar(Variable): - """ - Value holder for integer variables. - """ + """Value holder for integer variables.""" def __init__(self, master: Misc | None = None, value: int | None = None, name: str | None = None) -> None: - """ - Construct an integer variable. + """Construct an integer variable. MASTER can be given as master widget. VALUE is an optional value (defaults to 0) @@ -567,23 +534,16 @@ class IntVar(Variable): """ def set(self, value: int) -> None: - """ - Set the variable to VALUE. - """ + """Set the variable to VALUE.""" initialize = set def get(self) -> int: - """ - Return the value of the variable as an integer. - """ + """Return the value of the variable as an integer.""" class DoubleVar(Variable): - """ - Value holder for float variables. - """ + """Value holder for float variables.""" def __init__(self, master: Misc | None = None, value: float | None = None, name: str | None = None) -> None: - """ - Construct a float variable. + """Construct a float variable. MASTER can be given as master widget. VALUE is an optional value (defaults to 0.0) @@ -594,23 +554,16 @@ class DoubleVar(Variable): """ def set(self, value: float) -> None: - """ - Set the variable to VALUE. - """ + """Set the variable to VALUE.""" initialize = set def get(self) -> float: - """ - Return the value of the variable as a float. - """ + """Return the value of the variable as a float.""" class BooleanVar(Variable): - """ - Value holder for boolean variables. - """ + """Value holder for boolean variables.""" def __init__(self, master: Misc | None = None, value: bool | None = None, name: str | None = None) -> None: - """ - Construct a boolean variable. + """Construct a boolean variable. MASTER can be given as master widget. VALUE is an optional value (defaults to False) @@ -621,27 +574,19 @@ class BooleanVar(Variable): """ def set(self, value: bool) -> None: - """ - Set the variable to VALUE. - """ + """Set the variable to VALUE.""" initialize = set def get(self) -> bool: - """ - Return the value of the variable as a bool. - """ + """Return the value of the variable as a bool.""" def mainloop(n: int = 0) -> None: - """ - Run the main loop of Tcl. - """ + """Run the main loop of Tcl.""" getint: Incomplete getdouble: Incomplete def getboolean(s): - """ - Convert Tcl object to True or False. - """ + """Convert Tcl object to True or False.""" _Ts = TypeVarTuple("_Ts") @@ -655,8 +600,7 @@ class _BusyInfo(TypedDict): cursor: _Cursor class Misc: - """ - Internal class. + """Internal class. Base class which defines methods common for interior widgets. """ @@ -665,23 +609,20 @@ class Misc: tk: _tkinter.TkappType children: dict[str, Widget] def destroy(self) -> None: - """ - Internal function. + """Internal function. Delete all Tcl commands created for this widget in the Tcl interpreter. """ def deletecommand(self, name: str) -> None: - """ - Internal function. + """Internal function. Delete the Tcl command provided in NAME. """ def tk_strictMotif(self, boolean=None): - """ - Set Tcl internal variable, whether the look and feel + """Set Tcl internal variable, whether the look and feel should adhere to Motif. A parameter of 1 means adhere to Motif (e.g. no color @@ -690,13 +631,10 @@ class Misc: """ def tk_bisque(self) -> None: - """ - Change the color scheme to light brown as used in Tk 3.6 and before. - """ + """Change the color scheme to light brown as used in Tk 3.6 and before.""" def tk_setPalette(self, *args, **kw) -> None: - """ - Set a new color scheme for all widget elements. + """Set a new color scheme for all widget elements. A single color as argument will cause that all colors of Tk widget elements are derived from this. @@ -709,48 +647,38 @@ class Misc: """ def wait_variable(self, name: str | Variable = "PY_VAR") -> None: - """ - Wait until the variable is modified. + """Wait until the variable is modified. A parameter of type IntVar, StringVar, DoubleVar or BooleanVar must be given. """ waitvar = wait_variable def wait_window(self, window: Misc | None = None) -> None: - """ - Wait until a WIDGET is destroyed. + """Wait until a WIDGET is destroyed. If no parameter is given self is used. """ def wait_visibility(self, window: Misc | None = None) -> None: - """ - Wait until the visibility of a WIDGET changes + """Wait until the visibility of a WIDGET changes (e.g. it appears). If no parameter is given self is used. """ def setvar(self, name: str = "PY_VAR", value: str = "1") -> None: - """ - Set Tcl variable NAME to VALUE. - """ + """Set Tcl variable NAME to VALUE.""" def getvar(self, name: str = "PY_VAR"): - """ - Return value of Tcl variable NAME. - """ + """Return value of Tcl variable NAME.""" def getint(self, s): ... def getdouble(self, s): ... def getboolean(self, s): - """ - Return a boolean value for Tcl boolean values true and false given as parameter. - """ + """Return a boolean value for Tcl boolean values true and false given as parameter.""" def focus_set(self) -> None: - """ - Direct input focus to this widget. + """Direct input focus to this widget. If the application currently does not have the focus this widget will get the focus if the application gets @@ -758,15 +686,13 @@ class Misc: """ focus = focus_set def focus_force(self) -> None: - """ - Direct input focus to this widget even if the + """Direct input focus to this widget even if the application does not have the focus. Use with caution! """ def focus_get(self) -> Misc | None: - """ - Return the widget which has currently the focus in the + """Return the widget which has currently the focus in the application. Use focus_displayof to allow working with several @@ -775,28 +701,24 @@ class Misc: """ def focus_displayof(self) -> Misc | None: - """ - Return the widget which has currently the focus on the + """Return the widget which has currently the focus on the display where this widget is located. Return None if the application does not have the focus. """ def focus_lastfor(self) -> Misc | None: - """ - Return the widget which would have the focus if top level + """Return the widget which would have the focus if top level for this widget gets the focus from the window manager. """ def tk_focusFollowsMouse(self) -> None: - """ - The widget under mouse will get automatically focus. Can not + """The widget under mouse will get automatically focus. Can not be disabled easily. """ def tk_focusNext(self) -> Misc | None: - """ - Return the next widget in the focus order which follows + """Return the next widget in the focus order which follows widget which has currently the focus. The focus order first goes to the next child, then to @@ -807,14 +729,11 @@ class Misc: """ def tk_focusPrev(self) -> Misc | None: - """ - Return previous widget in the focus order. See tk_focusNext for details. - """ + """Return previous widget in the focus order. See tk_focusNext for details.""" # .after() can be called without the "func" argument, but it is basically never what you want. # It behaves like time.sleep() and freezes the GUI app. def after(self, ms: int | Literal["idle"], func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> str: - """ - Call function once after given time. + """Call function once after given time. MS specifies the time in milliseconds. FUNC gives the function which shall be called. Additional parameters @@ -823,8 +742,7 @@ class Misc: """ # after_idle is essentially partialmethod(after, "idle") def after_idle(self, func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> str: - """ - Call FUNC once if the Tcl main loop has no event to + """Call FUNC once if the Tcl main loop has no event to process. Return an identifier to cancel the scheduling with @@ -832,16 +750,14 @@ class Misc: """ def after_cancel(self, id: str) -> None: - """ - Cancel scheduling of function identified with ID. + """Cancel scheduling of function identified with ID. Identifier returned by after or after_idle must be given as first parameter. """ if sys.version_info >= (3, 13): def after_info(self, id: str | None = None) -> tuple[str, ...]: - """ - Return information about existing event handlers. + """Return information about existing event handlers. With no argument, return a tuple of the identifiers for all existing event handlers created by the after and after_idle commands for this @@ -855,14 +771,11 @@ class Misc: """ def bell(self, displayof: Literal[0] | Misc | None = 0) -> None: - """ - Ring a display's bell. - """ + """Ring a display's bell.""" if sys.version_info >= (3, 13): # Supports options from `_BusyInfo`` def tk_busy_cget(self, option: Literal["cursor"]) -> _Cursor: - """ - Return the value of busy configuration option. + """Return the value of busy configuration option. The widget must have been previously made busy by tk_busy_hold(). Option may have any of the values accepted by @@ -870,8 +783,7 @@ class Misc: """ busy_cget = tk_busy_cget def tk_busy_configure(self, cnf: Any = None, **kw: Any) -> Any: - """ - Query or modify the busy configuration options. + """Query or modify the busy configuration options. The widget must have been previously made busy by tk_busy_hold(). Options may have any of the values accepted by @@ -889,23 +801,20 @@ class Misc: busy_configure = tk_busy_configure busy_config = tk_busy_configure def tk_busy_current(self, pattern: str | None = None) -> list[Misc]: - """ - Return a list of widgets that are currently busy. + """Return a list of widgets that are currently busy. If a pattern is given, only busy widgets whose path names match a pattern are returned. """ busy_current = tk_busy_current def tk_busy_forget(self) -> None: - """ - Make this widget no longer busy. + """Make this widget no longer busy. User events will again be received by the widget. """ busy_forget = tk_busy_forget def tk_busy_hold(self, **kw: Unpack[_BusyInfo]) -> None: - """ - Make this widget appear busy. + """Make this widget appear busy. The specified widget and its descendants will be blocked from user interactions. Normally update() should be called @@ -921,14 +830,11 @@ class Misc: busy_hold = tk_busy_hold busy = tk_busy_hold def tk_busy_status(self) -> bool: - """ - Return True if the widget is busy, False otherwise. - """ + """Return True if the widget is busy, False otherwise.""" busy_status = tk_busy_status def clipboard_get(self, *, displayof: Misc = ..., type: str = ...) -> str: - """ - Retrieve data from the clipboard on window's display. + """Retrieve data from the clipboard on window's display. The window keyword defaults to the root window of the Tkinter application. @@ -944,16 +850,14 @@ class Misc: """ def clipboard_clear(self, *, displayof: Misc = ...) -> None: - """ - Clear the data in the Tk clipboard. + """Clear the data in the Tk clipboard. A widget specified for the optional displayof keyword argument specifies the target display. """ def clipboard_append(self, string: str, *, displayof: Misc = ..., format: str = ..., type: str = ...) -> None: - """ - Append STRING to the Tk clipboard. + """Append STRING to the Tk clipboard. A widget specified at the optional displayof keyword argument specifies the target display. The clipboard @@ -961,27 +865,22 @@ class Misc: """ def grab_current(self): - """ - Return widget which has currently the grab in this application + """Return widget which has currently the grab in this application or None. """ def grab_release(self) -> None: - """ - Release grab for this widget if currently set. - """ + """Release grab for this widget if currently set.""" def grab_set(self) -> None: - """ - Set grab for this widget. + """Set grab for this widget. A grab directs all events to this and descendant widgets in the application. """ def grab_set_global(self) -> None: - """ - Set global grab for this widget. + """Set global grab for this widget. A global grab directs all events to this and descendant widgets on the display. Use with caution - @@ -989,16 +888,14 @@ class Misc: """ def grab_status(self) -> Literal["local", "global"] | None: - """ - Return None, "local" or "global" if this widget has + """Return None, "local" or "global" if this widget has no, a local or a global grab. """ def option_add( self, pattern, value, priority: int | Literal["widgetDefault", "startupFile", "userDefault", "interactive"] | None = None ) -> None: - """ - Set a VALUE (second parameter) for an option + """Set a VALUE (second parameter) for an option PATTERN (first parameter). An optional third parameter gives the numeric priority @@ -1006,36 +903,30 @@ class Misc: """ def option_clear(self) -> None: - """ - Clear the option database. + """Clear the option database. It will be reloaded if option_add is called. """ def option_get(self, name, className): - """ - Return the value for an option NAME for this widget + """Return the value for an option NAME for this widget with CLASSNAME. Values with higher priority override lower values. """ def option_readfile(self, fileName, priority=None) -> None: - """ - Read file FILENAME into the option database. + """Read file FILENAME into the option database. An optional second parameter gives the numeric priority. """ def selection_clear(self, **kw) -> None: - """ - Clear the current X selection. - """ + """Clear the current X selection.""" def selection_get(self, **kw): - """ - Return the contents of the current X selection. + """Return the contents of the current X selection. A keyword parameter selection specifies the name of the selection and defaults to PRIMARY. A keyword @@ -1046,8 +937,7 @@ class Misc: """ def selection_handle(self, command, **kw) -> None: - """ - Specify a function COMMAND to call if the X + """Specify a function COMMAND to call if the X selection owned by this widget is queried by another application. @@ -1061,16 +951,14 @@ class Misc: """ def selection_own(self, **kw) -> None: - """ - Become owner of X selection. + """Become owner of X selection. A keyword parameter selection specifies the name of the selection (default PRIMARY). """ def selection_own_get(self, **kw): - """ - Return owner of X selection. + """Return owner of X selection. The following keyword parameter can be provided: @@ -1079,248 +967,169 @@ class Misc: """ def send(self, interp, cmd, *args): - """ - Send Tcl command CMD to different interpreter INTERP to be executed. - """ + """Send Tcl command CMD to different interpreter INTERP to be executed.""" def lower(self, belowThis=None) -> None: - """ - Lower this widget in the stacking order. - """ + """Lower this widget in the stacking order.""" def tkraise(self, aboveThis=None) -> None: - """ - Raise this widget in the stacking order. - """ + """Raise this widget in the stacking order.""" lift = tkraise if sys.version_info >= (3, 11): def info_patchlevel(self) -> _VersionInfoType: - """ - Returns the exact version of the Tcl library. - """ + """Returns the exact version of the Tcl library.""" def winfo_atom(self, name: str, displayof: Literal[0] | Misc | None = 0) -> int: - """ - Return integer which represents atom NAME. - """ + """Return integer which represents atom NAME.""" def winfo_atomname(self, id: int, displayof: Literal[0] | Misc | None = 0) -> str: - """ - Return name of atom with identifier ID. - """ + """Return name of atom with identifier ID.""" def winfo_cells(self) -> int: - """ - Return number of cells in the colormap for this widget. - """ + """Return number of cells in the colormap for this widget.""" def winfo_children(self) -> list[Widget]: # Widget because it can't be Toplevel or Tk - """ - Return a list of all widgets which are children of this widget. - """ + """Return a list of all widgets which are children of this widget.""" def winfo_class(self) -> str: - """ - Return window class name of this widget. - """ + """Return window class name of this widget.""" def winfo_colormapfull(self) -> bool: - """ - Return True if at the last color request the colormap was full. - """ + """Return True if at the last color request the colormap was full.""" def winfo_containing(self, rootX: int, rootY: int, displayof: Literal[0] | Misc | None = 0) -> Misc | None: - """ - Return the widget which is at the root coordinates ROOTX, ROOTY. - """ + """Return the widget which is at the root coordinates ROOTX, ROOTY.""" def winfo_depth(self) -> int: - """ - Return the number of bits per pixel. - """ + """Return the number of bits per pixel.""" def winfo_exists(self) -> bool: - """ - Return true if this widget exists. - """ + """Return true if this widget exists.""" def winfo_fpixels(self, number: _ScreenUnits) -> float: - """ - Return the number of pixels for the given distance NUMBER + """Return the number of pixels for the given distance NUMBER (e.g. "3c") as float. """ def winfo_geometry(self) -> str: - """ - Return geometry string for this widget in the form "widthxheight+X+Y". - """ + """Return geometry string for this widget in the form "widthxheight+X+Y".""" def winfo_height(self) -> int: - """ - Return height of this widget. - """ + """Return height of this widget.""" def winfo_id(self) -> int: - """ - Return identifier ID for this widget. - """ + """Return identifier ID for this widget.""" def winfo_interps(self, displayof: Literal[0] | Misc | None = 0) -> tuple[str, ...]: - """ - Return the name of all Tcl interpreters for this display. - """ + """Return the name of all Tcl interpreters for this display.""" def winfo_ismapped(self) -> bool: - """ - Return true if this widget is mapped. - """ + """Return true if this widget is mapped.""" def winfo_manager(self) -> str: - """ - Return the window manager name for this widget. - """ + """Return the window manager name for this widget.""" def winfo_name(self) -> str: - """ - Return the name of this widget. - """ + """Return the name of this widget.""" def winfo_parent(self) -> str: # return value needs nametowidget() - """ - Return the name of the parent of this widget. - """ + """Return the name of the parent of this widget.""" def winfo_pathname(self, id: int, displayof: Literal[0] | Misc | None = 0): - """ - Return the pathname of the widget given by ID. - """ + """Return the pathname of the widget given by ID.""" def winfo_pixels(self, number: _ScreenUnits) -> int: - """ - Rounded integer value of winfo_fpixels. - """ + """Rounded integer value of winfo_fpixels.""" def winfo_pointerx(self) -> int: - """ - Return the x coordinate of the pointer on the root window. - """ + """Return the x coordinate of the pointer on the root window.""" def winfo_pointerxy(self) -> tuple[int, int]: - """ - Return a tuple of x and y coordinates of the pointer on the root window. - """ + """Return a tuple of x and y coordinates of the pointer on the root window.""" def winfo_pointery(self) -> int: - """ - Return the y coordinate of the pointer on the root window. - """ + """Return the y coordinate of the pointer on the root window.""" def winfo_reqheight(self) -> int: - """ - Return requested height of this widget. - """ + """Return requested height of this widget.""" def winfo_reqwidth(self) -> int: - """ - Return requested width of this widget. - """ + """Return requested width of this widget.""" def winfo_rgb(self, color: str) -> tuple[int, int, int]: - """ - Return a tuple of integer RGB values in range(65536) for color in this widget. - """ + """Return a tuple of integer RGB values in range(65536) for color in this widget.""" def winfo_rootx(self) -> int: - """ - Return x coordinate of upper left corner of this widget on the + """Return x coordinate of upper left corner of this widget on the root window. """ def winfo_rooty(self) -> int: - """ - Return y coordinate of upper left corner of this widget on the + """Return y coordinate of upper left corner of this widget on the root window. """ def winfo_screen(self) -> str: - """ - Return the screen name of this widget. - """ + """Return the screen name of this widget.""" def winfo_screencells(self) -> int: - """ - Return the number of the cells in the colormap of the screen + """Return the number of the cells in the colormap of the screen of this widget. """ def winfo_screendepth(self) -> int: - """ - Return the number of bits per pixel of the root window of the + """Return the number of bits per pixel of the root window of the screen of this widget. """ def winfo_screenheight(self) -> int: - """ - Return the number of pixels of the height of the screen of this widget + """Return the number of pixels of the height of the screen of this widget in pixel. """ def winfo_screenmmheight(self) -> int: - """ - Return the number of pixels of the height of the screen of + """Return the number of pixels of the height of the screen of this widget in mm. """ def winfo_screenmmwidth(self) -> int: - """ - Return the number of pixels of the width of the screen of + """Return the number of pixels of the width of the screen of this widget in mm. """ def winfo_screenvisual(self) -> str: - """ - Return one of the strings directcolor, grayscale, pseudocolor, + """Return one of the strings directcolor, grayscale, pseudocolor, staticcolor, staticgray, or truecolor for the default colormodel of this screen. """ def winfo_screenwidth(self) -> int: - """ - Return the number of pixels of the width of the screen of + """Return the number of pixels of the width of the screen of this widget in pixel. """ def winfo_server(self) -> str: - """ - Return information of the X-Server of the screen of this widget in + """Return information of the X-Server of the screen of this widget in the form "XmajorRminor vendor vendorVersion". """ def winfo_toplevel(self) -> Tk | Toplevel: - """ - Return the toplevel widget of this widget. - """ + """Return the toplevel widget of this widget.""" def winfo_viewable(self) -> bool: - """ - Return true if the widget and all its higher ancestors are mapped. - """ + """Return true if the widget and all its higher ancestors are mapped.""" def winfo_visual(self) -> str: - """ - Return one of the strings directcolor, grayscale, pseudocolor, + """Return one of the strings directcolor, grayscale, pseudocolor, staticcolor, staticgray, or truecolor for the colormodel of this widget. """ def winfo_visualid(self) -> str: - """ - Return the X identifier for the visual for this widget. - """ + """Return the X identifier for the visual for this widget.""" def winfo_visualsavailable(self, includeids: bool = False) -> list[tuple[str, int]]: - """ - Return a list of all visuals available for the screen + """Return a list of all visuals available for the screen of this widget. Each item in the list consists of a visual name (see winfo_visual), a @@ -1328,64 +1137,52 @@ class Misc: """ def winfo_vrootheight(self) -> int: - """ - Return the height of the virtual root window associated with this + """Return the height of the virtual root window associated with this widget in pixels. If there is no virtual root window return the height of the screen. """ def winfo_vrootwidth(self) -> int: - """ - Return the width of the virtual root window associated with this + """Return the width of the virtual root window associated with this widget in pixel. If there is no virtual root window return the width of the screen. """ def winfo_vrootx(self) -> int: - """ - Return the x offset of the virtual root relative to the root + """Return the x offset of the virtual root relative to the root window of the screen of this widget. """ def winfo_vrooty(self) -> int: - """ - Return the y offset of the virtual root relative to the root + """Return the y offset of the virtual root relative to the root window of the screen of this widget. """ def winfo_width(self) -> int: - """ - Return the width of this widget. - """ + """Return the width of this widget.""" def winfo_x(self) -> int: - """ - Return the x coordinate of the upper left corner of this widget + """Return the x coordinate of the upper left corner of this widget in the parent. """ def winfo_y(self) -> int: - """ - Return the y coordinate of the upper left corner of this widget + """Return the y coordinate of the upper left corner of this widget in the parent. """ def update(self) -> None: - """ - Enter event loop until all pending events have been processed by Tcl. - """ + """Enter event loop until all pending events have been processed by Tcl.""" def update_idletasks(self) -> None: - """ - Enter event loop until all idle callbacks have been called. This + """Enter event loop until all idle callbacks have been called. This will update the display of windows but not process events caused by the user. """ @overload def bindtags(self, tagList: None = None) -> tuple[str, ...]: - """ - Set or get the list of bindtags for this widget. + """Set or get the list of bindtags for this widget. With no argument return the list of all bindtags associated with this widget. With a list of strings as argument the bindtags are @@ -1404,8 +1201,7 @@ class Misc: func: Callable[[Event[Misc]], object] | None = None, add: Literal["", "+"] | bool | None = None, ) -> str: - """ - Bind to this widget at event SEQUENCE a call to function FUNC. + """Bind to this widget at event SEQUENCE a call to function FUNC. SEQUENCE is a string of concatenated event patterns. An event pattern is of the form @@ -1457,8 +1253,7 @@ class Misc: func: Callable[[Event[Misc]], object] | None = None, add: Literal["", "+"] | bool | None = None, ) -> str: - """ - Bind to all widgets at an event SEQUENCE a call to function FUNC. + """Bind to all widgets at an event SEQUENCE a call to function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value. @@ -1476,8 +1271,7 @@ class Misc: func: Callable[[Event[Misc]], object] | None = None, add: Literal["", "+"] | bool | None = None, ) -> str: - """ - Bind to widgets with bindtag CLASSNAME at event + """Bind to widgets with bindtag CLASSNAME at event SEQUENCE a call of function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or @@ -1490,8 +1284,7 @@ class Misc: @overload def bind_class(self, className: str, *, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... def unbind(self, sequence: str, funcid: str | None = None) -> None: - """ - Unbind for this widget the event SEQUENCE. + """Unbind for this widget the event SEQUENCE. If FUNCID is given, only unbind the function identified with FUNCID and also delete the corresponding Tcl command. @@ -1501,57 +1294,43 @@ class Misc: """ def unbind_all(self, sequence: str) -> None: - """ - Unbind for all widgets for event SEQUENCE all functions. - """ + """Unbind for all widgets for event SEQUENCE all functions.""" def unbind_class(self, className: str, sequence: str) -> None: - """ - Unbind for all widgets with bindtag CLASSNAME for event SEQUENCE + """Unbind for all widgets with bindtag CLASSNAME for event SEQUENCE all functions. """ def mainloop(self, n: int = 0) -> None: - """ - Call the mainloop of Tk. - """ + """Call the mainloop of Tk.""" def quit(self) -> None: - """ - Quit the Tcl interpreter. All widgets will be destroyed. - """ + """Quit the Tcl interpreter. All widgets will be destroyed.""" @property def _windowingsystem(self) -> Literal["win32", "aqua", "x11"]: - """ - Internal function. - """ + """Internal function.""" def nametowidget(self, name: str | Misc | _tkinter.Tcl_Obj) -> Any: - """ - Return the Tkinter instance of a widget identified by + """Return the Tkinter instance of a widget identified by its Tcl name NAME. """ def register( self, func: Callable[..., object], subst: Callable[..., Sequence[Any]] | None = None, needcleanup: int = 1 ) -> str: - """ - Return a newly created Tcl function. If this + """Return a newly created Tcl function. If this function is called, the Python function FUNC will be executed. An optional function SUBST can be given which will be executed before FUNC. """ def keys(self) -> list[str]: - """ - Return a list of all resource names of this widget. - """ + """Return a list of all resource names of this widget.""" @overload def pack_propagate(self, flag: bool) -> bool | None: - """ - Set or get the status for propagation of geometry information. + """Set or get the status for propagation of geometry information. A boolean argument specifies whether the geometry information of the slaves will determine the size of this widget. If no argument @@ -1562,8 +1341,7 @@ class Misc: def pack_propagate(self) -> None: ... propagate = pack_propagate def grid_anchor(self, anchor: _Anchor | None = None) -> None: - """ - The anchor value controls how to place the grid within the + """The anchor value controls how to place the grid within the master when no row/column has any weight. The default anchor is nw. @@ -1573,8 +1351,7 @@ class Misc: def grid_bbox( self, column: None = None, row: None = None, col2: None = None, row2: None = None ) -> tuple[int, int, int, int] | None: - """ - Return a tuple of integer coordinates for the bounding + """Return a tuple of integer coordinates for the bounding box of this widget controlled by the geometry manager grid. If COLUMN, ROW is given the bounding box applies from @@ -1601,8 +1378,7 @@ class Misc: uniform: str = ..., weight: int = ..., ) -> _GridIndexInfo | MaybeNone: # can be None but annoying to check - """ - Configure column INDEX of a grid. + """Configure column INDEX of a grid. Valid resources are minsize (minimum size of the column), weight (how much does additional space propagate to this column) @@ -1619,8 +1395,7 @@ class Misc: uniform: str = ..., weight: int = ..., ) -> _GridIndexInfo | MaybeNone: # can be None but annoying to check - """ - Configure row INDEX of a grid. + """Configure row INDEX of a grid. Valid resources are minsize (minimum size of the row), weight (how much does additional space propagate to this row) @@ -1629,16 +1404,14 @@ class Misc: columnconfigure = grid_columnconfigure rowconfigure = grid_rowconfigure def grid_location(self, x: _ScreenUnits, y: _ScreenUnits) -> tuple[int, int]: - """ - Return a tuple of column and row which identify the cell + """Return a tuple of column and row which identify the cell at which the pixel at position X and Y inside the master widget is located. """ @overload def grid_propagate(self, flag: bool) -> None: - """ - Set or get the status for propagation of geometry information. + """Set or get the status for propagation of geometry information. A boolean argument specifies whether the geometry information of the slaves will determine the size of this widget. If no argument @@ -1648,40 +1421,32 @@ class Misc: @overload def grid_propagate(self) -> bool: ... def grid_size(self) -> tuple[int, int]: - """ - Return a tuple of the number of column and rows in the grid. - """ + """Return a tuple of the number of column and rows in the grid.""" size = grid_size # Widget because Toplevel or Tk is never a slave def pack_slaves(self) -> list[Widget]: - """ - Return a list of all slaves of this widget + """Return a list of all slaves of this widget in its packing order. """ def grid_slaves(self, row: int | None = None, column: int | None = None) -> list[Widget]: - """ - Return a list of all slaves of this widget + """Return a list of all slaves of this widget in its packing order. """ def place_slaves(self) -> list[Widget]: - """ - Return a list of all slaves of this widget + """Return a list of all slaves of this widget in its packing order. """ slaves = pack_slaves def event_add(self, virtual: str, *sequences: str) -> None: - """ - Bind a virtual event VIRTUAL (of the form <>) + """Bind a virtual event VIRTUAL (of the form <>) to an event SEQUENCE such that the virtual event is triggered whenever SEQUENCE occurs. """ def event_delete(self, virtual: str, *sequences: str) -> None: - """ - Unbind a virtual event VIRTUAL from SEQUENCE. - """ + """Unbind a virtual event VIRTUAL from SEQUENCE.""" def event_generate( self, @@ -1715,42 +1480,31 @@ class Misc: x: _ScreenUnits = ..., y: _ScreenUnits = ..., ) -> None: - """ - Generate an event SEQUENCE. Additional + """Generate an event SEQUENCE. Additional keyword arguments specify parameter of the event (e.g. x, y, rootx, rooty). """ def event_info(self, virtual: str | None = None) -> tuple[str, ...]: - """ - Return a list of all virtual events or the information + """Return a list of all virtual events or the information about the SEQUENCE bound to the virtual event VIRTUAL. """ def image_names(self) -> tuple[str, ...]: - """ - Return a list of all existing image names. - """ + """Return a list of all existing image names.""" def image_types(self) -> tuple[str, ...]: - """ - Return a list of all available image types (e.g. photo bitmap). - """ + """Return a list of all available image types (e.g. photo bitmap).""" # See #4363 and #4891 def __setitem__(self, key: str, value: Any) -> None: ... def __getitem__(self, key: str) -> Any: - """ - Return the resource value for a KEY given as string. - """ + """Return the resource value for a KEY given as string.""" def cget(self, key: str) -> Any: - """ - Return the resource value for a KEY given as string. - """ + """Return the resource value for a KEY given as string.""" def configure(self, cnf: Any = None) -> Any: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -1760,8 +1514,7 @@ class Misc: # conflict with the type of config in the subclasses. See #13149 class CallWrapper: - """ - Internal class. Stores function to call when some user + """Internal class. Stores function to call when some user defined Tcl function is called e.g. after an event occurred. """ @@ -1769,39 +1522,30 @@ class CallWrapper: subst: Incomplete widget: Incomplete def __init__(self, func, subst, widget) -> None: - """ - Store FUNC, SUBST and WIDGET as members. - """ + """Store FUNC, SUBST and WIDGET as members.""" def __call__(self, *args): - """ - Apply first function SUBST to arguments, than FUNC. - """ + """Apply first function SUBST to arguments, than FUNC.""" class XView: - """ - Mix-in class for querying and changing the horizontal position + """Mix-in class for querying and changing the horizontal position of a widget's window. """ @overload def xview(self) -> tuple[float, float]: - """ - Query and change the horizontal position of the view. - """ + """Query and change the horizontal position of the view.""" @overload def xview(self, *args): ... def xview_moveto(self, fraction: float) -> None: - """ - Adjusts the view in the window so that FRACTION of the + """Adjusts the view in the window so that FRACTION of the total width of the canvas is off-screen to the left. """ @overload def xview_scroll(self, number: int, what: Literal["units", "pages"]) -> None: - """ - Shift the x-view according to NUMBER which is measured in "units" + """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT). """ @@ -1809,29 +1553,24 @@ class XView: def xview_scroll(self, number: _ScreenUnits, what: Literal["pixels"]) -> None: ... class YView: - """ - Mix-in class for querying and changing the vertical position + """Mix-in class for querying and changing the vertical position of a widget's window. """ @overload def yview(self) -> tuple[float, float]: - """ - Query and change the vertical position of the view. - """ + """Query and change the vertical position of the view.""" @overload def yview(self, *args): ... def yview_moveto(self, fraction: float) -> None: - """ - Adjusts the view in the window so that FRACTION of the + """Adjusts the view in the window so that FRACTION of the total height of the canvas is off-screen to the top. """ @overload def yview_scroll(self, number: int, what: Literal["units", "pages"]) -> None: - """ - Shift the y-view according to NUMBER which is measured in + """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT). """ @@ -1871,14 +1610,11 @@ else: type: str class Wm: - """ - Provides functions for the communication with the window manager. - """ + """Provides functions for the communication with the window manager.""" @overload def wm_aspect(self, minNumer: int, minDenom: int, maxNumer: int, maxDenom: int) -> None: - """ - Instruct the window manager to set the aspect ratio (width/height) + """Instruct the window manager to set the aspect ratio (width/height) of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple of the actual values if no argument is given. """ @@ -1891,8 +1627,7 @@ class Wm: if sys.version_info >= (3, 13): @overload def wm_attributes(self, *, return_python_dict: Literal[False] = False) -> tuple[Any, ...]: - """ - Return or sets platform specific attributes. + """Return or sets platform specific attributes. When called with a single argument return_python_dict=True, return a dict of the platform specific attributes and their values. @@ -1911,8 +1646,7 @@ class Wm: else: @overload def wm_attributes(self) -> tuple[Any, ...]: - """ - Return or sets platform specific attributes. + """Return or sets platform specific attributes. When called with a single argument return_python_dict=True, return a dict of the platform specific attributes and their values. @@ -1927,8 +1661,7 @@ class Wm: @overload def wm_attributes(self, option: Literal["-alpha"], /) -> float: - """ - Return or sets platform specific attributes. + """Return or sets platform specific attributes. When called with a single argument return_python_dict=True, return a dict of the platform specific attributes and their values. @@ -1948,8 +1681,7 @@ class Wm: if sys.platform == "darwin": @overload def wm_attributes(self, option: Literal["-modified"], /) -> bool: - """ - Return or sets platform specific attributes. + """Return or sets platform specific attributes. When called with a single argument return_python_dict=True, return a dict of the platform specific attributes and their values. @@ -1973,8 +1705,7 @@ class Wm: elif sys.platform == "win32": @overload def wm_attributes(self, option: Literal["-transparentcolor"], /) -> str: - """ - Return or sets platform specific attributes. + """Return or sets platform specific attributes. When called with a single argument return_python_dict=True, return a dict of the platform specific attributes and their values. @@ -1995,8 +1726,7 @@ class Wm: # X11 @overload def wm_attributes(self, option: Literal["-zoomed"], /) -> bool: - """ - Return or sets platform specific attributes. + """Return or sets platform specific attributes. When called with a single argument return_python_dict=True, return a dict of the platform specific attributes and their values. @@ -2014,8 +1744,7 @@ class Wm: if sys.version_info >= (3, 13): @overload def wm_attributes(self, option: Literal["alpha"], /) -> float: - """ - Return or sets platform specific attributes. + """Return or sets platform specific attributes. When called with a single argument return_python_dict=True, return a dict of the platform specific attributes and their values. @@ -2035,8 +1764,7 @@ class Wm: if sys.platform == "darwin": @overload def wm_attributes(self, option: Literal["modified"], /) -> bool: - """ - Return or sets platform specific attributes. + """Return or sets platform specific attributes. When called with a single argument return_python_dict=True, return a dict of the platform specific attributes and their values. @@ -2060,8 +1788,7 @@ class Wm: elif sys.platform == "win32": @overload def wm_attributes(self, option: Literal["transparentcolor"], /) -> str: - """ - Return or sets platform specific attributes. + """Return or sets platform specific attributes. When called with a single argument return_python_dict=True, return a dict of the platform specific attributes and their values. @@ -2082,8 +1809,7 @@ class Wm: # X11 @overload def wm_attributes(self, option: Literal["zoomed"], /) -> bool: - """ - Return or sets platform specific attributes. + """Return or sets platform specific attributes. When called with a single argument return_python_dict=True, return a dict of the platform specific attributes and their values. @@ -2110,8 +1836,7 @@ class Wm: if sys.platform == "darwin": @overload def wm_attributes(self, option: Literal["-modified"], value: bool, /) -> Literal[""]: - """ - Return or sets platform specific attributes. + """Return or sets platform specific attributes. When called with a single argument return_python_dict=True, return a dict of the platform specific attributes and their values. @@ -2133,8 +1858,7 @@ class Wm: elif sys.platform == "win32": @overload def wm_attributes(self, option: Literal["-transparentcolor"], value: str, /) -> Literal[""]: - """ - Return or sets platform specific attributes. + """Return or sets platform specific attributes. When called with a single argument return_python_dict=True, return a dict of the platform specific attributes and their values. @@ -2155,8 +1879,7 @@ class Wm: # X11 @overload def wm_attributes(self, option: Literal["-zoomed"], value: bool, /) -> Literal[""]: - """ - Return or sets platform specific attributes. + """Return or sets platform specific attributes. When called with a single argument return_python_dict=True, return a dict of the platform specific attributes and their values. @@ -2188,8 +1911,7 @@ class Wm: topmost: bool = ..., transparent: bool = ..., ) -> None: - """ - Return or sets platform specific attributes. + """Return or sets platform specific attributes. When called with a single argument return_python_dict=True, return a dict of the platform specific attributes and their values. @@ -2213,8 +1935,7 @@ class Wm: toolwindow: bool = ..., topmost: bool = ..., ) -> None: - """ - Return or sets platform specific attributes. + """Return or sets platform specific attributes. When called with a single argument return_python_dict=True, return a dict of the platform specific attributes and their values. @@ -2232,8 +1953,7 @@ class Wm: def wm_attributes( self, *, alpha: float = ..., topmost: bool = ..., zoomed: bool = ..., fullscreen: bool = ..., type: str = ... ) -> None: - """ - Return or sets platform specific attributes. + """Return or sets platform specific attributes. When called with a single argument return_python_dict=True, return a dict of the platform specific attributes and their values. @@ -2247,15 +1967,13 @@ class Wm: """ attributes = wm_attributes def wm_client(self, name: str | None = None) -> str: - """ - Store NAME in WM_CLIENT_MACHINE property of this widget. Return + """Store NAME in WM_CLIENT_MACHINE property of this widget. Return current value. """ client = wm_client @overload def wm_colormapwindows(self) -> list[Misc]: - """ - Store list of window names (WLIST) into WM_COLORMAPWINDOWS property + """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property of this widget. This list contains windows whose colormaps differ from their parents. Return current list of widgets if WLIST is empty. """ @@ -2266,29 +1984,25 @@ class Wm: def wm_colormapwindows(self, first_wlist_item: Misc, /, *other_wlist_items: Misc) -> None: ... colormapwindows = wm_colormapwindows def wm_command(self, value: str | None = None) -> str: - """ - Store VALUE in WM_COMMAND property. It is the command + """Store VALUE in WM_COMMAND property. It is the command which shall be used to invoke the application. Return current command if VALUE is None. """ command = wm_command # Some of these always return empty string, but return type is set to None to prevent accidentally using it def wm_deiconify(self) -> None: - """ - Deiconify this widget. If it was never mapped it will not be mapped. + """Deiconify this widget. If it was never mapped it will not be mapped. On Windows it will raise this widget and give it the focus. """ deiconify = wm_deiconify def wm_focusmodel(self, model: Literal["active", "passive"] | None = None) -> Literal["active", "passive", ""]: - """ - Set focus model to MODEL. "active" means that this widget will claim + """Set focus model to MODEL. "active" means that this widget will claim the focus itself, "passive" means that the window manager shall give the focus. Return current focus model if MODEL is None. """ focusmodel = wm_focusmodel def wm_forget(self, window: Wm) -> None: - """ - The window will be unmapped from the screen and will no longer + """The window will be unmapped from the screen and will no longer be managed by wm. toplevel windows will be treated like frame windows once they are no longer managed by wm, however, the menu option configuration will be remembered and the menus will return @@ -2296,14 +2010,11 @@ class Wm: """ forget = wm_forget def wm_frame(self) -> str: - """ - Return identifier for decorative frame of this widget if present. - """ + """Return identifier for decorative frame of this widget if present.""" frame = wm_frame @overload def wm_geometry(self, newGeometry: None = None) -> str: - """ - Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return + """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return current value if None is given. """ @@ -2311,22 +2022,19 @@ class Wm: def wm_geometry(self, newGeometry: str) -> None: ... geometry = wm_geometry def wm_grid(self, baseWidth=None, baseHeight=None, widthInc=None, heightInc=None): - """ - Instruct the window manager that this widget shall only be + """Instruct the window manager that this widget shall only be resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the number of grid units requested in Tk_GeometryRequest. """ grid = wm_grid def wm_group(self, pathName=None): - """ - Set the group leader widgets for related widgets to PATHNAME. Return + """Set the group leader widgets for related widgets to PATHNAME. Return the group leader of this widget if None is given. """ group = wm_group def wm_iconbitmap(self, bitmap=None, default=None): - """ - Set bitmap for the iconified widget to BITMAP. Return + """Set bitmap for the iconified widget to BITMAP. Return the bitmap if None is given. Under Windows, the DEFAULT parameter can be used to set the icon @@ -2337,25 +2045,20 @@ class Wm: """ iconbitmap = wm_iconbitmap def wm_iconify(self) -> None: - """ - Display widget as icon. - """ + """Display widget as icon.""" iconify = wm_iconify def wm_iconmask(self, bitmap=None): - """ - Set mask for the icon bitmap of this widget. Return the + """Set mask for the icon bitmap of this widget. Return the mask if None is given. """ iconmask = wm_iconmask def wm_iconname(self, newName=None) -> str: - """ - Set the name of the icon for this widget. Return the name if + """Set the name of the icon for this widget. Return the name if None is given. """ iconname = wm_iconname def wm_iconphoto(self, default: bool, image1: _PhotoImageLike | str, /, *args: _PhotoImageLike | str) -> None: - """ - Sets the titlebar icon for this window based on the named photo + """Sets the titlebar icon for this window based on the named photo images passed through args. If default is True, this is applied to all future created toplevels as well. @@ -2377,28 +2080,24 @@ class Wm: """ iconphoto = wm_iconphoto def wm_iconposition(self, x: int | None = None, y: int | None = None) -> tuple[int, int] | None: - """ - Set the position of the icon of this widget to X and Y. Return + """Set the position of the icon of this widget to X and Y. Return a tuple of the current values of X and X if None is given. """ iconposition = wm_iconposition def wm_iconwindow(self, pathName=None): - """ - Set widget PATHNAME to be displayed instead of icon. Return the current + """Set widget PATHNAME to be displayed instead of icon. Return the current value if None is given. """ iconwindow = wm_iconwindow def wm_manage(self, widget) -> None: - """ - The widget specified will become a stand alone top-level window. + """The widget specified will become a stand alone top-level window. The window will be decorated with the window managers title bar, etc. """ manage = wm_manage @overload def wm_maxsize(self, width: None = None, height: None = None) -> tuple[int, int]: - """ - Set max WIDTH and HEIGHT for this widget. If the window is gridded + """Set max WIDTH and HEIGHT for this widget. If the window is gridded the values are given in grid units. Return the current values if None is given. """ @@ -2408,8 +2107,7 @@ class Wm: maxsize = wm_maxsize @overload def wm_minsize(self, width: None = None, height: None = None) -> tuple[int, int]: - """ - Set min WIDTH and HEIGHT for this widget. If the window is gridded + """Set min WIDTH and HEIGHT for this widget. If the window is gridded the values are given in grid units. Return the current values if None is given. """ @@ -2419,8 +2117,7 @@ class Wm: minsize = wm_minsize @overload def wm_overrideredirect(self, boolean: None = None) -> bool | None: # returns True or None - """ - Instruct the window manager to ignore this widget + """Instruct the window manager to ignore this widget if BOOLEAN is given with 1. Return the current value if None is given. """ @@ -2429,16 +2126,14 @@ class Wm: def wm_overrideredirect(self, boolean: bool) -> None: ... overrideredirect = wm_overrideredirect def wm_positionfrom(self, who: Literal["program", "user"] | None = None) -> Literal["", "program", "user"]: - """ - Instruct the window manager that the position of this widget shall + """Instruct the window manager that the position of this widget shall be defined by the user if WHO is "user", and by its own policy if WHO is "program". """ positionfrom = wm_positionfrom @overload def wm_protocol(self, name: str, func: Callable[[], object] | str) -> None: - """ - Bind function FUNC to command NAME for this widget. + """Bind function FUNC to command NAME for this widget. Return the function bound to NAME if None is given. NAME could be e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW". """ @@ -2450,8 +2145,7 @@ class Wm: protocol = wm_protocol @overload def wm_resizable(self, width: None = None, height: None = None) -> tuple[bool, bool]: - """ - Instruct the window manager whether this width can be resized + """Instruct the window manager whether this width can be resized in WIDTH or HEIGHT. Both values are boolean values. """ @@ -2459,16 +2153,14 @@ class Wm: def wm_resizable(self, width: bool, height: bool) -> None: ... resizable = wm_resizable def wm_sizefrom(self, who: Literal["program", "user"] | None = None) -> Literal["", "program", "user"]: - """ - Instruct the window manager that the size of this widget shall + """Instruct the window manager that the size of this widget shall be defined by the user if WHO is "user", and by its own policy if WHO is "program". """ sizefrom = wm_sizefrom @overload def wm_state(self, newstate: None = None) -> str: - """ - Query or set the state of this widget as one of normal, icon, + """Query or set the state of this widget as one of normal, icon, iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only). """ @@ -2477,17 +2169,14 @@ class Wm: state = wm_state @overload def wm_title(self, string: None = None) -> str: - """ - Set the title of this widget. - """ + """Set the title of this widget.""" @overload def wm_title(self, string: str) -> None: ... title = wm_title @overload def wm_transient(self, master: None = None) -> _tkinter.Tcl_Obj: - """ - Instruct the window manager that this widget is transient + """Instruct the window manager that this widget is transient with regard to widget MASTER. """ @@ -2495,15 +2184,13 @@ class Wm: def wm_transient(self, master: Wm | _tkinter.Tcl_Obj) -> None: ... transient = wm_transient def wm_withdraw(self) -> None: - """ - Withdraw this widget from the screen such that it is unmapped + """Withdraw this widget from the screen such that it is unmapped and forgotten by the window manager. Re-draw it with wm_deiconify. """ withdraw = wm_withdraw class Tk(Misc, Wm): - """ - Toplevel widget of Tk which represents mostly the main window + """Toplevel widget of Tk which represents mostly the main window of an application. It has an associated Tcl interpreter. """ @@ -2520,8 +2207,7 @@ class Tk(Misc, Wm): sync: bool = False, use: str | None = None, ) -> None: - """ - Return a new top level widget on screen SCREENNAME. A new Tcl interpreter will + """Return a new top level widget on screen SCREENNAME. A new Tcl interpreter will be created. BASENAME will be used for the identification of the profile file (see readprofile). It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME @@ -2550,8 +2236,7 @@ class Tk(Misc, Wm): takefocus: _TakeFocusValue = ..., width: _ScreenUnits = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -2562,14 +2247,12 @@ class Tk(Misc, Wm): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def destroy(self) -> None: - """ - Destroy this and all descendants widgets. This will + """Destroy this and all descendants widgets. This will end the application of this Tcl interpreter. """ def readprofile(self, baseName: str, className: str) -> None: - """ - Internal function. It reads .BASENAME.tcl and .CLASSNAME.tcl into + """Internal function. It reads .BASENAME.tcl and .CLASSNAME.tcl into the Tcl Interpreter and calls exec on the contents of .BASENAME.py and .CLASSNAME.py if such a file exists in the home directory. """ @@ -2625,8 +2308,7 @@ class _PackInfo(_InMiscTotal): pady: int | tuple[int, int] class Pack: - """ - Geometry manager Pack. + """Geometry manager Pack. Base class to use the methods pack_* in every widget. """ @@ -2652,8 +2334,7 @@ class Pack: in_: Misc = ..., **kw: Any, # allow keyword argument named 'in', see #4836 ) -> None: - """ - Pack a widget in the parent widget. Use as options: + """Pack a widget in the parent widget. Use as options: after=widget - pack it after you have packed widget anchor=NSEW (or subset) - position widget according to given direction @@ -2670,13 +2351,10 @@ class Pack: """ def pack_forget(self) -> None: - """ - Unmap this widget and do not use it for the packing order. - """ + """Unmap this widget and do not use it for the packing order.""" def pack_info(self) -> _PackInfo: # errors if widget hasn't been packed - """ - Return information about the packing options + """Return information about the packing options for this widget. """ pack = pack_configure @@ -2696,8 +2374,7 @@ class _PlaceInfo(_InMiscNonTotal): # empty dict if widget hasn't been placed rely: str # can be float()ed if not empty string class Place: - """ - Geometry manager Place. + """Geometry manager Place. Base class to use the methods place_* in every widget. """ @@ -2720,8 +2397,7 @@ class Place: in_: Misc = ..., **kw: Any, # allow keyword argument named 'in', see #4836 ) -> None: - """ - Place a widget in the parent widget. Use as options: + """Place a widget in the parent widget. Use as options: in=master - master relative to which the widget is placed in_=master - see 'in' option description x=amount - locate anchor of this widget at position x of master @@ -2744,13 +2420,10 @@ class Place: """ def place_forget(self) -> None: - """ - Unmap this widget. - """ + """Unmap this widget.""" def place_info(self) -> _PlaceInfo: - """ - Return information about the placing options + """Return information about the placing options for this widget. """ place = place_configure @@ -2768,8 +2441,7 @@ class _GridInfo(_InMiscNonTotal): # empty dict if widget hasn't been gridded sticky: str # consists of letters 'n', 's', 'w', 'e', no repeats, may be empty class Grid: - """ - Geometry manager Grid. + """Geometry manager Grid. Base class to use the methods grid_* in every widget. """ @@ -2790,8 +2462,7 @@ class Grid: in_: Misc = ..., **kw: Any, # allow keyword argument named 'in', see #4836 ) -> None: - """ - Position a widget in the parent widget in a grid. Use as options: + """Position a widget in the parent widget in a grid. Use as options: column=number - use cell identified with given column (starting with 0) columnspan=number - this widget will span several columns in=master - use master to contain this widget @@ -2807,18 +2478,13 @@ class Grid: """ def grid_forget(self) -> None: - """ - Unmap this widget. - """ + """Unmap this widget.""" def grid_remove(self) -> None: - """ - Unmap this widget but remember the grid options. - """ + """Unmap this widget but remember the grid options.""" def grid_info(self) -> _GridInfo: - """ - Return information about the options + """Return information about the options for positioning this widget in a grid. """ grid = grid_configure @@ -2826,27 +2492,21 @@ class Grid: size = Misc.grid_size class BaseWidget(Misc): - """ - Internal class. - """ + """Internal class.""" master: Misc widgetName: Incomplete def __init__(self, master, widgetName, cnf={}, kw={}, extra=()) -> None: - """ - Construct a widget with the parent widget MASTER, a name WIDGETNAME + """Construct a widget with the parent widget MASTER, a name WIDGETNAME and appropriate options. """ def destroy(self) -> None: - """ - Destroy this and all descendants widgets. - """ + """Destroy this and all descendants widgets.""" # This class represents any widget except Toplevel or Tk. class Widget(BaseWidget, Pack, Place, Grid): - """ - Internal class. + """Internal class. Base class for a widget which can be positioned with the geometry managers Pack, Place or Grid. @@ -2862,8 +2522,7 @@ class Widget(BaseWidget, Pack, Place, Grid): func: Callable[[Event[_W]], object] | None = None, add: Literal["", "+"] | bool | None = None, ) -> str: - """ - Bind to this widget at event SEQUENCE a call to function FUNC. + """Bind to this widget at event SEQUENCE a call to function FUNC. SEQUENCE is a string of concatenated event patterns. An event pattern is of the form @@ -2908,9 +2567,7 @@ class Widget(BaseWidget, Pack, Place, Grid): def bind(self, *, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... class Toplevel(BaseWidget, Wm): - """ - Toplevel widget, e.g. for dialogs. - """ + """Toplevel widget, e.g. for dialogs.""" # Toplevel and Tk have the same options because they correspond to the same # Tcl/Tk toplevel widget. For some reason, config and configure must be @@ -2944,8 +2601,7 @@ class Toplevel(BaseWidget, Wm): visual: str | tuple[str, int] = "", width: _ScreenUnits = 0, ) -> None: - """ - Construct a toplevel widget with the parent MASTER. + """Construct a toplevel widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, class, colormap, container, cursor, height, highlightbackground, @@ -2975,8 +2631,7 @@ class Toplevel(BaseWidget, Wm): takefocus: _TakeFocusValue = ..., width: _ScreenUnits = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -2988,9 +2643,7 @@ class Toplevel(BaseWidget, Wm): config = configure class Button(Widget): - """ - Button widget. - """ + """Button widget.""" def __init__( self, @@ -3040,8 +2693,7 @@ class Button(Widget): width: _ScreenUnits = 0, wraplength: _ScreenUnits = 0, ) -> None: - """ - Construct a button widget with the parent MASTER. + """Construct a button widget with the parent MASTER. STANDARD OPTIONS @@ -3102,8 +2754,7 @@ class Button(Widget): width: _ScreenUnits = ..., wraplength: _ScreenUnits = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -3114,8 +2765,7 @@ class Button(Widget): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def flash(self) -> None: - """ - Flash the button. + """Flash the button. This is accomplished by redisplaying the button several times, alternating between active and @@ -3126,8 +2776,7 @@ class Button(Widget): """ def invoke(self) -> Any: - """ - Invoke the command associated with the button. + """Invoke the command associated with the button. The return value is the return value from the command, or an empty string if there is no command associated with @@ -3136,9 +2785,7 @@ class Button(Widget): """ class Canvas(Widget, XView, YView): - """ - Canvas widget to display graphical elements like lines or text. - """ + """Canvas widget to display graphical elements like lines or text.""" def __init__( self, @@ -3182,8 +2829,7 @@ class Canvas(Widget, XView, YView): yscrollcommand: _XYScrollCommand = "", yscrollincrement: _ScreenUnits = 0, ) -> None: - """ - Construct a canvas widget with the parent MASTER. + """Construct a canvas widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, closeenough, confine, cursor, height, highlightbackground, highlightcolor, @@ -3230,8 +2876,7 @@ class Canvas(Widget, XView, YView): yscrollcommand: _XYScrollCommand = ..., yscrollincrement: _ScreenUnits = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -3242,102 +2887,75 @@ class Canvas(Widget, XView, YView): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def addtag(self, *args): # internal method - """ - Internal function. - """ + """Internal function.""" def addtag_above(self, newtag: str, tagOrId: str | int) -> None: - """ - Add tag NEWTAG to all items above TAGORID. - """ + """Add tag NEWTAG to all items above TAGORID.""" def addtag_all(self, newtag: str) -> None: - """ - Add tag NEWTAG to all items. - """ + """Add tag NEWTAG to all items.""" def addtag_below(self, newtag: str, tagOrId: str | int) -> None: - """ - Add tag NEWTAG to all items below TAGORID. - """ + """Add tag NEWTAG to all items below TAGORID.""" def addtag_closest( self, newtag: str, x: _ScreenUnits, y: _ScreenUnits, halo: _ScreenUnits | None = None, start: str | int | None = None ) -> None: - """ - Add tag NEWTAG to item which is closest to pixel at X, Y. + """Add tag NEWTAG to item which is closest to pixel at X, Y. If several match take the top-most. All items closer than HALO are considered overlapping (all are closest). If START is specified the next below this tag is taken. """ def addtag_enclosed(self, newtag: str, x1: _ScreenUnits, y1: _ScreenUnits, x2: _ScreenUnits, y2: _ScreenUnits) -> None: - """ - Add tag NEWTAG to all items in the rectangle defined + """Add tag NEWTAG to all items in the rectangle defined by X1,Y1,X2,Y2. """ def addtag_overlapping(self, newtag: str, x1: _ScreenUnits, y1: _ScreenUnits, x2: _ScreenUnits, y2: _ScreenUnits) -> None: - """ - Add tag NEWTAG to all items which overlap the rectangle + """Add tag NEWTAG to all items which overlap the rectangle defined by X1,Y1,X2,Y2. """ def addtag_withtag(self, newtag: str, tagOrId: str | int) -> None: - """ - Add tag NEWTAG to all items with TAGORID. - """ + """Add tag NEWTAG to all items with TAGORID.""" def find(self, *args): # internal method - """ - Internal function. - """ + """Internal function.""" def find_above(self, tagOrId: str | int) -> tuple[int, ...]: - """ - Return items above TAGORID. - """ + """Return items above TAGORID.""" def find_all(self) -> tuple[int, ...]: - """ - Return all items. - """ + """Return all items.""" def find_below(self, tagOrId: str | int) -> tuple[int, ...]: - """ - Return all items below TAGORID. - """ + """Return all items below TAGORID.""" def find_closest( self, x: _ScreenUnits, y: _ScreenUnits, halo: _ScreenUnits | None = None, start: str | int | None = None ) -> tuple[int, ...]: - """ - Return item which is closest to pixel at X, Y. + """Return item which is closest to pixel at X, Y. If several match take the top-most. All items closer than HALO are considered overlapping (all are closest). If START is specified the next below this tag is taken. """ def find_enclosed(self, x1: _ScreenUnits, y1: _ScreenUnits, x2: _ScreenUnits, y2: _ScreenUnits) -> tuple[int, ...]: - """ - Return all items in rectangle defined + """Return all items in rectangle defined by X1,Y1,X2,Y2. """ def find_overlapping(self, x1: _ScreenUnits, y1: _ScreenUnits, x2: _ScreenUnits, y2: float) -> tuple[int, ...]: - """ - Return all items which overlap the rectangle + """Return all items which overlap the rectangle defined by X1,Y1,X2,Y2. """ def find_withtag(self, tagOrId: str | int) -> tuple[int, ...]: - """ - Return all items with TAGORID. - """ + """Return all items with TAGORID.""" # Incompatible with Misc.bbox(), tkinter violates LSP def bbox(self, *args: str | int) -> tuple[int, int, int, int]: # type: ignore[override] - """ - Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle + """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle which encloses all items with tags specified as arguments. """ @@ -3349,8 +2967,7 @@ class Canvas(Widget, XView, YView): func: Callable[[Event[Canvas]], object] | None = None, add: Literal["", "+"] | bool | None = None, ) -> str: - """ - Bind to all items with TAGORID at event SEQUENCE a call to function FUNC. + """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will @@ -3364,28 +2981,23 @@ class Canvas(Widget, XView, YView): @overload def tag_bind(self, tagOrId: str | int, *, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... def tag_unbind(self, tagOrId: str | int, sequence: str, funcid: str | None = None) -> None: - """ - Unbind for all items with TAGORID for event SEQUENCE the + """Unbind for all items with TAGORID for event SEQUENCE the function identified with FUNCID. """ def canvasx(self, screenx, gridspacing=None): - """ - Return the canvas x coordinate of pixel position SCREENX rounded + """Return the canvas x coordinate of pixel position SCREENX rounded to nearest multiple of GRIDSPACING units. """ def canvasy(self, screeny, gridspacing=None): - """ - Return the canvas y coordinate of pixel position SCREENY rounded + """Return the canvas y coordinate of pixel position SCREENY rounded to nearest multiple of GRIDSPACING units. """ @overload def coords(self, tagOrId: str | int, /) -> list[float]: - """ - Return a list of coordinates for the item given in ARGS. - """ + """Return a list of coordinates for the item given in ARGS.""" @overload def coords(self, tagOrId: str | int, args: list[int] | list[float] | tuple[float, ...], /) -> None: ... @@ -3395,19 +3007,13 @@ class Canvas(Widget, XView, YView): # Lists and tuples can be flat as in [1, 2, 3, 4], or nested as in [(1, 2), (3, 4)]. # Keyword arguments should be the same in all overloads of each method. def create_arc(self, *args, **kw) -> int: - """ - Create arc shaped region with coordinates x1,y1,x2,y2. - """ + """Create arc shaped region with coordinates x1,y1,x2,y2.""" def create_bitmap(self, *args, **kw) -> int: - """ - Create bitmap with coordinates x1,y1. - """ + """Create bitmap with coordinates x1,y1.""" def create_image(self, *args, **kw) -> int: - """ - Create image item with coordinates x1,y1. - """ + """Create image item with coordinates x1,y1.""" @overload def create_line( @@ -3441,9 +3047,7 @@ class Canvas(Widget, XView, YView): tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., ) -> int: - """ - Create line with coordinates x1,y1,...,xn,yn. - """ + """Create line with coordinates x1,y1,...,xn,yn.""" @overload def create_line( @@ -3544,9 +3148,7 @@ class Canvas(Widget, XView, YView): tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., ) -> int: - """ - Create oval with coordinates x1,y1,x2,y2. - """ + """Create oval with coordinates x1,y1,x2,y2.""" @overload def create_oval( @@ -3652,9 +3254,7 @@ class Canvas(Widget, XView, YView): tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., ) -> int: - """ - Create polygon with coordinates x1,y1,...,xn,yn. - """ + """Create polygon with coordinates x1,y1,...,xn,yn.""" @overload def create_polygon( @@ -3763,9 +3363,7 @@ class Canvas(Widget, XView, YView): tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., ) -> int: - """ - Create rectangle with coordinates x1,y1,x2,y2. - """ + """Create rectangle with coordinates x1,y1,x2,y2.""" @overload def create_rectangle( @@ -3858,9 +3456,7 @@ class Canvas(Widget, XView, YView): text: float | str = ..., width: _ScreenUnits = ..., ) -> int: - """ - Create text with coordinates x1,y1. - """ + """Create text with coordinates x1,y1.""" @overload def create_text( @@ -3898,9 +3494,7 @@ class Canvas(Widget, XView, YView): width: _ScreenUnits = ..., window: Widget = ..., ) -> int: - """ - Create window with coordinates x1,y1,x2,y2. - """ + """Create window with coordinates x1,y1,x2,y2.""" @overload def create_window( @@ -3916,62 +3510,47 @@ class Canvas(Widget, XView, YView): window: Widget = ..., ) -> int: ... def dchars(self, *args) -> None: - """ - Delete characters of text items identified by tag or id in ARGS (possibly + """Delete characters of text items identified by tag or id in ARGS (possibly several times) from FIRST to LAST character (including). """ def delete(self, *tagsOrCanvasIds: str | int) -> None: - """ - Delete items identified by all tag or ids contained in ARGS. - """ + """Delete items identified by all tag or ids contained in ARGS.""" @overload def dtag(self, tag: str, tag_to_delete: str | None = ..., /) -> None: - """ - Delete tag or id given as last arguments in ARGS from items + """Delete tag or id given as last arguments in ARGS from items identified by first argument in ARGS. """ @overload def dtag(self, id: int, tag_to_delete: str, /) -> None: ... def focus(self, *args): - """ - Set focus to the first item specified in ARGS. - """ + """Set focus to the first item specified in ARGS.""" def gettags(self, tagOrId: str | int, /) -> tuple[str, ...]: - """ - Return tags associated with the first item specified in ARGS. - """ + """Return tags associated with the first item specified in ARGS.""" def icursor(self, *args) -> None: - """ - Set cursor at position POS in the item identified by TAGORID. + """Set cursor at position POS in the item identified by TAGORID. In ARGS TAGORID must be first. """ def index(self, *args): - """ - Return position of cursor as integer in item specified in ARGS. - """ + """Return position of cursor as integer in item specified in ARGS.""" def insert(self, *args) -> None: - """ - Insert TEXT in item TAGORID at position POS. ARGS must + """Insert TEXT in item TAGORID at position POS. ARGS must be TAGORID POS TEXT. """ def itemcget(self, tagOrId, option): - """ - Return the resource value for an OPTION for item TAGORID. - """ + """Return the resource value for an OPTION for item TAGORID.""" # itemconfigure kwargs depend on item type, which is not known when type checking def itemconfigure( self, tagOrId: str | int, cnf: dict[str, Any] | None = None, **kw: Any ) -> dict[str, tuple[str, str, str, str, str]] | None: - """ - Configure resources of an item TAGORID. + """Configure resources of an item TAGORID. The values for resources are specified as keyword arguments. To get an overview about @@ -3979,13 +3558,10 @@ class Canvas(Widget, XView, YView): """ itemconfig = itemconfigure def move(self, *args) -> None: - """ - Move an item TAGORID given in ARGS. - """ + """Move an item TAGORID given in ARGS.""" def moveto(self, tagOrId: str | int, x: Literal[""] | float = "", y: Literal[""] | float = "") -> None: - """ - Move the items given by TAGORID in the canvas coordinate + """Move the items given by TAGORID in the canvas coordinate space so that the first coordinate pair of the bottommost item with tag TAGORID is located at position (X,Y). X and Y may be the empty string, in which case the @@ -3994,8 +3570,7 @@ class Canvas(Widget, XView, YView): """ def postscript(self, cnf={}, **kw): - """ - Print the contents of the canvas to a postscript + """Print the contents of the canvas to a postscript file. Valid options: colormap, colormode, file, fontmap, height, pageanchor, pageheight, pagewidth, pagex, pagey, rotate, width, x, y. @@ -4006,86 +3581,62 @@ class Canvas(Widget, XView, YView): # # But mypy doesn't like aliasing here (maybe because Misc defines the same names) def tag_lower(self, first: str | int, second: str | int | None = ..., /) -> None: - """ - Lower an item TAGORID given in ARGS + """Lower an item TAGORID given in ARGS (optional below another item). """ def lower(self, first: str | int, second: str | int | None = ..., /) -> None: # type: ignore[override] - """ - Lower an item TAGORID given in ARGS + """Lower an item TAGORID given in ARGS (optional below another item). """ def tag_raise(self, first: str | int, second: str | int | None = ..., /) -> None: - """ - Raise an item TAGORID given in ARGS + """Raise an item TAGORID given in ARGS (optional above another item). """ def tkraise(self, first: str | int, second: str | int | None = ..., /) -> None: # type: ignore[override] - """ - Raise an item TAGORID given in ARGS + """Raise an item TAGORID given in ARGS (optional above another item). """ def lift(self, first: str | int, second: str | int | None = ..., /) -> None: # type: ignore[override] - """ - Raise an item TAGORID given in ARGS + """Raise an item TAGORID given in ARGS (optional above another item). """ def scale(self, tagOrId: str | int, xOrigin: _ScreenUnits, yOrigin: _ScreenUnits, xScale: float, yScale: float, /) -> None: - """ - Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE. - """ + """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE.""" def scan_mark(self, x, y) -> None: - """ - Remember the current X, Y coordinates. - """ + """Remember the current X, Y coordinates.""" def scan_dragto(self, x, y, gain: int = 10) -> None: - """ - Adjust the view of the canvas to GAIN times the + """Adjust the view of the canvas to GAIN times the difference between X and Y and the coordinates given in scan_mark. """ def select_adjust(self, tagOrId, index) -> None: - """ - Adjust the end of the selection near the cursor of an item TAGORID to index. - """ + """Adjust the end of the selection near the cursor of an item TAGORID to index.""" def select_clear(self) -> None: - """ - Clear the selection if it is in this widget. - """ + """Clear the selection if it is in this widget.""" def select_from(self, tagOrId, index) -> None: - """ - Set the fixed end of a selection in item TAGORID to INDEX. - """ + """Set the fixed end of a selection in item TAGORID to INDEX.""" def select_item(self): - """ - Return the item which has the selection. - """ + """Return the item which has the selection.""" def select_to(self, tagOrId, index) -> None: - """ - Set the variable end of a selection in item TAGORID to INDEX. - """ + """Set the variable end of a selection in item TAGORID to INDEX.""" def type(self, tagOrId: str | int) -> int | None: - """ - Return the type of the item TAGORID. - """ + """Return the type of the item TAGORID.""" class Checkbutton(Widget): - """ - Checkbutton widget which is either in on- or off-state. - """ + """Checkbutton widget which is either in on- or off-state.""" def __init__( self, @@ -4146,8 +3697,7 @@ class Checkbutton(Widget): width: _ScreenUnits = 0, wraplength: _ScreenUnits = 0, ) -> None: - """ - Construct a checkbutton widget with the parent MASTER. + """Construct a checkbutton widget with the parent MASTER. Valid resource names: activebackground, activeforeground, anchor, background, bd, bg, bitmap, borderwidth, command, cursor, @@ -4206,8 +3756,7 @@ class Checkbutton(Widget): width: _ScreenUnits = ..., wraplength: _ScreenUnits = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -4218,34 +3767,22 @@ class Checkbutton(Widget): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def deselect(self) -> None: - """ - Put the button in off-state. - """ + """Put the button in off-state.""" def flash(self) -> None: - """ - Flash the button. - """ + """Flash the button.""" def invoke(self) -> Any: - """ - Toggle the button and invoke a command if given as resource. - """ + """Toggle the button and invoke a command if given as resource.""" def select(self) -> None: - """ - Put the button in on-state. - """ + """Put the button in on-state.""" def toggle(self) -> None: - """ - Toggle the button. - """ + """Toggle the button.""" class Entry(Widget, XView): - """ - Entry widget which allows displaying simple text. - """ + """Entry widget which allows displaying simple text.""" def __init__( self, @@ -4291,8 +3828,7 @@ class Entry(Widget, XView): width: int = 20, xscrollcommand: _XYScrollCommand = "", ) -> None: - """ - Construct an entry widget with the parent MASTER. + """Construct an entry widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, cursor, exportselection, fg, font, foreground, highlightbackground, @@ -4347,8 +3883,7 @@ class Entry(Widget, XView): width: int = ..., xscrollcommand: _XYScrollCommand = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -4359,72 +3894,48 @@ class Entry(Widget, XView): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def delete(self, first: str | int, last: str | int | None = None) -> None: - """ - Delete text from FIRST to LAST (not included). - """ + """Delete text from FIRST to LAST (not included).""" def get(self) -> str: - """ - Return the text. - """ + """Return the text.""" def icursor(self, index: str | int) -> None: - """ - Insert cursor at INDEX. - """ + """Insert cursor at INDEX.""" def index(self, index: str | int) -> int: - """ - Return position of cursor. - """ + """Return position of cursor.""" def insert(self, index: str | int, string: str) -> None: - """ - Insert STRING at INDEX. - """ + """Insert STRING at INDEX.""" def scan_mark(self, x) -> None: - """ - Remember the current X, Y coordinates. - """ + """Remember the current X, Y coordinates.""" def scan_dragto(self, x) -> None: - """ - Adjust the view of the canvas to 10 times the + """Adjust the view of the canvas to 10 times the difference between X and Y and the coordinates given in scan_mark. """ def selection_adjust(self, index: str | int) -> None: - """ - Adjust the end of the selection near the cursor to INDEX. - """ + """Adjust the end of the selection near the cursor to INDEX.""" def selection_clear(self) -> None: # type: ignore[override] - """ - Clear the selection if it is in this widget. - """ + """Clear the selection if it is in this widget.""" def selection_from(self, index: str | int) -> None: - """ - Set the fixed end of a selection to INDEX. - """ + """Set the fixed end of a selection to INDEX.""" def selection_present(self) -> bool: - """ - Return True if there are characters selected in the entry, False + """Return True if there are characters selected in the entry, False otherwise. """ def selection_range(self, start: str | int, end: str | int) -> None: - """ - Set the selection from START to END (not included). - """ + """Set the selection from START to END (not included).""" def selection_to(self, index: str | int) -> None: - """ - Set the variable end of a selection to INDEX. - """ + """Set the variable end of a selection to INDEX.""" select_adjust = selection_adjust select_clear = selection_clear select_from = selection_from @@ -4433,9 +3944,7 @@ class Entry(Widget, XView): select_to = selection_to class Frame(Widget): - """ - Frame widget which may contain other widgets and can have a 3D border. - """ + """Frame widget which may contain other widgets and can have a 3D border.""" def __init__( self, @@ -4463,8 +3972,7 @@ class Frame(Widget): visual: str | tuple[str, int] = "", # can't be changed with configure() width: _ScreenUnits = 0, ) -> None: - """ - Construct a frame widget with the parent MASTER. + """Construct a frame widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, class, colormap, container, cursor, height, highlightbackground, @@ -4492,8 +4000,7 @@ class Frame(Widget): takefocus: _TakeFocusValue = ..., width: _ScreenUnits = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -4505,9 +4012,7 @@ class Frame(Widget): config = configure class Label(Widget): - """ - Label widget which can display text and bitmaps. - """ + """Label widget which can display text and bitmaps.""" def __init__( self, @@ -4547,8 +4052,7 @@ class Label(Widget): width: _ScreenUnits = 0, wraplength: _ScreenUnits = 0, ) -> None: - """ - Construct a label widget with the parent MASTER. + """Construct a label widget with the parent MASTER. STANDARD OPTIONS @@ -4602,8 +4106,7 @@ class Label(Widget): width: _ScreenUnits = ..., wraplength: _ScreenUnits = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -4615,9 +4118,7 @@ class Label(Widget): config = configure class Listbox(Widget, XView, YView): - """ - Listbox widget which can display a list of strings. - """ + """Listbox widget which can display a list of strings.""" def __init__( self, @@ -4670,8 +4171,7 @@ class Listbox(Widget, XView, YView): xscrollcommand: _XYScrollCommand = "", yscrollcommand: _XYScrollCommand = "", ) -> None: - """ - Construct a listbox widget with the parent MASTER. + """Construct a listbox widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, cursor, exportselection, fg, font, foreground, height, highlightbackground, @@ -4715,8 +4215,7 @@ class Listbox(Widget, XView, YView): xscrollcommand: _XYScrollCommand = ..., yscrollcommand: _XYScrollCommand = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -4727,97 +4226,65 @@ class Listbox(Widget, XView, YView): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def activate(self, index: str | int) -> None: - """ - Activate item identified by INDEX. - """ + """Activate item identified by INDEX.""" def bbox(self, index: str | int) -> tuple[int, int, int, int] | None: # type: ignore[override] - """ - Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle + """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle which encloses the item identified by the given index. """ def curselection(self): - """ - Return the indices of currently selected item. - """ + """Return the indices of currently selected item.""" def delete(self, first: str | int, last: str | int | None = None) -> None: - """ - Delete items from FIRST to LAST (included). - """ + """Delete items from FIRST to LAST (included).""" def get(self, first: str | int, last: str | int | None = None): - """ - Get list of items from FIRST to LAST (included). - """ + """Get list of items from FIRST to LAST (included).""" def index(self, index: str | int) -> int: - """ - Return index of item identified with INDEX. - """ + """Return index of item identified with INDEX.""" def insert(self, index: str | int, *elements: str | float) -> None: - """ - Insert ELEMENTS at INDEX. - """ + """Insert ELEMENTS at INDEX.""" def nearest(self, y): - """ - Get index of item which is nearest to y coordinate Y. - """ + """Get index of item which is nearest to y coordinate Y.""" def scan_mark(self, x, y) -> None: - """ - Remember the current X, Y coordinates. - """ + """Remember the current X, Y coordinates.""" def scan_dragto(self, x, y) -> None: - """ - Adjust the view of the listbox to 10 times the + """Adjust the view of the listbox to 10 times the difference between X and Y and the coordinates given in scan_mark. """ def see(self, index: str | int) -> None: - """ - Scroll such that INDEX is visible. - """ + """Scroll such that INDEX is visible.""" def selection_anchor(self, index: str | int) -> None: - """ - Set the fixed end oft the selection to INDEX. - """ + """Set the fixed end oft the selection to INDEX.""" select_anchor = selection_anchor def selection_clear(self, first: str | int, last: str | int | None = None) -> None: # type: ignore[override] - """ - Clear the selection from FIRST to LAST (included). - """ + """Clear the selection from FIRST to LAST (included).""" select_clear = selection_clear def selection_includes(self, index: str | int): - """ - Return True if INDEX is part of the selection. - """ + """Return True if INDEX is part of the selection.""" select_includes = selection_includes def selection_set(self, first: str | int, last: str | int | None = None) -> None: - """ - Set the selection from FIRST to LAST (included) without + """Set the selection from FIRST to LAST (included) without changing the currently selected elements. """ select_set = selection_set def size(self) -> int: # type: ignore[override] - """ - Return the number of elements in the listbox. - """ + """Return the number of elements in the listbox.""" def itemcget(self, index: str | int, option): - """ - Return the resource value for an ITEM and an OPTION. - """ + """Return the resource value for an ITEM and an OPTION.""" def itemconfigure(self, index: str | int, cnf=None, **kw): - """ - Configure resources of an ITEM. + """Configure resources of an ITEM. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments @@ -4828,9 +4295,7 @@ class Listbox(Widget, XView, YView): itemconfig = itemconfigure class Menu(Widget): - """ - Menu widget which allows displaying menu bars, pull-down menus and pop-up menus. - """ + """Menu widget which allows displaying menu bars, pull-down menus and pop-up menus.""" def __init__( self, @@ -4863,8 +4328,7 @@ class Menu(Widget): title: str = "", type: Literal["menubar", "tearoff", "normal"] = "normal", ) -> None: - """ - Construct menu widget with the parent MASTER. + """Construct menu widget with the parent MASTER. Valid resource names: activebackground, activeborderwidth, activeforeground, background, bd, bg, borderwidth, cursor, @@ -4899,8 +4363,7 @@ class Menu(Widget): title: str = ..., type: Literal["menubar", "tearoff", "normal"] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -4911,24 +4374,16 @@ class Menu(Widget): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def tk_popup(self, x: int, y: int, entry: str | int = "") -> None: - """ - Post the menu at position X,Y with entry ENTRY. - """ + """Post the menu at position X,Y with entry ENTRY.""" def activate(self, index: str | int) -> None: - """ - Activate entry at INDEX. - """ + """Activate entry at INDEX.""" def add(self, itemType, cnf={}, **kw): # docstring says "Internal function." - """ - Internal function. - """ + """Internal function.""" def insert(self, index, itemType, cnf={}, **kw): # docstring says "Internal function." - """ - Internal function. - """ + """Internal function.""" def add_cascade( self, @@ -4951,9 +4406,7 @@ class Menu(Widget): state: Literal["normal", "active", "disabled"] = ..., underline: int = ..., ) -> None: - """ - Add hierarchical menu item. - """ + """Add hierarchical menu item.""" def add_checkbutton( self, @@ -4981,9 +4434,7 @@ class Menu(Widget): underline: int = ..., variable: Variable = ..., ) -> None: - """ - Add checkbutton menu item. - """ + """Add checkbutton menu item.""" def add_command( self, @@ -5005,9 +4456,7 @@ class Menu(Widget): state: Literal["normal", "active", "disabled"] = ..., underline: int = ..., ) -> None: - """ - Add command menu item. - """ + """Add command menu item.""" def add_radiobutton( self, @@ -5034,14 +4483,10 @@ class Menu(Widget): value: Any = ..., variable: Variable = ..., ) -> None: - """ - Add radio menu item. - """ + """Add radio menu item.""" def add_separator(self, cnf: dict[str, Any] | None = {}, *, background: str = ...) -> None: - """ - Add separator. - """ + """Add separator.""" def insert_cascade( self, @@ -5065,9 +4510,7 @@ class Menu(Widget): state: Literal["normal", "active", "disabled"] = ..., underline: int = ..., ) -> None: - """ - Add hierarchical menu item at INDEX. - """ + """Add hierarchical menu item at INDEX.""" def insert_checkbutton( self, @@ -5096,9 +4539,7 @@ class Menu(Widget): underline: int = ..., variable: Variable = ..., ) -> None: - """ - Add checkbutton menu item at INDEX. - """ + """Add checkbutton menu item at INDEX.""" def insert_command( self, @@ -5121,9 +4562,7 @@ class Menu(Widget): state: Literal["normal", "active", "disabled"] = ..., underline: int = ..., ) -> None: - """ - Add command menu item at INDEX. - """ + """Add command menu item at INDEX.""" def insert_radiobutton( self, @@ -5151,73 +4590,49 @@ class Menu(Widget): value: Any = ..., variable: Variable = ..., ) -> None: - """ - Add radio menu item at INDEX. - """ + """Add radio menu item at INDEX.""" def insert_separator(self, index: str | int, cnf: dict[str, Any] | None = {}, *, background: str = ...) -> None: - """ - Add separator at INDEX. - """ + """Add separator at INDEX.""" def delete(self, index1: str | int, index2: str | int | None = None) -> None: - """ - Delete menu items between INDEX1 and INDEX2 (included). - """ + """Delete menu items between INDEX1 and INDEX2 (included).""" def entrycget(self, index: str | int, option: str) -> Any: - """ - Return the resource value of a menu item for OPTION at INDEX. - """ + """Return the resource value of a menu item for OPTION at INDEX.""" def entryconfigure( self, index: str | int, cnf: dict[str, Any] | None = None, **kw: Any ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure a menu item at INDEX. - """ + """Configure a menu item at INDEX.""" entryconfig = entryconfigure def index(self, index: str | int) -> int | None: - """ - Return the index of a menu item identified by INDEX. - """ + """Return the index of a menu item identified by INDEX.""" def invoke(self, index: str | int) -> Any: - """ - Invoke a menu item identified by INDEX and execute + """Invoke a menu item identified by INDEX and execute the associated command. """ def post(self, x: int, y: int) -> None: - """ - Display a menu at position X,Y. - """ + """Display a menu at position X,Y.""" def type(self, index: str | int) -> Literal["cascade", "checkbutton", "command", "radiobutton", "separator"]: - """ - Return the type of the menu item at INDEX. - """ + """Return the type of the menu item at INDEX.""" def unpost(self) -> None: - """ - Unmap a menu. - """ + """Unmap a menu.""" def xposition(self, index: str | int) -> int: - """ - Return the x-position of the leftmost pixel of the menu item + """Return the x-position of the leftmost pixel of the menu item at INDEX. """ def yposition(self, index: str | int) -> int: - """ - Return the y-position of the topmost pixel of the menu item at INDEX. - """ + """Return the y-position of the topmost pixel of the menu item at INDEX.""" class Menubutton(Widget): - """ - Menubutton widget, obsolete since Tk8.0. - """ + """Menubutton widget, obsolete since Tk8.0.""" def __init__( self, @@ -5300,8 +4715,7 @@ class Menubutton(Widget): width: _ScreenUnits = ..., wraplength: _ScreenUnits = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -5313,9 +4727,7 @@ class Menubutton(Widget): config = configure class Message(Widget): - """ - Message widget to display multiline text. Obsolete since Label does it too. - """ + """Message widget to display multiline text. Obsolete since Label does it too.""" def __init__( self, @@ -5375,8 +4787,7 @@ class Message(Widget): textvariable: Variable = ..., width: _ScreenUnits = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -5388,9 +4799,7 @@ class Message(Widget): config = configure class Radiobutton(Widget): - """ - Radiobutton widget which shows only one of several buttons in on-state. - """ + """Radiobutton widget which shows only one of several buttons in on-state.""" def __init__( self, @@ -5440,8 +4849,7 @@ class Radiobutton(Widget): width: _ScreenUnits = 0, wraplength: _ScreenUnits = 0, ) -> None: - """ - Construct a radiobutton widget with the parent MASTER. + """Construct a radiobutton widget with the parent MASTER. Valid resource names: activebackground, activeforeground, anchor, background, bd, bg, bitmap, borderwidth, command, cursor, @@ -5499,8 +4907,7 @@ class Radiobutton(Widget): width: _ScreenUnits = ..., wraplength: _ScreenUnits = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -5511,29 +4918,19 @@ class Radiobutton(Widget): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def deselect(self) -> None: - """ - Put the button in off-state. - """ + """Put the button in off-state.""" def flash(self) -> None: - """ - Flash the button. - """ + """Flash the button.""" def invoke(self) -> Any: - """ - Toggle the button and invoke a command if given as resource. - """ + """Toggle the button and invoke a command if given as resource.""" def select(self) -> None: - """ - Put the button in on-state. - """ + """Put the button in on-state.""" class Scale(Widget): - """ - Scale widget which can display a numerical scale. - """ + """Scale widget which can display a numerical scale.""" def __init__( self, @@ -5577,8 +4974,7 @@ class Scale(Widget): variable: IntVar | DoubleVar = ..., width: _ScreenUnits = 15, ) -> None: - """ - Construct a scale widget with the parent MASTER. + """Construct a scale widget with the parent MASTER. Valid resource names: activebackground, background, bigincrement, bd, bg, borderwidth, command, cursor, digits, fg, font, foreground, from, @@ -5628,8 +5024,7 @@ class Scale(Widget): variable: IntVar | DoubleVar = ..., width: _ScreenUnits = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -5640,32 +5035,24 @@ class Scale(Widget): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def get(self) -> float: - """ - Get the current value as integer or float. - """ + """Get the current value as integer or float.""" def set(self, value) -> None: - """ - Set the value to VALUE. - """ + """Set the value to VALUE.""" def coords(self, value: float | None = None) -> tuple[int, int]: - """ - Return a tuple (X,Y) of the point along the centerline of the + """Return a tuple (X,Y) of the point along the centerline of the trough that corresponds to VALUE or the current value if None is given. """ def identify(self, x, y) -> Literal["", "slider", "trough1", "trough2"]: - """ - Return where the point X,Y lies. Valid return values are "slider", + """Return where the point X,Y lies. Valid return values are "slider", "though1" and "though2". """ class Scrollbar(Widget): - """ - Scrollbar widget which displays a slider at a certain position. - """ + """Scrollbar widget which displays a slider at a certain position.""" def __init__( self, @@ -5699,8 +5086,7 @@ class Scrollbar(Widget): troughcolor: str = ..., width: _ScreenUnits = ..., ) -> None: - """ - Construct a scrollbar widget with the parent MASTER. + """Construct a scrollbar widget with the parent MASTER. Valid resource names: activebackground, activerelief, background, bd, bg, borderwidth, command, cursor, @@ -5737,8 +5123,7 @@ class Scrollbar(Widget): troughcolor: str = ..., width: _ScreenUnits = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -5749,8 +5134,7 @@ class Scrollbar(Widget): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def activate(self, index=None): - """ - Marks the element indicated by index as active. + """Marks the element indicated by index as active. The only index values understood by this method are "arrow1", "slider", or "arrow2". If any other value is specified then no element of the scrollbar will be active. If index is not specified, @@ -5759,32 +5143,27 @@ class Scrollbar(Widget): """ def delta(self, deltax: int, deltay: int) -> float: - """ - Return the fractional change of the scrollbar setting if it + """Return the fractional change of the scrollbar setting if it would be moved by DELTAX or DELTAY pixels. """ def fraction(self, x: int, y: int) -> float: - """ - Return the fractional value which corresponds to a slider + """Return the fractional value which corresponds to a slider position of X,Y. """ def identify(self, x: int, y: int) -> Literal["arrow1", "arrow2", "slider", "trough1", "trough2", ""]: - """ - Return the element under position X,Y as one of + """Return the element under position X,Y as one of "arrow1","slider","arrow2" or "". """ def get(self) -> tuple[float, float, float, float] | tuple[float, float]: - """ - Return the current fractional values (upper and lower end) + """Return the current fractional values (upper and lower end) of the slider position. """ def set(self, first: float | str, last: float | str) -> None: - """ - Set the fractional values of the slider position (upper and + """Set the fractional values of the slider position (upper and lower ends as value between 0 and 1). """ @@ -5794,9 +5173,7 @@ _WhatToCount: TypeAlias = Literal[ ] class Text(Widget, XView, YView): - """ - Text widget which can display text in various forms. - """ + """Text widget which can display text in various forms.""" def __init__( self, @@ -5854,8 +5231,7 @@ class Text(Widget, XView, YView): xscrollcommand: _XYScrollCommand = "", yscrollcommand: _XYScrollCommand = "", ) -> None: - """ - Construct a text widget with the parent MASTER. + """Construct a text widget with the parent MASTER. STANDARD OPTIONS @@ -5928,8 +5304,7 @@ class Text(Widget, XView, YView): xscrollcommand: _XYScrollCommand = ..., yscrollcommand: _XYScrollCommand = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -5940,21 +5315,18 @@ class Text(Widget, XView, YView): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def bbox(self, index: _TextIndex) -> tuple[int, int, int, int] | None: # type: ignore[override] - """ - Return a tuple of (x,y,width,height) which gives the bounding + """Return a tuple of (x,y,width,height) which gives the bounding box of the visible part of the character at the given index. """ def compare(self, index1: _TextIndex, op: Literal["<", "<=", "==", ">=", ">", "!="], index2: _TextIndex) -> bool: - """ - Return whether between index INDEX1 and index INDEX2 the + """Return whether between index INDEX1 and index INDEX2 the relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=. """ if sys.version_info >= (3, 13): @overload def count(self, index1: _TextIndex, index2: _TextIndex, *, return_ints: Literal[True]) -> int: - """ - Counts the number of relevant things between the two indices. + """Counts the number of relevant things between the two indices. If INDEX1 is after INDEX2, the result will be a negative number (and this holds for each of the possible options). @@ -6073,8 +5445,7 @@ class Text(Widget, XView, YView): else: @overload def count(self, index1: _TextIndex, index2: _TextIndex) -> tuple[int] | None: - """ - Counts the number of relevant things between the two indices. + """Counts the number of relevant things between the two indices. If INDEX1 is after INDEX2, the result will be a negative number (and this holds for each of the possible options). @@ -6115,21 +5486,17 @@ class Text(Widget, XView, YView): @overload def debug(self, boolean: None = None) -> bool: - """ - Turn on the internal consistency checks of the B-Tree inside the text + """Turn on the internal consistency checks of the B-Tree inside the text widget according to BOOLEAN. """ @overload def debug(self, boolean: bool) -> None: ... def delete(self, index1: _TextIndex, index2: _TextIndex | None = None) -> None: - """ - Delete the characters between INDEX1 and INDEX2 (not included). - """ + """Delete the characters between INDEX1 and INDEX2 (not included).""" def dlineinfo(self, index: _TextIndex) -> tuple[int, int, int, int, int] | None: - """ - Return tuple (x,y,width,height,baseline) giving the bounding box + """Return tuple (x,y,width,height,baseline) giving the bounding box and baseline position of the visible part of the line containing the character at INDEX. """ @@ -6148,8 +5515,7 @@ class Text(Widget, XView, YView): text: bool = ..., window: bool = ..., ) -> list[tuple[str, str, str]]: - """ - Return the contents of the widget between index1 and index2. + """Return the contents of the widget between index1 and index2. The type of contents returned in filtered based on the keyword parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are @@ -6191,8 +5557,7 @@ class Text(Widget, XView, YView): window: bool = ..., ) -> None: ... def edit(self, *args): # docstring says "Internal method" - """ - Internal method + """Internal method This method controls the undo mechanism and the modified flag. The exact behavior of the @@ -6206,8 +5571,7 @@ class Text(Widget, XView, YView): @overload def edit_modified(self, arg: None = None) -> bool: # actually returns Literal[0, 1] - """ - Get or Set the modified flag + """Get or Set the modified flag If arg is not specified, returns the modified flag of the widget. The insert, delete, edit undo and @@ -6219,8 +5583,7 @@ class Text(Widget, XView, YView): @overload def edit_modified(self, arg: bool) -> None: ... # actually returns empty string def edit_redo(self) -> None: # actually returns empty string - """ - Redo the last undone edit + """Redo the last undone edit When the undo option is true, reapplies the last undone edits provided no other edits were done since @@ -6229,20 +5592,16 @@ class Text(Widget, XView, YView): """ def edit_reset(self) -> None: # actually returns empty string - """ - Clears the undo and redo stacks - """ + """Clears the undo and redo stacks""" def edit_separator(self) -> None: # actually returns empty string - """ - Inserts a separator (boundary) on the undo stack. + """Inserts a separator (boundary) on the undo stack. Does nothing when the undo option is false """ def edit_undo(self) -> None: # actually returns empty string - """ - Undoes the last edit action + """Undoes the last edit action If the undo option is true. An edit action is defined as all the insert and delete commands that are recorded @@ -6252,15 +5611,11 @@ class Text(Widget, XView, YView): """ def get(self, index1: _TextIndex, index2: _TextIndex | None = None) -> str: - """ - Return the text from INDEX1 to INDEX2 (not included). - """ + """Return the text from INDEX1 to INDEX2 (not included).""" @overload def image_cget(self, index: _TextIndex, option: Literal["image", "name"]) -> str: - """ - Return the value of OPTION of an embedded image at INDEX. - """ + """Return the value of OPTION of an embedded image at INDEX.""" @overload def image_cget(self, index: _TextIndex, option: Literal["padx", "pady"]) -> int: ... @@ -6270,9 +5625,7 @@ class Text(Widget, XView, YView): def image_cget(self, index: _TextIndex, option: str) -> Any: ... @overload def image_configure(self, index: _TextIndex, cnf: str) -> tuple[str, str, str, str, str | int]: - """ - Configure an embedded image at INDEX. - """ + """Configure an embedded image at INDEX.""" @overload def image_configure( @@ -6297,77 +5650,56 @@ class Text(Widget, XView, YView): padx: _ScreenUnits = ..., pady: _ScreenUnits = ..., ) -> str: - """ - Create an embedded image at INDEX. - """ + """Create an embedded image at INDEX.""" def image_names(self) -> tuple[str, ...]: - """ - Return all names of embedded images in this widget. - """ + """Return all names of embedded images in this widget.""" def index(self, index: _TextIndex) -> str: - """ - Return the index in the form line.char for INDEX. - """ + """Return the index in the form line.char for INDEX.""" def insert(self, index: _TextIndex, chars: str, *args: str | list[str] | tuple[str, ...]) -> None: - """ - Insert CHARS before the characters at INDEX. An additional + """Insert CHARS before the characters at INDEX. An additional tag can be given in ARGS. Additional CHARS and tags can follow in ARGS. """ @overload def mark_gravity(self, markName: str, direction: None = None) -> Literal["left", "right"]: - """ - Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT). + """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT). Return the current value if None is given for DIRECTION. """ @overload def mark_gravity(self, markName: str, direction: Literal["left", "right"]) -> None: ... # actually returns empty string def mark_names(self) -> tuple[str, ...]: - """ - Return all mark names. - """ + """Return all mark names.""" def mark_set(self, markName: str, index: _TextIndex) -> None: - """ - Set mark MARKNAME before the character at INDEX. - """ + """Set mark MARKNAME before the character at INDEX.""" def mark_unset(self, *markNames: str) -> None: - """ - Delete all marks in MARKNAMES. - """ + """Delete all marks in MARKNAMES.""" def mark_next(self, index: _TextIndex) -> str | None: - """ - Return the name of the next mark after INDEX. - """ + """Return the name of the next mark after INDEX.""" def mark_previous(self, index: _TextIndex) -> str | None: - """ - Return the name of the previous mark before INDEX. - """ + """Return the name of the previous mark before INDEX.""" # **kw of peer_create is same as the kwargs of Text.__init__ def peer_create(self, newPathName: str | Text, cnf: dict[str, Any] = {}, **kw) -> None: - """ - Creates a peer text widget with the given newPathName, and any + """Creates a peer text widget with the given newPathName, and any optional standard configuration options. By default the peer will have the same start and end line as the parent widget, but these can be overridden with the standard configuration options. """ def peer_names(self) -> tuple[_tkinter.Tcl_Obj, ...]: - """ - Returns a list of peers of this widget (this does not include + """Returns a list of peers of this widget (this does not include the widget itself). """ def replace(self, index1: _TextIndex, index2: _TextIndex, chars: str, *args: str | list[str] | tuple[str, ...]) -> None: - """ - Replaces the range of characters between index1 and index2 with + """Replaces the range of characters between index1 and index2 with the given characters and tags specified by args. See the method insert for some more information about args, and the @@ -6375,13 +5707,10 @@ class Text(Widget, XView, YView): """ def scan_mark(self, x: int, y: int) -> None: - """ - Remember the current X, Y coordinates. - """ + """Remember the current X, Y coordinates.""" def scan_dragto(self, x: int, y: int) -> None: - """ - Adjust the view of the text to 10 times the + """Adjust the view of the text to 10 times the difference between X and Y and the coordinates given in scan_mark. """ @@ -6399,20 +5728,16 @@ class Text(Widget, XView, YView): count: Variable | None = None, elide: bool | None = None, ) -> str: # returns empty string for not found - """ - Search PATTERN beginning from INDEX until STOPINDEX. + """Search PATTERN beginning from INDEX until STOPINDEX. Return the index of the first character of a match or an empty string. """ def see(self, index: _TextIndex) -> None: - """ - Scroll such that the character at INDEX is visible. - """ + """Scroll such that the character at INDEX is visible.""" def tag_add(self, tagName: str, index1: _TextIndex, *args: _TextIndex) -> None: - """ - Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS. + """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS. Additional pairs of indices may follow in ARGS. """ # tag_bind stuff is very similar to Canvas @@ -6424,8 +5749,7 @@ class Text(Widget, XView, YView): func: Callable[[Event[Text]], object] | None, add: Literal["", "+"] | bool | None = None, ) -> str: - """ - Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC. + """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will @@ -6435,15 +5759,12 @@ class Text(Widget, XView, YView): @overload def tag_bind(self, tagName: str, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... def tag_unbind(self, tagName: str, sequence: str, funcid: str | None = None) -> None: - """ - Unbind for all characters with TAGNAME for event SEQUENCE the + """Unbind for all characters with TAGNAME for event SEQUENCE the function identified with FUNCID. """ # allowing any string for cget instead of just Literals because there's no other way to look up tag options def tag_cget(self, tagName: str, option: str): - """ - Return the value of OPTION for tag TAGNAME. - """ + """Return the value of OPTION for tag TAGNAME.""" @overload def tag_configure( @@ -6480,64 +5801,48 @@ class Text(Widget, XView, YView): underlinefg: str = ..., wrap: Literal["none", "char", "word"] = ..., # be careful with "none" vs None ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure a tag TAGNAME. - """ + """Configure a tag TAGNAME.""" @overload def tag_configure(self, tagName: str, cnf: str) -> tuple[str, str, str, Any, Any]: ... tag_config = tag_configure def tag_delete(self, first_tag_name: str, /, *tagNames: str) -> None: # error if no tag names given - """ - Delete all tags in TAGNAMES. - """ + """Delete all tags in TAGNAMES.""" def tag_lower(self, tagName: str, belowThis: str | None = None) -> None: - """ - Change the priority of tag TAGNAME such that it is lower + """Change the priority of tag TAGNAME such that it is lower than the priority of BELOWTHIS. """ def tag_names(self, index: _TextIndex | None = None) -> tuple[str, ...]: - """ - Return a list of all tag names. - """ + """Return a list of all tag names.""" def tag_nextrange(self, tagName: str, index1: _TextIndex, index2: _TextIndex | None = None) -> tuple[str, str] | tuple[()]: - """ - Return a list of start and end index for the first sequence of + """Return a list of start and end index for the first sequence of characters between INDEX1 and INDEX2 which all have tag TAGNAME. The text is searched forward from INDEX1. """ def tag_prevrange(self, tagName: str, index1: _TextIndex, index2: _TextIndex | None = None) -> tuple[str, str] | tuple[()]: - """ - Return a list of start and end index for the first sequence of + """Return a list of start and end index for the first sequence of characters between INDEX1 and INDEX2 which all have tag TAGNAME. The text is searched backwards from INDEX1. """ def tag_raise(self, tagName: str, aboveThis: str | None = None) -> None: - """ - Change the priority of tag TAGNAME such that it is higher + """Change the priority of tag TAGNAME such that it is higher than the priority of ABOVETHIS. """ def tag_ranges(self, tagName: str) -> tuple[_tkinter.Tcl_Obj, ...]: - """ - Return a list of ranges of text which have tag TAGNAME. - """ + """Return a list of ranges of text which have tag TAGNAME.""" # tag_remove and tag_delete are different def tag_remove(self, tagName: str, index1: _TextIndex, index2: _TextIndex | None = None) -> None: - """ - Remove tag TAGNAME from all characters between INDEX1 and INDEX2. - """ + """Remove tag TAGNAME from all characters between INDEX1 and INDEX2.""" @overload def window_cget(self, index: _TextIndex, option: Literal["padx", "pady"]) -> int: - """ - Return the value of OPTION of an embedded window at INDEX. - """ + """Return the value of OPTION of an embedded window at INDEX.""" @overload def window_cget(self, index: _TextIndex, option: Literal["stretch"]) -> bool: ... # actually returns Literal[0, 1] @@ -6549,9 +5854,7 @@ class Text(Widget, XView, YView): def window_cget(self, index: _TextIndex, option: str) -> Any: ... @overload def window_configure(self, index: _TextIndex, cnf: str) -> tuple[str, str, str, str, str | int]: - """ - Configure an embedded window at INDEX. - """ + """Configure an embedded window at INDEX.""" @overload def window_configure( @@ -6579,33 +5882,23 @@ class Text(Widget, XView, YView): stretch: bool | Literal[0, 1] = ..., window: Misc | str = ..., ) -> None: - """ - Create a window at INDEX. - """ + """Create a window at INDEX.""" def window_names(self) -> tuple[str, ...]: - """ - Return all names of embedded windows in this widget. - """ + """Return all names of embedded windows in this widget.""" def yview_pickplace(self, *what): # deprecated - """ - Obsolete function, use see. - """ + """Obsolete function, use see.""" class _setit: - """ - Internal class. It wraps the command in the widget OptionMenu. - """ + """Internal class. It wraps the command in the widget OptionMenu.""" def __init__(self, var, value, callback=None) -> None: ... def __call__(self, *args) -> None: ... # manual page: tk_optionMenu class OptionMenu(Menubutton): - """ - OptionMenu which allows the user to select a value from a menu. - """ + """OptionMenu which allows the user to select a value from a menu.""" widgetName: Incomplete menuname: Incomplete @@ -6619,8 +5912,7 @@ class OptionMenu(Menubutton): # kwarg only from now on command: Callable[[StringVar], object] | None = ..., ) -> None: - """ - Construct an optionmenu widget with the parent MASTER, with + """Construct an optionmenu widget with the parent MASTER, with the resource textvariable set to VARIABLE, the initially selected value VALUE, the other menu values VALUES and an additional keyword argument command. @@ -6644,9 +5936,7 @@ class _BitmapImageLike(_Image): ... class _PhotoImageLike(_Image): ... class Image(_Image): - """ - Base class for images. - """ + """Base class for images.""" name: Incomplete tk: _tkinter.TkappType @@ -6657,14 +5947,10 @@ class Image(_Image): configure: Incomplete config: Incomplete def type(self): - """ - Return the type of the image, e.g. "photo" or "bitmap". - """ + """Return the type of the image, e.g. "photo" or "bitmap".""" class PhotoImage(Image, _PhotoImageLike): - """ - Widget which can display images in PGM, PPM, GIF, PNG format. - """ + """Widget which can display images in PGM, PPM, GIF, PNG format.""" # This should be kept in sync with PIL.ImageTK.PhotoImage.__init__() def __init__( @@ -6681,8 +5967,7 @@ class PhotoImage(Image, _PhotoImageLike): palette: int | str = ..., width: int = ..., ) -> None: - """ - Create an image with NAME. + """Create an image with NAME. Valid resource names: data, format, file, gamma, height, palette, width. @@ -6699,19 +5984,13 @@ class PhotoImage(Image, _PhotoImageLike): palette: int | str = ..., width: int = ..., ) -> None: - """ - Configure the image. - """ + """Configure the image.""" config = configure def blank(self) -> None: - """ - Display a transparent image. - """ + """Display a transparent image.""" def cget(self, option: str) -> str: - """ - Return the value of OPTION. - """ + """Return the value of OPTION.""" def __getitem__(self, key: str) -> str: ... # always string: image['height'] can be '0' if sys.version_info >= (3, 13): @@ -6722,8 +6001,7 @@ class PhotoImage(Image, _PhotoImageLike): zoom: int | tuple[int, int] | list[int] | None = None, subsample: int | tuple[int, int] | list[int] | None = None, ) -> PhotoImage: - """ - Return a new PhotoImage with the same image as this widget. + """Return a new PhotoImage with the same image as this widget. The FROM_COORDS option specifies a rectangular sub-region of the source image to be copied. It must be a tuple or a list of 1 to 4 @@ -6741,8 +6019,7 @@ class PhotoImage(Image, _PhotoImageLike): """ def subsample(self, x: int, y: Literal[""] = "", *, from_coords: Iterable[int] | None = None) -> PhotoImage: - """ - Return a new PhotoImage based on the same image as this widget + """Return a new PhotoImage based on the same image as this widget but use only every Xth or Yth pixel. If Y is not given, the default value is the same as X. @@ -6751,8 +6028,7 @@ class PhotoImage(Image, _PhotoImageLike): """ def zoom(self, x: int, y: Literal[""] = "", *, from_coords: Iterable[int] | None = None) -> PhotoImage: - """ - Return a new PhotoImage with the same image as this widget + """Return a new PhotoImage with the same image as this widget but zoom it with a factor of X in the X direction and Y in the Y direction. If Y is not given, the default value is the same as X. @@ -6772,8 +6048,7 @@ class PhotoImage(Image, _PhotoImageLike): # `None` defaults to overlay. compositingrule: Literal["overlay", "set"] | None = None, ) -> None: - """ - Copy a region from the source image (which must be a PhotoImage) to + """Copy a region from the source image (which must be a PhotoImage) to this image, possibly with pixel zooming and/or subsampling. If no options are specified, this command copies the whole of the source image into this image, starting at coordinates (0, 0). @@ -6816,8 +6091,7 @@ class PhotoImage(Image, _PhotoImageLike): """ else: def copy(self) -> PhotoImage: - """ - Return a new PhotoImage with the same image as this widget. + """Return a new PhotoImage with the same image as this widget. The FROM_COORDS option specifies a rectangular sub-region of the source image to be copied. It must be a tuple or a list of 1 to 4 @@ -6835,8 +6109,7 @@ class PhotoImage(Image, _PhotoImageLike): """ def zoom(self, x: int, y: int | Literal[""] = "") -> PhotoImage: - """ - Return a new PhotoImage with the same image as this widget + """Return a new PhotoImage with the same image as this widget but zoom it with a factor of X in the X direction and Y in the Y direction. If Y is not given, the default value is the same as X. @@ -6845,8 +6118,7 @@ class PhotoImage(Image, _PhotoImageLike): """ def subsample(self, x: int, y: int | Literal[""] = "") -> PhotoImage: - """ - Return a new PhotoImage based on the same image as this widget + """Return a new PhotoImage based on the same image as this widget but use only every Xth or Yth pixel. If Y is not given, the default value is the same as X. @@ -6855,9 +6127,7 @@ class PhotoImage(Image, _PhotoImageLike): """ def get(self, x: int, y: int) -> tuple[int, int, int]: - """ - Return the color (red, green, blue) of the pixel at X,Y. - """ + """Return the color (red, green, blue) of the pixel at X,Y.""" def put( self, @@ -6873,8 +6143,7 @@ class PhotoImage(Image, _PhotoImageLike): ), to: tuple[int, int] | tuple[int, int, int, int] | None = None, ) -> None: - """ - Put row formatted colors to image starting from + """Put row formatted colors to image starting from position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6)) """ if sys.version_info >= (3, 13): @@ -6887,8 +6156,7 @@ class PhotoImage(Image, _PhotoImageLike): to: Iterable[int] | None = None, shrink: bool = False, ) -> None: - """ - Reads image data from the file named FILENAME into the image. + """Reads image data from the file named FILENAME into the image. The FORMAT option specifies the format of the image data in the file. @@ -6919,8 +6187,7 @@ class PhotoImage(Image, _PhotoImageLike): background: str | None = None, grayscale: bool = False, ) -> None: - """ - Writes image data from the image to a file named FILENAME. + """Writes image data from the image to a file named FILENAME. The FORMAT option specifies the name of the image file format handler to be used to write the data to the file. If this option @@ -6946,8 +6213,7 @@ class PhotoImage(Image, _PhotoImageLike): def data( self, format: str, *, from_coords: Iterable[int] | None = None, background: str | None = None, grayscale: bool = False ) -> bytes: - """ - Returns image data. + """Returns image data. The FORMAT option specifies the name of the image file format handler to be used. If this option is not given, this method uses @@ -6985,8 +6251,7 @@ class PhotoImage(Image, _PhotoImageLike): else: def write(self, filename: StrOrBytesPath, format: str | None = None, from_coords: tuple[int, int] | None = None) -> None: - """ - Writes image data from the image to a file named FILENAME. + """Writes image data from the image to a file named FILENAME. The FORMAT option specifies the name of the image file format handler to be used to write the data to the file. If this option @@ -7009,19 +6274,13 @@ class PhotoImage(Image, _PhotoImageLike): """ def transparency_get(self, x: int, y: int) -> bool: - """ - Return True if the pixel at x,y is transparent. - """ + """Return True if the pixel at x,y is transparent.""" def transparency_set(self, x: int, y: int, boolean: bool) -> None: - """ - Set the transparency of the pixel at x,y. - """ + """Set the transparency of the pixel at x,y.""" class BitmapImage(Image, _BitmapImageLike): - """ - Widget which can display images in XBM format. - """ + """Widget which can display images in XBM format.""" # This should be kept in sync with PIL.ImageTK.BitmapImage.__init__() def __init__( @@ -7037,8 +6296,7 @@ class BitmapImage(Image, _BitmapImageLike): maskdata: str = ..., maskfile: StrOrBytesPath = ..., ) -> None: - """ - Create a bitmap with NAME. + """Create a bitmap with NAME. Valid resource names: background, data, file, foreground, maskdata, maskfile. """ @@ -7047,9 +6305,7 @@ def image_names() -> tuple[str, ...]: ... def image_types() -> tuple[str, ...]: ... class Spinbox(Widget, XView): - """ - spinbox widget. - """ + """spinbox widget.""" def __init__( self, @@ -7109,8 +6365,7 @@ class Spinbox(Widget, XView): wrap: bool = False, xscrollcommand: _XYScrollCommand = "", ) -> None: - """ - Construct a spinbox widget with the parent MASTER. + """Construct a spinbox widget with the parent MASTER. STANDARD OPTIONS @@ -7193,8 +6448,7 @@ class Spinbox(Widget, XView): wrap: bool = ..., xscrollcommand: _XYScrollCommand = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -7205,8 +6459,7 @@ class Spinbox(Widget, XView): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def bbox(self, index) -> tuple[int, int, int, int] | None: # type: ignore[override] - """ - Return a tuple of X1,Y1,X2,Y2 coordinates for a + """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle which encloses the character given by index. The first two elements of the list give the x and y @@ -7219,8 +6472,7 @@ class Spinbox(Widget, XView): """ def delete(self, first, last=None) -> Literal[""]: - """ - Delete one or more elements of the spinbox. + """Delete one or more elements of the spinbox. First is the index of the first character to delete, and last is the index of the character just after @@ -7230,53 +6482,42 @@ class Spinbox(Widget, XView): """ def get(self) -> str: - """ - Returns the spinbox's string - """ + """Returns the spinbox's string""" def icursor(self, index): - """ - Alter the position of the insertion cursor. + """Alter the position of the insertion cursor. The insertion cursor will be displayed just before the character given by index. Returns an empty string """ def identify(self, x: int, y: int) -> Literal["", "buttondown", "buttonup", "entry"]: - """ - Returns the name of the widget at position x, y + """Returns the name of the widget at position x, y Return value is one of: none, buttondown, buttonup, entry """ def index(self, index: str | int) -> int: - """ - Returns the numerical index corresponding to index - """ + """Returns the numerical index corresponding to index""" def insert(self, index: str | int, s: str) -> Literal[""]: - """ - Insert string s at index + """Insert string s at index Returns an empty string. """ # spinbox.invoke("asdf") gives error mentioning .invoke("none"), but it's not documented def invoke(self, element: Literal["none", "buttonup", "buttondown"]) -> Literal[""]: - """ - Causes the specified element to be invoked + """Causes the specified element to be invoked The element could be buttondown or buttonup triggering the action associated with it. """ def scan(self, *args): - """ - Internal function. - """ + """Internal function.""" def scan_mark(self, x): - """ - Records x and the current view in the spinbox window; + """Records x and the current view in the spinbox window; used in conjunction with later scan dragto commands. Typically this command is associated with a mouse button @@ -7284,8 +6525,7 @@ class Spinbox(Widget, XView): """ def scan_dragto(self, x): - """ - Compute the difference between the given x argument + """Compute the difference between the given x argument and the x argument to the last scan mark command It then adjusts the view left or right by 10 times the @@ -7296,13 +6536,10 @@ class Spinbox(Widget, XView): """ def selection(self, *args) -> tuple[int, ...]: - """ - Internal function. - """ + """Internal function.""" def selection_adjust(self, index): - """ - Locate the end of the selection nearest to the character + """Locate the end of the selection nearest to the character given by index, Then adjust that end of the selection to be at index @@ -7315,46 +6552,35 @@ class Spinbox(Widget, XView): """ def selection_clear(self): # type: ignore[override] - """ - Clear the selection + """Clear the selection If the selection isn't in this widget then the command has no effect. """ def selection_element(self, element=None): - """ - Sets or gets the currently selected element. + """Sets or gets the currently selected element. If a spinbutton element is specified, it will be displayed depressed. """ def selection_from(self, index: int) -> None: - """ - Set the fixed end of a selection to INDEX. - """ + """Set the fixed end of a selection to INDEX.""" def selection_present(self) -> None: - """ - Return True if there are characters selected in the spinbox, False + """Return True if there are characters selected in the spinbox, False otherwise. """ def selection_range(self, start: int, end: int) -> None: - """ - Set the selection from START to END (not included). - """ + """Set the selection from START to END (not included).""" def selection_to(self, index: int) -> None: - """ - Set the variable end of a selection to INDEX. - """ + """Set the variable end of a selection to INDEX.""" class LabelFrame(Widget): - """ - labelframe widget. - """ + """labelframe widget.""" def __init__( self, @@ -7389,8 +6615,7 @@ class LabelFrame(Widget): visual: str | tuple[str, int] = "", # can't be changed with configure() width: _ScreenUnits = 0, ) -> None: - """ - Construct a labelframe widget with the parent MASTER. + """Construct a labelframe widget with the parent MASTER. STANDARD OPTIONS @@ -7433,8 +6658,7 @@ class LabelFrame(Widget): text: float | str = ..., width: _ScreenUnits = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -7446,9 +6670,7 @@ class LabelFrame(Widget): config = configure class PanedWindow(Widget): - """ - panedwindow widget. - """ + """panedwindow widget.""" def __init__( self, @@ -7478,8 +6700,7 @@ class PanedWindow(Widget): showhandle: bool = False, width: _ScreenUnits = "", ) -> None: - """ - Construct a panedwindow widget with the parent MASTER. + """Construct a panedwindow widget with the parent MASTER. STANDARD OPTIONS @@ -7520,8 +6741,7 @@ class PanedWindow(Widget): showhandle: bool = ..., width: _ScreenUnits = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -7532,8 +6752,7 @@ class PanedWindow(Widget): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def add(self, child: Widget, **kw) -> None: - """ - Add a child widget to the panedwindow in a new pane. + """Add a child widget to the panedwindow in a new pane. The child argument is the name of the child widget followed by pairs of arguments that specify how to @@ -7542,15 +6761,13 @@ class PanedWindow(Widget): """ def remove(self, child) -> None: - """ - Remove the pane containing child from the panedwindow + """Remove the pane containing child from the panedwindow All geometry management options for child will be forgotten. """ forget: Incomplete def identify(self, x: int, y: int): - """ - Identify the panedwindow component at point x, y + """Identify the panedwindow component at point x, y If the point is over a sash or a sash handle, the result is a two element list containing the index of the sash or @@ -7561,33 +6778,22 @@ class PanedWindow(Widget): """ def proxy(self, *args): - """ - Internal function. - """ + """Internal function.""" def proxy_coord(self): - """ - Return the x and y pair of the most recent proxy location - """ + """Return the x and y pair of the most recent proxy location""" def proxy_forget(self): - """ - Remove the proxy from the display. - """ + """Remove the proxy from the display.""" def proxy_place(self, x, y): - """ - Place the proxy at the given x and y coordinates. - """ + """Place the proxy at the given x and y coordinates.""" def sash(self, *args): - """ - Internal function. - """ + """Internal function.""" def sash_coord(self, index): - """ - Return the current x and y pair for the sash given by index. + """Return the current x and y pair for the sash given by index. Index must be an integer between 0 and 1 less than the number of panes in the panedwindow. The coordinates given are @@ -7600,27 +6806,22 @@ class PanedWindow(Widget): """ def sash_mark(self, index): - """ - Records x and y for the sash given by index; + """Records x and y for the sash given by index; Used in conjunction with later dragto commands to move the sash. """ def sash_place(self, index, x, y): - """ - Place the sash given by index at the given coordinates - """ + """Place the sash given by index at the given coordinates""" def panecget(self, child, option): - """ - Query a management option for window. + """Query a management option for window. Option may be any value allowed by the paneconfigure subcommand """ def paneconfigure(self, tagOrId, cnf=None, **kw): - """ - Query or modify the management options for window. + """Query or modify the management options for window. If no option is specified, returns a list describing all of the available options for pathName. If option is @@ -7688,8 +6889,6 @@ class PanedWindow(Widget): """ paneconfig: Incomplete def panes(self): - """ - Returns an ordered list of the child panes. - """ + """Returns an ordered list of the child panes.""" def _test() -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/colorchooser.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/colorchooser.pyi index fa02200fcb..22a917d210 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/colorchooser.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/colorchooser.pyi @@ -5,8 +5,7 @@ from typing import ClassVar __all__ = ["Chooser", "askcolor"] class Chooser(Dialog): - """ - Create a dialog for the tk_chooseColor command. + """Create a dialog for the tk_chooseColor command. Args: master: The master widget for this dialog. If not provided, @@ -26,8 +25,7 @@ class Chooser(Dialog): def askcolor( color: str | bytes | None = None, *, initialcolor: str = ..., parent: Misc = ..., title: str = ... ) -> tuple[None, None] | tuple[tuple[int, int, int], str]: - """ - Display dialog window for selection of a color. + """Display dialog window for selection of a color. Convenience wrapper for the Chooser class. Displays the color chooser dialog with color as the initial value. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/filedialog.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/filedialog.pyi index 99e930a5c1..600b735f10 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/filedialog.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/filedialog.pyi @@ -37,8 +37,7 @@ __all__ = [ dialogstates: dict[Hashable, tuple[str, str]] class FileDialog: - """ - Standard file selection dialog -- no checks on selected file. + """Standard file selection dialog -- no checks on selected file. Usage: @@ -93,17 +92,13 @@ class FileDialog: def set_selection(self, file: StrPath) -> None: ... class LoadFileDialog(FileDialog): - """ - File selection dialog which checks that the file exists. - """ + """File selection dialog which checks that the file exists.""" title: str def ok_command(self) -> None: ... class SaveFileDialog(FileDialog): - """ - File selection dialog which checks that the file may be created. - """ + """File selection dialog which checks that the file may be created.""" title: str def ok_command(self) -> None: ... @@ -111,23 +106,17 @@ class SaveFileDialog(FileDialog): class _Dialog(commondialog.Dialog): ... class Open(_Dialog): - """ - Ask for a filename to open - """ + """Ask for a filename to open""" command: ClassVar[str] class SaveAs(_Dialog): - """ - Ask for a filename to save as - """ + """Ask for a filename to save as""" command: ClassVar[str] class Directory(commondialog.Dialog): - """ - Ask for a directory - """ + """Ask for a directory""" command: ClassVar[str] @@ -143,9 +132,7 @@ def asksaveasfilename( title: str | None = ..., typevariable: StringVar | str | None = ..., ) -> str: # can be empty string - """ - Ask for a filename to save as - """ + """Ask for a filename to save as""" def askopenfilename( *, @@ -157,9 +144,7 @@ def askopenfilename( title: str | None = ..., typevariable: StringVar | str | None = ..., ) -> str: # can be empty string - """ - Ask for a filename to open - """ + """Ask for a filename to open""" def askopenfilenames( *, @@ -171,8 +156,7 @@ def askopenfilenames( title: str | None = ..., typevariable: StringVar | str | None = ..., ) -> Literal[""] | tuple[str, ...]: - """ - Ask for multiple filenames to open + """Ask for multiple filenames to open Returns a list of filenames or empty list if cancel button selected @@ -181,9 +165,7 @@ def askopenfilenames( def askdirectory( *, initialdir: StrOrBytesPath | None = ..., mustexist: bool | None = False, parent: Misc | None = ..., title: str | None = ... ) -> str: # can be empty string - """ - Ask for a directory, and return the file name - """ + """Ask for a directory, and return the file name""" # TODO: If someone actually uses these, overload to have the actual return type of open(..., mode) def asksaveasfile( @@ -198,9 +180,7 @@ def asksaveasfile( title: str | None = ..., typevariable: StringVar | str | None = ..., ) -> IO[Incomplete] | None: - """ - Ask for a filename to save as, and returned the opened file - """ + """Ask for a filename to save as, and returned the opened file""" def askopenfile( mode: str = "r", @@ -213,9 +193,7 @@ def askopenfile( title: str | None = ..., typevariable: StringVar | str | None = ..., ) -> IO[Incomplete] | None: - """ - Ask for a filename to open, and returned the opened file - """ + """Ask for a filename to open, and returned the opened file""" def askopenfiles( mode: str = "r", @@ -228,8 +206,7 @@ def askopenfiles( title: str | None = ..., typevariable: StringVar | str | None = ..., ) -> tuple[IO[Incomplete], ...]: # can be empty tuple - """ - Ask for multiple filenames and return the open file + """Ask for multiple filenames and return the open file objects returns a list of open file objects or an empty list if @@ -237,6 +214,4 @@ def askopenfiles( """ def test() -> None: - """ - Simple test program. - """ + """Simple test program.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/font.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/font.pyi index 28a3dd7b47..b963749045 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/font.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/font.pyi @@ -38,8 +38,7 @@ class _MetricsDict(TypedDict): fixed: bool class Font: - """ - Represents a named font. + """Represents a named font. Constructor options are: @@ -82,9 +81,7 @@ class Font: def __setitem__(self, key: str, value: Any) -> None: ... @overload def cget(self, option: Literal["family"]) -> str: - """ - Get font attribute - """ + """Get font attribute""" @overload def cget(self, option: Literal["size"]) -> int: ... @@ -99,9 +96,7 @@ class Font: __getitem__ = cget @overload def actual(self, option: Literal["family"], displayof: tkinter.Misc | None = None) -> str: - """ - Return actual font attributes - """ + """Return actual font attributes""" @overload def actual(self, option: Literal["size"], displayof: tkinter.Misc | None = None) -> int: ... @@ -125,19 +120,14 @@ class Font: underline: bool = ..., overstrike: bool = ..., ) -> _FontDict | None: - """ - Modify font attributes - """ + """Modify font attributes""" configure = config def copy(self) -> Font: - """ - Return a distinct copy of the current font - """ + """Return a distinct copy of the current font""" @overload def metrics(self, option: Literal["ascent", "descent", "linespace"], /, *, displayof: tkinter.Misc | None = ...) -> int: - """ - Return font metrics. + """Return font metrics. For best performance, create a dummy widget using this font before calling this method. @@ -148,31 +138,21 @@ class Font: @overload def metrics(self, *, displayof: tkinter.Misc | None = ...) -> _MetricsDict: ... def measure(self, text: str, displayof: tkinter.Misc | None = None) -> int: - """ - Return text width - """ + """Return text width""" def __eq__(self, other: object) -> bool: ... def __del__(self) -> None: ... def families(root: tkinter.Misc | None = None, displayof: tkinter.Misc | None = None) -> tuple[str, ...]: - """ - Get font families (as a tuple) - """ + """Get font families (as a tuple)""" def names(root: tkinter.Misc | None = None) -> tuple[str, ...]: - """ - Get names of defined fonts (as a tuple) - """ + """Get names of defined fonts (as a tuple)""" if sys.version_info >= (3, 10): def nametofont(name: str, root: tkinter.Misc | None = None) -> Font: - """ - Given the name of a tk named font, returns a Font representation. - """ + """Given the name of a tk named font, returns a Font representation.""" else: def nametofont(name: str) -> Font: - """ - Given the name of a tk named font, returns a Font representation. - """ + """Given the name of a tk named font, returns a Font representation.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/messagebox.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/messagebox.pyi index a593364ee3..c92e23f7b0 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/messagebox.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/messagebox.pyi @@ -22,9 +22,7 @@ YES: Final = "yes" NO: Final = "no" class Message(Dialog): - """ - A message box - """ + """A message box""" command: ClassVar[str] @@ -37,9 +35,7 @@ def showinfo( default: Literal["ok"] = ..., parent: Misc = ..., ) -> str: - """ - Show an info message - """ + """Show an info message""" def showwarning( title: str | None = None, @@ -50,9 +46,7 @@ def showwarning( default: Literal["ok"] = ..., parent: Misc = ..., ) -> str: - """ - Show a warning message - """ + """Show a warning message""" def showerror( title: str | None = None, @@ -63,9 +57,7 @@ def showerror( default: Literal["ok"] = ..., parent: Misc = ..., ) -> str: - """ - Show an error message - """ + """Show an error message""" def askquestion( title: str | None = None, @@ -76,9 +68,7 @@ def askquestion( default: Literal["yes", "no"] = ..., parent: Misc = ..., ) -> str: - """ - Ask a question - """ + """Ask a question""" def askokcancel( title: str | None = None, @@ -89,9 +79,7 @@ def askokcancel( default: Literal["ok", "cancel"] = ..., parent: Misc = ..., ) -> bool: - """ - Ask if operation should proceed; return true if the answer is ok - """ + """Ask if operation should proceed; return true if the answer is ok""" def askyesno( title: str | None = None, @@ -102,9 +90,7 @@ def askyesno( default: Literal["yes", "no"] = ..., parent: Misc = ..., ) -> bool: - """ - Ask a question; return true if the answer is yes - """ + """Ask a question; return true if the answer is yes""" def askyesnocancel( title: str | None = None, @@ -115,9 +101,7 @@ def askyesnocancel( default: Literal["cancel", "yes", "no"] = ..., parent: Misc = ..., ) -> bool | None: - """ - Ask a question; return true if the answer is yes, None if cancelled. - """ + """Ask a question; return true if the answer is yes, None if cancelled.""" def askretrycancel( title: str | None = None, @@ -128,6 +112,4 @@ def askretrycancel( default: Literal["retry", "cancel"] = ..., parent: Misc = ..., ) -> bool: - """ - Ask if operation should be retried; return true if the answer is yes - """ + """Ask if operation should be retried; return true if the answer is yes""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/simpledialog.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/simpledialog.pyi index da5b86b1d5..f98725caa2 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/simpledialog.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/simpledialog.pyi @@ -17,15 +17,13 @@ askstring -- get a string from the user from tkinter import Event, Frame, Misc, Toplevel class Dialog(Toplevel): - """ - Class to open dialogs. + """Class to open dialogs. This class is intended as a base class for custom dialogs """ def __init__(self, parent: Misc | None, title: str | None = None) -> None: - """ - Initialize a dialog. + """Initialize a dialog. Arguments: @@ -35,8 +33,7 @@ class Dialog(Toplevel): """ def body(self, master: Frame) -> Misc | None: - """ - create dialog body. + """create dialog body. return widget that should have initial focus. This method should be overridden, and is called @@ -44,8 +41,7 @@ class Dialog(Toplevel): """ def buttonbox(self) -> None: - """ - add standard button box. + """add standard button box. override if you do not want the standard buttons """ @@ -53,16 +49,14 @@ class Dialog(Toplevel): def ok(self, event: Event[Misc] | None = None) -> None: ... def cancel(self, event: Event[Misc] | None = None) -> None: ... def validate(self) -> bool: - """ - validate the data + """validate the data This method is called automatically to validate the data before the dialog is destroyed. By default, it always validates OK. """ def apply(self) -> None: - """ - process the data + """process the data This method is called automatically to process the data, *after* the dialog is destroyed. By default, it does nothing. @@ -93,8 +87,7 @@ def askfloat( maxvalue: float | None = ..., parent: Misc | None = ..., ) -> float | None: - """ - get a float from the user + """get a float from the user Arguments: @@ -114,8 +107,7 @@ def askinteger( maxvalue: int | None = ..., parent: Misc | None = ..., ) -> int | None: - """ - get an integer from the user + """get an integer from the user Arguments: @@ -135,8 +127,7 @@ def askstring( # minvalue/maxvalue is accepted but not useful. parent: Misc | None = ..., ) -> str | None: - """ - get a string from the user + """get a string from the user Arguments: diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/tix.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/tix.pyi index 0e6610e4df..e8e383809e 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/tix.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/tix.pyi @@ -35,8 +35,7 @@ TCL_IDLE_EVENTS: Final = 32 TCL_ALL_EVENTS: Final = 0 class tixCommand: - """ - The tix commands provide access to miscellaneous elements + """The tix commands provide access to miscellaneous elements of Tix's internal state and the Tix application context. Most of the information manipulated by these commands pertains to the application as a whole, or to a screen or @@ -47,8 +46,7 @@ class tixCommand: """ def tix_addbitmapdir(self, directory: str) -> None: - """ - Tix maintains a list of directories under which + """Tix maintains a list of directories under which the tix_getimage and tix_getbitmap commands will search for image files. The standard bitmap directory is $TIX_LIBRARY/bitmaps. The addbitmapdir command @@ -59,15 +57,13 @@ class tixCommand: """ def tix_cget(self, option: str) -> Any: - """ - Returns the current value of the configuration + """Returns the current value of the configuration option given by option. Option may be any of the options described in the CONFIGURATION OPTIONS section. """ def tix_configure(self, cnf: dict[str, Any] | None = None, **kw: Any) -> Any: - """ - Query or modify the configuration options of the Tix application + """Query or modify the configuration options of the Tix application context. If no option is specified, returns a dictionary all of the available options. If option is specified with no value, then the command returns a list describing the one named option (this list @@ -79,8 +75,7 @@ class tixCommand: """ def tix_filedialog(self, dlgclass: str | None = None) -> str: - """ - Returns the file selection dialog that may be shared among + """Returns the file selection dialog that may be shared among different calls from this application. This command will create a file selection dialog widget when it is called the first time. This dialog will be returned by all subsequent calls to tix_filedialog. @@ -90,8 +85,7 @@ class tixCommand: """ def tix_getbitmap(self, name: str) -> str: - """ - Locates a bitmap file of the name name.xpm or name in one of the + """Locates a bitmap file of the name name.xpm or name in one of the bitmap directories (see the tix_addbitmapdir command above). By using tix_getbitmap, you can avoid hard coding the pathnames of the bitmap files in your application. When successful, it returns the @@ -101,8 +95,7 @@ class tixCommand: """ def tix_getimage(self, name: str) -> str: - """ - Locates an image file of the name name.xpm, name.xbm or name.ppm + """Locates an image file of the name name.xpm, name.xbm or name.ppm in one of the bitmap directories (see the addbitmapdir command above). If more than one file with the same name (but different extensions) exist, then the image type is chosen according to the @@ -115,8 +108,7 @@ class tixCommand: """ def tix_option_get(self, name: str) -> Any: - """ - Gets the options maintained by the Tix + """Gets the options maintained by the Tix scheme mechanism. Available options include: active_bg active_fg bg @@ -131,8 +123,7 @@ class tixCommand: """ def tix_resetoptions(self, newScheme: str, newFontSet: str, newScmPrio: str | None = None) -> None: - """ - Resets the scheme and fontset of the Tix application to + """Resets the scheme and fontset of the Tix application to newScheme and newFontSet, respectively. This affects only those widgets created after this call. Therefore, it is best to call the resetoptions command before the creation of any widgets in a Tix @@ -148,16 +139,14 @@ class tixCommand: """ class Tk(tkinter.Tk, tixCommand): - """ - Toplevel widget of Tix which represents mostly the main window + """Toplevel widget of Tix which represents mostly the main window of an application. It has an associated Tcl interpreter. """ def __init__(self, screenName: str | None = None, baseName: str | None = None, className: str = "Tix") -> None: ... class TixWidget(tkinter.Widget): - """ - A TixWidget class is used to package all (or most) Tix widgets. + """A TixWidget class is used to package all (or most) Tix widgets. Widget initialization is extended in two ways: 1) It is possible to give a list of options which must be part of @@ -180,32 +169,24 @@ class TixWidget(tkinter.Widget): ) -> None: ... def __getattr__(self, name: str): ... def set_silent(self, value: str) -> None: - """ - Set a variable without calling its action routine - """ + """Set a variable without calling its action routine""" def subwidget(self, name: str) -> tkinter.Widget: - """ - Return the named subwidget (which must have been created by + """Return the named subwidget (which must have been created by the sub-class). """ def subwidgets_all(self) -> list[tkinter.Widget]: - """ - Return all subwidgets. - """ + """Return all subwidgets.""" def config_all(self, option: Any, value: Any) -> None: - """ - Set configuration options for all subwidgets (and self). - """ + """Set configuration options for all subwidgets (and self).""" def image_create(self, imgtype: str, cnf: dict[str, Any] = {}, master: tkinter.Widget | None = None, **kw) -> None: ... def image_delete(self, imgname: str) -> None: ... class TixSubWidget(TixWidget): - """ - Subwidget class. + """Subwidget class. This is used to mirror child widgets automatically created by Tix/Tk as part of a mega-widget in Python (which is not informed @@ -215,8 +196,7 @@ class TixSubWidget(TixWidget): def __init__(self, master: tkinter.Widget, name: str, destroy_physically: int = 1, check_intermediate: int = 1) -> None: ... class DisplayStyle: - """ - DisplayStyle - handle configuration options shared by + """DisplayStyle - handle configuration options shared by (multiple) Display Items """ @@ -227,8 +207,7 @@ class DisplayStyle: def config(self, cnf: dict[str, Any] = {}, **kw): ... class Balloon(TixWidget): - """ - Balloon help widget. + """Balloon help widget. Subwidget Class --------- ----- @@ -238,30 +217,25 @@ class Balloon(TixWidget): def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... def bind_widget(self, widget: tkinter.Widget, cnf: dict[str, Any] = {}, **kw) -> None: - """ - Bind balloon widget to another. + """Bind balloon widget to another. One balloon widget may be bound to several widgets at the same time """ def unbind_widget(self, widget: tkinter.Widget) -> None: ... class ButtonBox(TixWidget): - """ - ButtonBox - A container for pushbuttons. + """ButtonBox - A container for pushbuttons. Subwidgets are the buttons added with the add method. """ def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... def add(self, name: str, cnf: dict[str, Any] = {}, **kw) -> tkinter.Widget: - """ - Add a button with given name to box. - """ + """Add a button with given name to box.""" def invoke(self, name: str) -> None: ... class ComboBox(TixWidget): - """ - ComboBox - an Entry field with a dropdown menu. The user can select a + """ComboBox - an Entry field with a dropdown menu. The user can select a choice by either typing in the entry subwidget or selecting from the listbox subwidget. @@ -281,8 +255,7 @@ class ComboBox(TixWidget): def pick(self, index: int) -> None: ... class Control(TixWidget): - """ - Control - An entry field with value change arrows. The user can + """Control - An entry field with value change arrows. The user can adjust the value by pressing the two arrow buttons or by entering the value directly into the entry. The new value will be checked against the user-defined upper and lower limits. @@ -301,8 +274,7 @@ class Control(TixWidget): def invoke(self) -> None: ... class LabelEntry(TixWidget): - """ - LabelEntry - Entry field with label. Packages an entry widget + """LabelEntry - Entry field with label. Packages an entry widget and a label into one mega widget. It can be used to simplify the creation of ``entry-form'' type of interface. @@ -315,8 +287,7 @@ class LabelEntry(TixWidget): def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... class LabelFrame(TixWidget): - """ - LabelFrame - Labelled Frame container. Packages a frame widget + """LabelFrame - Labelled Frame container. Packages a frame widget and a label into one mega widget. To create widgets inside a LabelFrame widget, one creates the new widgets relative to the frame subwidget and manage them inside the frame subwidget. @@ -330,16 +301,14 @@ class LabelFrame(TixWidget): def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... class Meter(TixWidget): - """ - The Meter widget can be used to show the progress of a background + """The Meter widget can be used to show the progress of a background job which may take a long time to execute. """ def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... class OptionMenu(TixWidget): - """ - OptionMenu - creates a menu button of options. + """OptionMenu - creates a menu button of options. Subwidget Class --------- ----- @@ -355,8 +324,7 @@ class OptionMenu(TixWidget): def enable(self, name: str) -> None: ... class PopupMenu(TixWidget): - """ - PopupMenu widget can be used as a replacement of the tk_popup command. + """PopupMenu widget can be used as a replacement of the tk_popup command. The advantage of the Tix PopupMenu widget is it requires less application code to manipulate. @@ -373,8 +341,7 @@ class PopupMenu(TixWidget): def post_widget(self, widget: tkinter.Widget, x: int, y: int) -> None: ... class Select(TixWidget): - """ - Select - Container of button subwidgets. It can be used to provide + """Select - Container of button subwidgets. It can be used to provide radio-box or check-box style of selection options for the user. Subwidgets are buttons added dynamically using the add method. @@ -385,16 +352,13 @@ class Select(TixWidget): def invoke(self, name: str) -> None: ... class StdButtonBox(TixWidget): - """ - StdButtonBox - Standard Button Box (OK, Apply, Cancel and Help) - """ + """StdButtonBox - Standard Button Box (OK, Apply, Cancel and Help)""" def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... def invoke(self, name: str) -> None: ... class DirList(TixWidget): - """ - DirList - displays a list view of a directory, its previous + """DirList - displays a list view of a directory, its previous directories and its sub-directories. The user can choose one of the directories displayed in the list or change to another directory. @@ -409,8 +373,7 @@ class DirList(TixWidget): def chdir(self, dir: str) -> None: ... class DirTree(TixWidget): - """ - DirTree - Directory Listing in a hierarchical view. + """DirTree - Directory Listing in a hierarchical view. Displays a tree view of a directory, its previous directories and its sub-directories. The user can choose one of the directories displayed in the list or change to another directory. @@ -426,8 +389,7 @@ class DirTree(TixWidget): def chdir(self, dir: str) -> None: ... class DirSelectDialog(TixWidget): - """ - The DirSelectDialog widget presents the directories in the file + """The DirSelectDialog widget presents the directories in the file system in a dialog window. The user can use this dialog window to navigate through the file system to select the desired directory. @@ -441,8 +403,7 @@ class DirSelectDialog(TixWidget): def popdown(self) -> None: ... class DirSelectBox(TixWidget): - """ - DirSelectBox - Motif style file select box. + """DirSelectBox - Motif style file select box. It is generally used for the user to choose a file. FileSelectBox stores the files mostly recently selected into a ComboBox widget so that they can be quickly @@ -459,8 +420,7 @@ class DirSelectBox(TixWidget): def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... class ExFileSelectBox(TixWidget): - """ - ExFileSelectBox - MS Windows style file select box. + """ExFileSelectBox - MS Windows style file select box. It provides a convenient method for the user to select files. Subwidget Class @@ -480,8 +440,7 @@ class ExFileSelectBox(TixWidget): def invoke(self) -> None: ... class FileSelectBox(TixWidget): - """ - ExFileSelectBox - Motif style file select box. + """ExFileSelectBox - Motif style file select box. It is generally used for the user to choose a file. FileSelectBox stores the files mostly recently selected into a ComboBox widget so that they can be quickly @@ -500,8 +459,7 @@ class FileSelectBox(TixWidget): def invoke(self) -> None: ... class FileEntry(TixWidget): - """ - FileEntry - Entry field with button that invokes a FileSelectDialog. + """FileEntry - Entry field with button that invokes a FileSelectDialog. The user can type in the filename manually. Alternatively, the user can press the button widget that sits next to the entry, which will bring up a file selection dialog. @@ -517,8 +475,7 @@ class FileEntry(TixWidget): def file_dialog(self) -> None: ... class HList(TixWidget, tkinter.XView, tkinter.YView): - """ - HList - Hierarchy display widget can be used to display any data + """HList - Hierarchy display widget can be used to display any data that have a hierarchical structure, for example, file system directory trees. The list entries are indented and connected by branch lines according to their places in the hierarchy. @@ -582,8 +539,7 @@ class HList(TixWidget, tkinter.XView, tkinter.YView): def show_entry(self, entry: str) -> None: ... class CheckList(TixWidget): - """ - The CheckList widget + """The CheckList widget displays a list of items to be selected by the user. CheckList acts similarly to the Tk checkbutton or radiobutton widgets, except it is capable of handling many more items than checkbuttons or radiobuttons. @@ -591,80 +547,60 @@ class CheckList(TixWidget): def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... def autosetmode(self) -> None: - """ - This command calls the setmode method for all the entries in this + """This command calls the setmode method for all the entries in this Tree widget: if an entry has no child entries, its mode is set to none. Otherwise, if the entry has any hidden child entries, its mode is set to open; otherwise its mode is set to close. """ def close(self, entrypath: str) -> None: - """ - Close the entry given by entryPath if its mode is close. - """ + """Close the entry given by entryPath if its mode is close.""" def getmode(self, entrypath: str) -> str: - """ - Returns the current mode of the entry given by entryPath. - """ + """Returns the current mode of the entry given by entryPath.""" def open(self, entrypath: str) -> None: - """ - Open the entry given by entryPath if its mode is open. - """ + """Open the entry given by entryPath if its mode is open.""" def getselection(self, mode: str = "on") -> tuple[str, ...]: - """ - Returns a list of items whose status matches status. If status is + """Returns a list of items whose status matches status. If status is not specified, the list of items in the "on" status will be returned. Mode can be on, off, default """ def getstatus(self, entrypath: str) -> str: - """ - Returns the current status of entryPath. - """ + """Returns the current status of entryPath.""" def setstatus(self, entrypath: str, mode: str = "on") -> None: - """ - Sets the status of entryPath to be status. A bitmap will be + """Sets the status of entryPath to be status. A bitmap will be displayed next to the entry its status is on, off or default. """ class Tree(TixWidget): - """ - Tree - The tixTree widget can be used to display hierarchical + """Tree - The tixTree widget can be used to display hierarchical data in a tree form. The user can adjust the view of the tree by opening or closing parts of the tree. """ def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... def autosetmode(self) -> None: - """ - This command calls the setmode method for all the entries in this + """This command calls the setmode method for all the entries in this Tree widget: if an entry has no child entries, its mode is set to none. Otherwise, if the entry has any hidden child entries, its mode is set to open; otherwise its mode is set to close. """ def close(self, entrypath: str) -> None: - """ - Close the entry given by entryPath if its mode is close. - """ + """Close the entry given by entryPath if its mode is close.""" def getmode(self, entrypath: str) -> str: - """ - Returns the current mode of the entry given by entryPath. - """ + """Returns the current mode of the entry given by entryPath.""" def open(self, entrypath: str) -> None: - """ - Open the entry given by entryPath if its mode is open. - """ + """Open the entry given by entryPath if its mode is open.""" def setmode(self, entrypath: str, mode: str = "none") -> None: - """ - This command is used to indicate whether the entry given by + """This command is used to indicate whether the entry given by entryPath has children entries and whether the children are visible. mode must be one of open, close or none. If mode is set to open, a (+) indicator is drawn next the entry. If mode is set to close, a (-) @@ -676,8 +612,7 @@ class Tree(TixWidget): """ class TList(TixWidget, tkinter.XView, tkinter.YView): - """ - TList - Hierarchy display widget which can be + """TList - Hierarchy display widget which can be used to display data in a tabular format. The list entries of a TList widget are similar to the entries in the Tk listbox widget. The main differences are (1) the TList widget can display the list entries in a @@ -713,8 +648,7 @@ class TList(TixWidget, tkinter.XView, tkinter.YView): def selection_set(self, first: int, last: int | None = None) -> None: ... class PanedWindow(TixWidget): - """ - PanedWindow - Multi-pane container widget + """PanedWindow - Multi-pane container widget allows the user to interactively manipulate the sizes of several panes. The panes can be arranged either vertically or horizontally.The user changes the sizes of the panes by dragging the resize handle @@ -734,8 +668,7 @@ class PanedWindow(TixWidget): def panes(self) -> list[tkinter.Widget]: ... class ListNoteBook(TixWidget): - """ - A ListNoteBook widget is very similar to the TixNoteBook widget: + """A ListNoteBook widget is very similar to the TixNoteBook widget: it can be used to display many windows in a limited space using a notebook metaphor. The notebook is divided into a stack of pages (windows). At one time only one of these pages can be shown. @@ -750,8 +683,7 @@ class ListNoteBook(TixWidget): def raise_page(self, name: str) -> None: ... class NoteBook(TixWidget): - """ - NoteBook - Multi-page container widget (tabbed notebook metaphor). + """NoteBook - Multi-page container widget (tabbed notebook metaphor). Subwidgets Class ---------- ----- @@ -768,8 +700,7 @@ class NoteBook(TixWidget): def raised(self) -> bool: ... class InputOnly(TixWidget): - """ - InputOnly - Invisible widget. Unix only. + """InputOnly - Invisible widget. Unix only. Subwidgets - None """ @@ -777,8 +708,7 @@ class InputOnly(TixWidget): def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... class Form: - """ - The Tix Form geometry manager + """The Tix Form geometry manager Widgets can be arranged by specifying attachments to other widgets. See Tix documentation for complete details diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/ttk.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/ttk.pyi index dc691e2e79..def58db8b7 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/ttk.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/tkinter/ttk.pyi @@ -50,14 +50,12 @@ __all__ = [ ] def tclobjs_to_py(adict: dict[Any, Any]) -> dict[Any, Any]: - """ - Returns adict with its values converted from Tcl objects to Python + """Returns adict with its values converted from Tcl objects to Python objects. """ def setup_master(master=None): - """ - If master is not None, itself is returned. If master is None, + """If master is not None, itself is returned. If master is None, the default master is returned if there is one, otherwise a new master is created and returned. @@ -77,16 +75,13 @@ _Padding: TypeAlias = ( _TtkCompound: TypeAlias = Literal["", "text", "image", tkinter._Compound] class Style: - """ - Manipulate style database. - """ + """Manipulate style database.""" master: Incomplete tk: _tkinter.TkappType def __init__(self, master: tkinter.Misc | None = None) -> None: ... def configure(self, style, query_opt=None, **kw): - """ - Query or sets the default value of the specified option(s) in + """Query or sets the default value of the specified option(s) in style. Each key in kw is an option and each value is either a string or @@ -94,8 +89,7 @@ class Style: """ def map(self, style, query_opt=None, **kw): - """ - Query or sets dynamic values of the specified option(s) in + """Query or sets dynamic values of the specified option(s) in style. Each key in kw is an option and each value should be a list or a @@ -105,8 +99,7 @@ class Style: """ def lookup(self, style, option, state=None, default=None): - """ - Returns the value specified for option in style. + """Returns the value specified for option in style. If state is specified it is expected to be a sequence of one or more states. If the default argument is set, it is used as @@ -114,8 +107,7 @@ class Style: """ def layout(self, style, layoutspec=None): - """ - Define the widget layout for given style. If layoutspec is + """Define the widget layout for given style. If layoutspec is omitted, return the layout specification for given style. layoutspec is expected to be a list or an object different than @@ -149,23 +141,16 @@ class Style: """ def element_create(self, elementname, etype, *args, **kw) -> None: - """ - Create a new element in the current theme of given etype. - """ + """Create a new element in the current theme of given etype.""" def element_names(self): - """ - Returns the list of elements defined in the current theme. - """ + """Returns the list of elements defined in the current theme.""" def element_options(self, elementname): - """ - Return the list of elementname's options. - """ + """Return the list of elementname's options.""" def theme_create(self, themename, parent=None, settings=None) -> None: - """ - Creates a new theme. + """Creates a new theme. It is an error if themename already exists. If parent is specified, the new theme will inherit styles, elements and @@ -174,8 +159,7 @@ class Style: """ def theme_settings(self, themename, settings) -> None: - """ - Temporarily sets the current theme to themename, apply specified + """Temporarily sets the current theme to themename, apply specified settings and then restore the previous theme. Each key in settings is a style and each value may contain the @@ -185,14 +169,11 @@ class Style: """ def theme_names(self) -> tuple[str, ...]: - """ - Returns a list of all known themes. - """ + """Returns a list of all known themes.""" @overload def theme_use(self, themename: str) -> None: - """ - If themename is None, returns the theme in use, otherwise, set + """If themename is None, returns the theme in use, otherwise, set the current theme to themename, refreshes all widgets and emits a <> event. """ @@ -201,13 +182,10 @@ class Style: def theme_use(self, themename: None = None) -> str: ... class Widget(tkinter.Widget): - """ - Base class for Tk themed widgets. - """ + """Base class for Tk themed widgets.""" def __init__(self, master: tkinter.Misc | None, widgetname, kw=None) -> None: - """ - Constructs a Ttk Widget with the parent master. + """Constructs a Ttk Widget with the parent master. STANDARD OPTIONS @@ -228,16 +206,14 @@ class Widget(tkinter.Widget): """ def identify(self, x: int, y: int) -> str: - """ - Returns the name of the element at position x, y, or the empty + """Returns the name of the element at position x, y, or the empty string if the point does not lie within any element. x and y are pixel coordinates relative to the widget. """ def instate(self, statespec, callback=None, *args, **kw): - """ - Test the widget's state. + """Test the widget's state. If callback is not specified, returns True if the widget state matches statespec and False otherwise. If callback is specified, @@ -246,8 +222,7 @@ class Widget(tkinter.Widget): """ def state(self, statespec=None): - """ - Modify or inquire widget state. + """Modify or inquire widget state. Widget state is returned if statespec is None, otherwise it is set according to the statespec flags and then a new state spec @@ -256,8 +231,7 @@ class Widget(tkinter.Widget): """ class Button(Widget): - """ - Ttk Button widget, displays a textual label and/or image, and + """Ttk Button widget, displays a textual label and/or image, and evaluates a command when pressed. """ @@ -281,8 +255,7 @@ class Button(Widget): underline: int = -1, width: int | Literal[""] = "", ) -> None: - """ - Construct a Ttk Button widget with the parent master. + """Construct a Ttk Button widget with the parent master. STANDARD OPTIONS @@ -313,8 +286,7 @@ class Button(Widget): underline: int = ..., width: int | Literal[""] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -325,14 +297,10 @@ class Button(Widget): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def invoke(self) -> Any: - """ - Invokes the command associated with the button. - """ + """Invokes the command associated with the button.""" class Checkbutton(Widget): - """ - Ttk Checkbutton widget which is either in on- or off-state. - """ + """Ttk Checkbutton widget which is either in on- or off-state.""" def __init__( self, @@ -359,8 +327,7 @@ class Checkbutton(Widget): variable: tkinter.Variable = ..., width: int | Literal[""] = "", ) -> None: - """ - Construct a Ttk Checkbutton widget with the parent master. + """Construct a Ttk Checkbutton widget with the parent master. STANDARD OPTIONS @@ -393,8 +360,7 @@ class Checkbutton(Widget): variable: tkinter.Variable = ..., width: int | Literal[""] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -405,8 +371,7 @@ class Checkbutton(Widget): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def invoke(self) -> Any: - """ - Toggles between the selected and deselected states and + """Toggles between the selected and deselected states and invokes the associated command. If the widget is currently selected, sets the option variable to the offvalue option and deselects the widget; otherwise, sets the option variable @@ -416,8 +381,7 @@ class Checkbutton(Widget): """ class Entry(Widget, tkinter.Entry): - """ - Ttk Entry widget displays a one-line text string and allows that + """Ttk Entry widget displays a one-line text string and allows that string to be edited by the user. """ @@ -445,8 +409,7 @@ class Entry(Widget, tkinter.Entry): width: int = 20, xscrollcommand: tkinter._XYScrollCommand = "", ) -> None: - """ - Constructs a Ttk Entry widget with the parent master. + """Constructs a Ttk Entry widget with the parent master. STANDARD OPTIONS @@ -484,8 +447,7 @@ class Entry(Widget, tkinter.Entry): width: int = ..., xscrollcommand: tkinter._XYScrollCommand = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -517,8 +479,7 @@ class Entry(Widget, tkinter.Entry): width: int = ..., xscrollcommand: tkinter._XYScrollCommand = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -528,27 +489,23 @@ class Entry(Widget, tkinter.Entry): @overload def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... def bbox(self, index) -> tuple[int, int, int, int]: # type: ignore[override] - """ - Return a tuple of (x, y, width, height) which describes the + """Return a tuple of (x, y, width, height) which describes the bounding box of the character given by index. """ def identify(self, x: int, y: int) -> str: - """ - Returns the name of the element at position x, y, or the + """Returns the name of the element at position x, y, or the empty string if the coordinates are outside the window. """ def validate(self): - """ - Force revalidation, independent of the conditions specified + """Force revalidation, independent of the conditions specified by the validate option. Returns False if validation fails, True if it succeeds. Sets or clears the invalid state accordingly. """ class Combobox(Entry): - """ - Ttk Combobox widget combines a text field with a pop-down list of + """Ttk Combobox widget combines a text field with a pop-down list of values. """ @@ -578,8 +535,7 @@ class Combobox(Entry): width: int = 20, xscrollcommand: tkinter._XYScrollCommand = ..., # undocumented ) -> None: - """ - Construct a Ttk Combobox widget with the parent master. + """Construct a Ttk Combobox widget with the parent master. STANDARD OPTIONS @@ -616,8 +572,7 @@ class Combobox(Entry): width: int = ..., xscrollcommand: tkinter._XYScrollCommand = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -652,8 +607,7 @@ class Combobox(Entry): width: int = ..., xscrollcommand: tkinter._XYScrollCommand = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -663,21 +617,17 @@ class Combobox(Entry): @overload def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... def current(self, newindex: int | None = None) -> int: - """ - If newindex is supplied, sets the combobox value to the + """If newindex is supplied, sets the combobox value to the element at position newindex in the list of values. Otherwise, returns the index of the current value in the list of values or -1 if the current value does not appear in the list. """ def set(self, value: Any) -> None: - """ - Sets the value of the combobox to value. - """ + """Sets the value of the combobox to value.""" class Frame(Widget): - """ - Ttk Frame widget is a container, used to group other widgets + """Ttk Frame widget is a container, used to group other widgets together. """ @@ -699,8 +649,7 @@ class Frame(Widget): takefocus: tkinter._TakeFocusValue = "", width: tkinter._ScreenUnits = 0, ) -> None: - """ - Construct a Ttk Frame with parent master. + """Construct a Ttk Frame with parent master. STANDARD OPTIONS @@ -726,8 +675,7 @@ class Frame(Widget): takefocus: tkinter._TakeFocusValue = ..., width: tkinter._ScreenUnits = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -739,9 +687,7 @@ class Frame(Widget): config = configure class Label(Widget): - """ - Ttk Label widget displays a textual label and/or image. - """ + """Ttk Label widget displays a textual label and/or image.""" def __init__( self, @@ -770,8 +716,7 @@ class Label(Widget): width: int | Literal[""] = "", wraplength: tkinter._ScreenUnits = ..., ) -> None: - """ - Construct a Ttk Label with parent master. + """Construct a Ttk Label with parent master. STANDARD OPTIONS @@ -810,8 +755,7 @@ class Label(Widget): width: int | Literal[""] = ..., wraplength: tkinter._ScreenUnits = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -823,8 +767,7 @@ class Label(Widget): config = configure class Labelframe(Widget): - """ - Ttk Labelframe widget is a container used to group other widgets + """Ttk Labelframe widget is a container used to group other widgets together. It has an optional label, which may be a plain text string or another widget. """ @@ -849,8 +792,7 @@ class Labelframe(Widget): underline: int = -1, width: tkinter._ScreenUnits = 0, ) -> None: - """ - Construct a Ttk Labelframe with parent master. + """Construct a Ttk Labelframe with parent master. STANDARD OPTIONS @@ -880,8 +822,7 @@ class Labelframe(Widget): underline: int = ..., width: tkinter._ScreenUnits = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -895,8 +836,7 @@ class Labelframe(Widget): LabelFrame = Labelframe class Menubutton(Widget): - """ - Ttk Menubutton widget displays a textual label and/or image, and + """Ttk Menubutton widget displays a textual label and/or image, and displays a menu when pressed. """ @@ -920,8 +860,7 @@ class Menubutton(Widget): underline: int = -1, width: int | Literal[""] = "", ) -> None: - """ - Construct a Ttk Menubutton with parent master. + """Construct a Ttk Menubutton with parent master. STANDARD OPTIONS @@ -952,8 +891,7 @@ class Menubutton(Widget): underline: int = ..., width: int | Literal[""] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -965,8 +903,7 @@ class Menubutton(Widget): config = configure class Notebook(Widget): - """ - Ttk Notebook widget manages a collection of windows and displays + """Ttk Notebook widget manages a collection of windows and displays a single one at a time. Each child window is associated with a tab, which the user may select to change the currently-displayed window. """ @@ -984,8 +921,7 @@ class Notebook(Widget): takefocus: tkinter._TakeFocusValue = ..., width: int = 0, ) -> None: - """ - Construct a Ttk Notebook with parent master. + """Construct a Ttk Notebook with parent master. STANDARD OPTIONS @@ -1026,8 +962,7 @@ class Notebook(Widget): takefocus: tkinter._TakeFocusValue = ..., width: int = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -1051,22 +986,19 @@ class Notebook(Widget): compound: tkinter._Compound = ..., underline: int = ..., ) -> None: - """ - Adds a new tab to the notebook. + """Adds a new tab to the notebook. If window is currently managed by the notebook but hidden, it is restored to its previous position. """ def forget(self, tab_id) -> None: # type: ignore[override] - """ - Removes the tab specified by tab_id, unmaps and unmanages the + """Removes the tab specified by tab_id, unmaps and unmanages the associated window. """ def hide(self, tab_id) -> None: - """ - Hides the tab specified by tab_id. + """Hides the tab specified by tab_id. The tab will not be displayed, but the associated window remains managed by the notebook and its configuration remembered. Hidden @@ -1074,20 +1006,17 @@ class Notebook(Widget): """ def identify(self, x: int, y: int) -> str: - """ - Returns the name of the tab element at position x, y, or the + """Returns the name of the tab element at position x, y, or the empty string if none. """ def index(self, tab_id): - """ - Returns the numeric index of the tab specified by tab_id, or + """Returns the numeric index of the tab specified by tab_id, or the total number of tabs if tab_id is the string "end". """ def insert(self, pos, child, **kw) -> None: - """ - Inserts a pane at the specified position. + """Inserts a pane at the specified position. pos is either the string end, an integer index, or the name of a managed child. If child is already managed by the notebook, @@ -1095,8 +1024,7 @@ class Notebook(Widget): """ def select(self, tab_id=None): - """ - Selects the specified tab. + """Selects the specified tab. The associated child window will be displayed, and the previously-selected window (if different) is unmapped. If tab_id @@ -1105,8 +1033,7 @@ class Notebook(Widget): """ def tab(self, tab_id, option=None, **kw): - """ - Query or modify the options of the specific tab_id. + """Query or modify the options of the specific tab_id. If kw is not given, returns a dict of the tab option values. If option is specified, returns the value of that option. Otherwise, sets the @@ -1114,13 +1041,10 @@ class Notebook(Widget): """ def tabs(self): - """ - Returns a list of windows managed by the notebook. - """ + """Returns a list of windows managed by the notebook.""" def enable_traversal(self) -> None: - """ - Enable keyboard traversal for a toplevel window containing + """Enable keyboard traversal for a toplevel window containing this notebook. This will extend the bindings for the toplevel window containing @@ -1142,8 +1066,7 @@ class Notebook(Widget): """ class Panedwindow(Widget, tkinter.PanedWindow): - """ - Ttk Panedwindow widget displays a number of subwindows, stacked + """Ttk Panedwindow widget displays a number of subwindows, stacked either vertically or horizontally. """ @@ -1161,8 +1084,7 @@ class Panedwindow(Widget, tkinter.PanedWindow): takefocus: tkinter._TakeFocusValue = "", width: int = 0, ) -> None: - """ - Construct a Ttk Panedwindow with parent master. + """Construct a Ttk Panedwindow with parent master. STANDARD OPTIONS @@ -1178,8 +1100,7 @@ class Panedwindow(Widget, tkinter.PanedWindow): """ def add(self, child: tkinter.Widget, *, weight: int = ..., **kw) -> None: - """ - Add a child widget to the panedwindow in a new pane. + """Add a child widget to the panedwindow in a new pane. The child argument is the name of the child widget followed by pairs of arguments that specify how to @@ -1198,8 +1119,7 @@ class Panedwindow(Widget, tkinter.PanedWindow): takefocus: tkinter._TakeFocusValue = ..., width: int = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -1220,8 +1140,7 @@ class Panedwindow(Widget, tkinter.PanedWindow): takefocus: tkinter._TakeFocusValue = ..., width: int = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -1232,8 +1151,7 @@ class Panedwindow(Widget, tkinter.PanedWindow): def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... forget: Incomplete def insert(self, pos, child, **kw) -> None: - """ - Inserts a pane at the specified positions. + """Inserts a pane at the specified positions. pos is either the string end, and integer index, or the name of a child. If child is already managed by the paned window, @@ -1241,8 +1159,7 @@ class Panedwindow(Widget, tkinter.PanedWindow): """ def pane(self, pane, option=None, **kw): - """ - Query or modify the options of the specified pane. + """Query or modify the options of the specified pane. pane is either an integer index or the name of a managed subwindow. If kw is not given, returns a dict of the pane option values. If @@ -1251,8 +1168,7 @@ class Panedwindow(Widget, tkinter.PanedWindow): """ def sashpos(self, index, newpos=None): - """ - If newpos is specified, sets the position of sash number index. + """If newpos is specified, sets the position of sash number index. May adjust the positions of adjacent sashes to ensure that positions are monotonically increasing. Sash positions are further @@ -1264,8 +1180,7 @@ class Panedwindow(Widget, tkinter.PanedWindow): PanedWindow = Panedwindow class Progressbar(Widget): - """ - Ttk Progressbar widget shows the status of a long-running + """Ttk Progressbar widget shows the status of a long-running operation. They can operate in two modes: determinate mode shows the amount completed relative to the total amount of work to be done, and indeterminate mode provides an animated display to let the user know @@ -1289,8 +1204,7 @@ class Progressbar(Widget): value: float = 0.0, variable: tkinter.IntVar | tkinter.DoubleVar = ..., ) -> None: - """ - Construct a Ttk Progressbar with parent master. + """Construct a Ttk Progressbar with parent master. STANDARD OPTIONS @@ -1317,8 +1231,7 @@ class Progressbar(Widget): value: float = ..., variable: tkinter.IntVar | tkinter.DoubleVar = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -1329,29 +1242,25 @@ class Progressbar(Widget): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def start(self, interval: Literal["idle"] | int | None = None) -> None: - """ - Begin autoincrement mode: schedules a recurring timer event + """Begin autoincrement mode: schedules a recurring timer event that calls method step every interval milliseconds. interval defaults to 50 milliseconds (20 steps/second) if omitted. """ def step(self, amount: float | None = None) -> None: - """ - Increments the value option by amount. + """Increments the value option by amount. amount defaults to 1.0 if omitted. """ def stop(self) -> None: - """ - Stop autoincrement mode: cancels any recurring timer event + """Stop autoincrement mode: cancels any recurring timer event initiated by start. """ class Radiobutton(Widget): - """ - Ttk Radiobutton widgets are used in groups to show or change a + """Ttk Radiobutton widgets are used in groups to show or change a set of mutually-exclusive options. """ @@ -1376,8 +1285,7 @@ class Radiobutton(Widget): variable: tkinter.Variable | Literal[""] = ..., width: int | Literal[""] = "", ) -> None: - """ - Construct a Ttk Radiobutton with parent master. + """Construct a Ttk Radiobutton with parent master. STANDARD OPTIONS @@ -1409,8 +1317,7 @@ class Radiobutton(Widget): variable: tkinter.Variable | Literal[""] = ..., width: int | Literal[""] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -1421,8 +1328,7 @@ class Radiobutton(Widget): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def invoke(self) -> Any: - """ - Sets the option variable to the option value, selects the + """Sets the option variable to the option value, selects the widget, and invokes the associated command. Returns the result of the command, or an empty string if @@ -1431,8 +1337,7 @@ class Radiobutton(Widget): # type ignore, because identify() methods of Widget and tkinter.Scale are incompatible class Scale(Widget, tkinter.Scale): # type: ignore[misc] - """ - Ttk Scale widget is typically used to control the numeric value of + """Ttk Scale widget is typically used to control the numeric value of a linked variable that varies uniformly over some range. """ @@ -1454,8 +1359,7 @@ class Scale(Widget, tkinter.Scale): # type: ignore[misc] value: float = 0, variable: tkinter.IntVar | tkinter.DoubleVar = ..., ) -> None: - """ - Construct a Ttk Scale with parent master. + """Construct a Ttk Scale with parent master. STANDARD OPTIONS @@ -1483,8 +1387,7 @@ class Scale(Widget, tkinter.Scale): # type: ignore[misc] value: float = ..., variable: tkinter.IntVar | tkinter.DoubleVar = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Modify or query scale options. + """Modify or query scale options. Setting a value for any of the "from", "from_" or "to" options generates a <> event. @@ -1510,8 +1413,7 @@ class Scale(Widget, tkinter.Scale): # type: ignore[misc] value: float = ..., variable: tkinter.IntVar | tkinter.DoubleVar = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -1521,8 +1423,7 @@ class Scale(Widget, tkinter.Scale): # type: ignore[misc] @overload def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... def get(self, x: int | None = None, y: int | None = None) -> float: - """ - Get the current value of the value option, or the value + """Get the current value of the value option, or the value corresponding to the coordinates x, y if they are specified. x and y are pixel coordinates relative to the scale widget @@ -1531,9 +1432,7 @@ class Scale(Widget, tkinter.Scale): # type: ignore[misc] # type ignore, because identify() methods of Widget and tkinter.Scale are incompatible class Scrollbar(Widget, tkinter.Scrollbar): # type: ignore[misc] - """ - Ttk Scrollbar controls the viewport of a scrollable widget. - """ + """Ttk Scrollbar controls the viewport of a scrollable widget.""" def __init__( self, @@ -1547,8 +1446,7 @@ class Scrollbar(Widget, tkinter.Scrollbar): # type: ignore[misc] style: str = "", takefocus: tkinter._TakeFocusValue = "", ) -> None: - """ - Construct a Ttk Scrollbar with parent master. + """Construct a Ttk Scrollbar with parent master. STANDARD OPTIONS @@ -1570,8 +1468,7 @@ class Scrollbar(Widget, tkinter.Scrollbar): # type: ignore[misc] style: str = ..., takefocus: tkinter._TakeFocusValue = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -1592,8 +1489,7 @@ class Scrollbar(Widget, tkinter.Scrollbar): # type: ignore[misc] style: str = ..., takefocus: tkinter._TakeFocusValue = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -1604,8 +1500,7 @@ class Scrollbar(Widget, tkinter.Scrollbar): # type: ignore[misc] def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... class Separator(Widget): - """ - Ttk Separator widget displays a horizontal or vertical separator + """Ttk Separator widget displays a horizontal or vertical separator bar. """ @@ -1620,8 +1515,7 @@ class Separator(Widget): style: str = "", takefocus: tkinter._TakeFocusValue = "", ) -> None: - """ - Construct a Ttk Separator with parent master. + """Construct a Ttk Separator with parent master. STANDARD OPTIONS @@ -1642,8 +1536,7 @@ class Separator(Widget): style: str = ..., takefocus: tkinter._TakeFocusValue = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -1655,8 +1548,7 @@ class Separator(Widget): config = configure class Sizegrip(Widget): - """ - Ttk Sizegrip allows the user to resize the containing toplevel + """Ttk Sizegrip allows the user to resize the containing toplevel window by pressing and dragging the grip. """ @@ -1670,8 +1562,7 @@ class Sizegrip(Widget): style: str = "", takefocus: tkinter._TakeFocusValue = "", ) -> None: - """ - Construct a Ttk Sizegrip with parent master. + """Construct a Ttk Sizegrip with parent master. STANDARD OPTIONS @@ -1687,8 +1578,7 @@ class Sizegrip(Widget): style: str = ..., takefocus: tkinter._TakeFocusValue = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -1700,8 +1590,7 @@ class Sizegrip(Widget): config = configure class Spinbox(Entry): - """ - Ttk Spinbox is an Entry with increment and decrement arrows + """Ttk Spinbox is an Entry with increment and decrement arrows It is commonly used for number entry or to select from a list of string values. @@ -1737,8 +1626,7 @@ class Spinbox(Entry): wrap: bool = False, xscrollcommand: tkinter._XYScrollCommand = "", ) -> None: - """ - Construct a Ttk Spinbox widget with the parent master. + """Construct a Ttk Spinbox widget with the parent master. STANDARD OPTIONS @@ -1779,8 +1667,7 @@ class Spinbox(Entry): wrap: bool = ..., xscrollcommand: tkinter._XYScrollCommand = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -1791,9 +1678,7 @@ class Spinbox(Entry): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure # type: ignore[assignment] def set(self, value: Any) -> None: - """ - Sets the value of the Spinbox to value. - """ + """Sets the value of the Spinbox to value.""" class _TreeviewItemDict(TypedDict): text: str @@ -1824,8 +1709,7 @@ class _TreeviewColumnDict(TypedDict): id: str class Treeview(Widget, tkinter.XView, tkinter.YView): - """ - Ttk Treeview widget displays a hierarchical collection of items. + """Ttk Treeview widget displays a hierarchical collection of items. Each item has a textual label, an optional image, and an optional list of data values. The data values are displayed in successive columns @@ -1854,8 +1738,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): xscrollcommand: tkinter._XYScrollCommand = "", yscrollcommand: tkinter._XYScrollCommand = "", ) -> None: - """ - Construct a Ttk Treeview with parent master. + """Construct a Ttk Treeview with parent master. STANDARD OPTIONS @@ -1892,8 +1775,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): xscrollcommand: tkinter._XYScrollCommand = ..., yscrollcommand: tkinter._XYScrollCommand = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: - """ - Configure resources of a widget. + """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about @@ -1904,8 +1786,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def bbox(self, item: str | int, column: str | int | None = None) -> tuple[int, int, int, int] | Literal[""]: # type: ignore[override] - """ - Returns the bounding box (relative to the treeview widget's + """Returns the bounding box (relative to the treeview widget's window) of the specified item in the form x y width height. If column is specified, returns the bounding box of that cell. @@ -1914,15 +1795,13 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): """ def get_children(self, item: str | int | None = None) -> tuple[str, ...]: - """ - Returns a tuple of children belonging to item. + """Returns a tuple of children belonging to item. If item is not specified, returns root children. """ def set_children(self, item: str | int, *newchildren: str | int) -> None: - """ - Replaces item's child with newchildren. + """Replaces item's child with newchildren. Children present in item that are not present in newchildren are detached from tree. No items in newchildren may be an @@ -1931,8 +1810,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): @overload def column(self, column: str | int, option: Literal["width", "minwidth"]) -> int: - """ - Query or modify the options for the specified column. + """Query or modify the options for the specified column. If kw is not given, returns a dict of the column option values. If option is specified then the value for that option is returned. @@ -1960,14 +1838,12 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): # id is read-only ) -> _TreeviewColumnDict | None: ... def delete(self, *items: str | int) -> None: - """ - Delete all specified items and all their descendants. The root + """Delete all specified items and all their descendants. The root item may not be deleted. """ def detach(self, *items: str | int) -> None: - """ - Unlinks all of the specified items from the tree. + """Unlinks all of the specified items from the tree. The items and all of their descendants are still present, and may be reinserted at another point in the tree, but will not be @@ -1975,15 +1851,13 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): """ def exists(self, item: str | int) -> bool: - """ - Returns True if the specified item is present in the tree, + """Returns True if the specified item is present in the tree, False otherwise. """ @overload # type: ignore[override] def focus(self, item: None = None) -> str: # can return empty string - """ - If item is specified, sets the focus item to item. Otherwise, + """If item is specified, sets the focus item to item. Otherwise, returns the current focus item, or '' if there is none. """ @@ -1991,8 +1865,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): def focus(self, item: str | int) -> Literal[""]: ... @overload def heading(self, column: str | int, option: Literal["text"]) -> str: - """ - Query or modify the heading options for the specified column. + """Query or modify the heading options for the specified column. If kw is not given, returns a dict of the heading option values. If option is specified then the value for that option is returned. @@ -2037,27 +1910,22 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): ) -> None: ... # Internal Method. Leave untyped: def identify(self, component, x, y): # type: ignore[override] - """ - Returns a description of the specified component under the + """Returns a description of the specified component under the point given by x and y, or the empty string if no such component is present at that position. """ def identify_row(self, y: int) -> str: - """ - Returns the item ID of the item at position y. - """ + """Returns the item ID of the item at position y.""" def identify_column(self, x: int) -> str: - """ - Returns the data column identifier of the cell at position x. + """Returns the data column identifier of the cell at position x. The tree column has ID #0. """ def identify_region(self, x: int, y: int) -> Literal["heading", "separator", "tree", "cell", "nothing"]: - """ - Returns one of: + """Returns one of: heading: Tree heading area. separator: Space between two columns headings; @@ -2068,15 +1936,13 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): """ def identify_element(self, x: int, y: int) -> str: # don't know what possible return values are - """ - Returns the element at position x, y. + """Returns the element at position x, y. * Availability: Tk 8.6 """ def index(self, item: str | int) -> int: - """ - Returns the integer index of item within its parent's list + """Returns the integer index of item within its parent's list of children. """ @@ -2093,8 +1959,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): open: bool = ..., tags: str | list[str] | tuple[str, ...] = ..., ) -> str: - """ - Creates a new item and return the item identifier of the newly + """Creates a new item and return the item identifier of the newly created item. parent is the item ID of the parent item, or the empty string @@ -2110,8 +1975,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): @overload def item(self, item: str | int, option: Literal["text"]) -> str: - """ - Query or modify the options for the specified item. + """Query or modify the options for the specified item. If no options are given, a dict with options/values for the item is returned. If option is specified then the value for that option @@ -2144,8 +2008,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): tags: str | list[str] | tuple[str, ...] = ..., ) -> None: ... def move(self, item: str | int, parent: str, index: int | Literal["end"]) -> None: - """ - Moves item to position index in parent's list of children. + """Moves item to position index in parent's list of children. It is illegal to move an item under one of its descendants. If index is less than or equal to zero, item is moved to the @@ -2154,26 +2017,22 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): """ reattach = move def next(self, item: str | int) -> str: # returning empty string means last item - """ - Returns the identifier of item's next sibling, or '' if item + """Returns the identifier of item's next sibling, or '' if item is the last child of its parent. """ def parent(self, item: str | int) -> str: - """ - Returns the ID of the parent of item, or '' if item is at the + """Returns the ID of the parent of item, or '' if item is at the top level of the hierarchy. """ def prev(self, item: str | int) -> str: # returning empty string means first item - """ - Returns the identifier of item's previous sibling, or '' if + """Returns the identifier of item's previous sibling, or '' if item is the first child of its parent. """ def see(self, item: str | int) -> None: - """ - Ensure that item is visible. + """Ensure that item is visible. Sets all of item's ancestors open option to True, and scrolls the widget if necessary so that item is within the visible @@ -2181,46 +2040,35 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): """ def selection(self) -> tuple[str, ...]: - """ - Returns the tuple of selected items. - """ + """Returns the tuple of selected items.""" @overload def selection_set(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: - """ - The specified items becomes the new selection. - """ + """The specified items becomes the new selection.""" @overload def selection_set(self, *items: str | int) -> None: ... @overload def selection_add(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: - """ - Add all of the specified items to the selection. - """ + """Add all of the specified items to the selection.""" @overload def selection_add(self, *items: str | int) -> None: ... @overload def selection_remove(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: - """ - Remove all of the specified items from the selection. - """ + """Remove all of the specified items from the selection.""" @overload def selection_remove(self, *items: str | int) -> None: ... @overload def selection_toggle(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: - """ - Toggle the selection state of each specified item. - """ + """Toggle the selection state of each specified item.""" @overload def selection_toggle(self, *items: str | int) -> None: ... @overload def set(self, item: str | int, column: None = None, value: None = None) -> dict[str, Any]: - """ - Query or set the value of given item. + """Query or set the value of given item. With one argument, return a dictionary of column/value pairs for the specified item. With two arguments, return the current @@ -2238,8 +2086,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): def tag_bind( self, tagname: str, sequence: str | None = None, callback: Callable[[tkinter.Event[Treeview]], object] | None = None ) -> str: - """ - Bind a callback for the given event sequence to the tag tagname. + """Bind a callback for the given event sequence to the tag tagname. When an event is delivered to an item, the callbacks for each of the item's tags option are called. """ @@ -2250,8 +2097,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): def tag_bind(self, tagname: str, *, callback: str) -> None: ... @overload def tag_configure(self, tagname: str, option: Literal["foreground", "background"]) -> str: - """ - Query or modify the options for the specified tagname. + """Query or modify the options for the specified tagname. If kw is not given, returns a dict of the option settings for tagname. If option is specified, returns the value for that option for the @@ -2277,8 +2123,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): ) -> _TreeviewTagDict | MaybeNone: ... # can be None but annoying to check @overload def tag_has(self, tagname: str, item: None = None) -> tuple[str, ...]: - """ - If item is specified, returns 1 or 0 depending on whether the + """If item is specified, returns 1 or 0 depending on whether the specified item has the given tagname. Otherwise, returns a list of all items which have the specified tag. @@ -2289,8 +2134,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): def tag_has(self, tagname: str, item: str | int) -> bool: ... class LabeledScale(Frame): - """ - A Ttk Scale widget with a Ttk Label widget indicating its + """A Ttk Scale widget with a Ttk Label widget indicating its current value. The Ttk Scale can be accessed through instance.scale, and Ttk Label @@ -2321,8 +2165,7 @@ class LabeledScale(Frame): takefocus: tkinter._TakeFocusValue = "", width: tkinter._ScreenUnits = 0, ) -> None: - """ - Construct a horizontal LabeledScale with parent master, a + """Construct a horizontal LabeledScale with parent master, a variable to be associated with the Ttk Scale widget and its range. If variable is not specified, a tkinter.IntVar is created. @@ -2336,8 +2179,7 @@ class LabeledScale(Frame): value: Any class OptionMenu(Menubutton): - """ - Themed OptionMenu, based after tkinter's OptionMenu, which allows + """Themed OptionMenu, based after tkinter's OptionMenu, which allows the user to select a value from a menu. """ @@ -2352,8 +2194,7 @@ class OptionMenu(Menubutton): direction: Literal["above", "below", "left", "right", "flush"] = "below", command: Callable[[tkinter.StringVar], object] | None = None, ) -> None: - """ - Construct a themed OptionMenu widget with master as the parent, + """Construct a themed OptionMenu widget with master as the parent, the resource textvariable set to variable, the initially selected value specified by the default parameter, the menu values given by *values and additional keywords. @@ -2370,7 +2211,6 @@ class OptionMenu(Menubutton): # configure, config, cget, destroy are inherited from Menubutton # destroy and __setitem__ are overridden, signature does not change def set_menu(self, default: str | None = None, *values: str) -> None: - """ - Build a new menu of radiobuttons with *values and optionally + """Build a new menu of radiobuttons with *values and optionally a default value. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/tokenize.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/tokenize.pyi index dd70692ec8..aa42c68b4a 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/tokenize.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/tokenize.pyi @@ -158,8 +158,7 @@ class Untokenizer: def add_whitespace(self, start: _Position) -> None: ... if sys.version_info >= (3, 12): def add_backslash_continuation(self, start: _Position) -> None: - """ - Add backslash continuation characters if the row has increased + """Add backslash continuation characters if the row has increased without encountering a newline token. This also inserts the correct amount of whitespace before the backslash. @@ -172,8 +171,7 @@ class Untokenizer: # Returns str, unless the ENCODING token is present, in which case it returns bytes. def untokenize(iterable: Iterable[_Token]) -> str | Any: - """ - Transform tokens back into Python source code. + """Transform tokens back into Python source code. It returns a bytes object, encoded using the ENCODING token, which is the first token sequence output by tokenize. @@ -188,8 +186,7 @@ def untokenize(iterable: Iterable[_Token]) -> str | Any: """ def detect_encoding(readline: Callable[[], bytes | bytearray]) -> tuple[str, Sequence[bytes]]: - """ - The detect_encoding() function is used to detect the encoding that should + """The detect_encoding() function is used to detect the encoding that should be used to decode a Python source file. It requires one argument, readline, in the same way as the tokenize() generator. @@ -206,8 +203,7 @@ def detect_encoding(readline: Callable[[], bytes | bytearray]) -> tuple[str, Seq """ def tokenize(readline: Callable[[], bytes | bytearray]) -> Generator[TokenInfo, None, None]: - """ - The tokenize() generator requires one argument, readline, which + """The tokenize() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as bytes. Alternatively, readline @@ -226,16 +222,14 @@ def tokenize(readline: Callable[[], bytes | bytearray]) -> Generator[TokenInfo, """ def generate_tokens(readline: Callable[[], str]) -> Generator[TokenInfo, None, None]: - """ - Tokenize a source reading Python code as unicode strings. + """Tokenize a source reading Python code as unicode strings. This has the same API as tokenize(), except that it expects the *readline* callable to return str objects instead of bytes. """ def open(filename: FileDescriptorOrPath) -> TextIO: - """ - Open a file in read only mode using the encoding detected by + """Open a file in read only mode using the encoding detected by detect_encoding(). """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/tomllib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/tomllib.pyi index aacc744472..c9024b51e8 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/tomllib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/tomllib.pyi @@ -8,8 +8,7 @@ __all__ = ("loads", "load", "TOMLDecodeError") if sys.version_info >= (3, 14): class TOMLDecodeError(ValueError): - """ - An error raised if a document is not valid TOML. + """An error raised if a document is not valid TOML. Adds the following attributes to ValueError: msg: The unformatted error message @@ -32,16 +31,10 @@ if sys.version_info >= (3, 14): else: class TOMLDecodeError(ValueError): - """ - An error raised if a document is not valid TOML. - """ + """An error raised if a document is not valid TOML.""" def load(fp: SupportsRead[bytes], /, *, parse_float: Callable[[str], Any] = ...) -> dict[str, Any]: - """ - Parse TOML from a binary file object. - """ + """Parse TOML from a binary file object.""" def loads(s: str, /, *, parse_float: Callable[[str], Any] = ...) -> dict[str, Any]: - """ - Parse TOML from a string. - """ + """Parse TOML from a string.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/trace.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/trace.pyi index 232e97be81..559c499723 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/trace.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/trace.pyi @@ -49,9 +49,7 @@ class CoverageResults: outfile: StrPath | None = None, ) -> None: ... # undocumented def update(self, other: CoverageResults) -> None: - """ - Merge in the data from another CoverageResults - """ + """Merge in the data from another CoverageResults""" if sys.version_info >= (3, 13): def write_results( self, @@ -61,8 +59,7 @@ class CoverageResults: *, ignore_missing_files: bool = False, ) -> None: - """ - Write the coverage results. + """Write the coverage results. :param show_missing: Show lines that had no hits. :param summary: Include coverage summary per module. @@ -75,8 +72,7 @@ class CoverageResults: """ else: def write_results(self, show_missing: bool = True, summary: bool = False, coverdir: StrPath | None = None) -> None: - """ - Write the coverage results. + """Write the coverage results. :param show_missing: Show lines that had no hits. :param summary: Include coverage summary per module. @@ -91,13 +87,10 @@ class CoverageResults: def write_results_file( self, path: StrPath, lines: Sequence[str], lnotab: Any, lines_hit: Mapping[int, int], encoding: str | None = None ) -> tuple[int, int]: - """ - Return a coverage results file in path. - """ + """Return a coverage results file in path.""" def is_ignored_filename(self, filename: str) -> bool: # undocumented - """ - Return True if the filename does not refer to a file + """Return True if the filename does not refer to a file we want to have reported. """ @@ -128,8 +121,7 @@ class Trace: outfile: StrPath | None = None, timing: bool = False, ) -> None: - """ - @param count true iff it should count number of times each + """@param count true iff it should count number of times each line is executed @param trace true iff it should print out each line that is being counted @@ -153,22 +145,19 @@ class Trace: def runfunc(self, func: Callable[_P, _T], /, *args: _P.args, **kw: _P.kwargs) -> _T: ... def file_module_function_of(self, frame: types.FrameType) -> _FileModuleFunction: ... def globaltrace_trackcallers(self, frame: types.FrameType, why: str, arg: Any) -> None: - """ - Handler for call events. + """Handler for call events. Adds information about who called who to the self._callers dict. """ def globaltrace_countfuncs(self, frame: types.FrameType, why: str, arg: Any) -> None: - """ - Handler for call events. + """Handler for call events. Adds (filename, modulename, funcname) to the self._calledfuncs dict. """ def globaltrace_lt(self, frame: types.FrameType, why: str, arg: Any) -> None: - """ - Handler for call events. + """Handler for call events. If the code block being entered is to be ignored, returns 'None', else returns self.localtrace. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/traceback.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/traceback.pyi index a34a15a928..868c8ba51c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/traceback.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/traceback.pyi @@ -37,8 +37,7 @@ if sys.version_info >= (3, 14): _FrameSummaryTuple: TypeAlias = tuple[str, int, str, str | None] def print_tb(tb: TracebackType | None, limit: int | None = None, file: SupportsWrite[str] | None = None) -> None: - """ - Print up to 'limit' stack trace entries from the traceback 'tb'. + """Print up to 'limit' stack trace entries from the traceback 'tb'. If 'limit' is omitted or None, all entries are printed. If 'file' is omitted or None, the output goes to sys.stderr; otherwise @@ -57,8 +56,7 @@ if sys.version_info >= (3, 10): file: SupportsWrite[str] | None = None, chain: bool = True, ) -> None: - """ - Print exception up to 'limit' stack trace entries from 'tb' to 'file'. + """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. This differs from print_tb() in the following ways: (1) if traceback is not None, it prints a header "Traceback (most recent @@ -82,8 +80,7 @@ if sys.version_info >= (3, 10): limit: int | None = None, chain: bool = True, ) -> list[str]: - """ - Format a stack trace and the exception information. + """Format a stack trace and the exception information. The arguments have the same meaning as the corresponding arguments to print_exception(). The return value is a list of strings, each @@ -104,8 +101,7 @@ else: file: SupportsWrite[str] | None = None, chain: bool = True, ) -> None: - """ - Print exception up to 'limit' stack trace entries from 'tb' to 'file'. + """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. This differs from print_tb() in the following ways: (1) if traceback is not None, it prints a header "Traceback (most recent @@ -123,8 +119,7 @@ else: limit: int | None = None, chain: bool = True, ) -> list[str]: - """ - Format a stack trace and the exception information. + """Format a stack trace and the exception information. The arguments have the same meaning as the corresponding arguments to print_exception(). The return value is a list of strings, each @@ -134,18 +129,13 @@ else: """ def print_exc(limit: int | None = None, file: SupportsWrite[str] | None = None, chain: bool = True) -> None: - """ - Shorthand for 'print_exception(sys.exception(), limit=limit, file=file, chain=chain)'. - """ + """Shorthand for 'print_exception(sys.exception(), limit=limit, file=file, chain=chain)'.""" def print_last(limit: int | None = None, file: SupportsWrite[str] | None = None, chain: bool = True) -> None: - """ - This is a shorthand for 'print_exception(sys.last_exc, limit=limit, file=file, chain=chain)'. - """ + """This is a shorthand for 'print_exception(sys.last_exc, limit=limit, file=file, chain=chain)'.""" def print_stack(f: FrameType | None = None, limit: int | None = None, file: SupportsWrite[str] | None = None) -> None: - """ - Print a stack trace from its invocation point. + """Print a stack trace from its invocation point. The optional 'f' argument can be used to specify an alternate stack frame at which to start. The optional 'limit' and 'file' @@ -153,8 +143,7 @@ def print_stack(f: FrameType | None = None, limit: int | None = None, file: Supp """ def extract_tb(tb: TracebackType | None, limit: int | None = None) -> StackSummary: - """ - Return a StackSummary object representing a list of + """Return a StackSummary object representing a list of pre-processed entries from traceback. This is useful for alternate formatting of stack traces. If @@ -167,8 +156,7 @@ def extract_tb(tb: TracebackType | None, limit: int | None = None) -> StackSumma """ def extract_stack(f: FrameType | None = None, limit: int | None = None) -> StackSummary: - """ - Extract the raw traceback from the current stack frame. + """Extract the raw traceback from the current stack frame. The return value has the same format as for extract_tb(). The optional 'f' and 'limit' arguments have the same meaning as for @@ -178,8 +166,7 @@ def extract_stack(f: FrameType | None = None, limit: int | None = None) -> Stack """ def format_list(extracted_list: Iterable[FrameSummary | _FrameSummaryTuple]) -> list[str]: - """ - Format a list of tuples or FrameSummary objects for printing. + """Format a list of tuples or FrameSummary objects for printing. Given a list of tuples or FrameSummary objects as returned by extract_tb() or extract_stack(), return a list of strings ready @@ -192,16 +179,14 @@ def format_list(extracted_list: Iterable[FrameSummary | _FrameSummaryTuple]) -> """ def print_list(extracted_list: Iterable[FrameSummary | _FrameSummaryTuple], file: SupportsWrite[str] | None = None) -> None: - """ - Print the list of tuples as returned by extract_tb() or + """Print the list of tuples as returned by extract_tb() or extract_stack() as a formatted stack trace to the given file. """ if sys.version_info >= (3, 13): @overload def format_exception_only(exc: BaseException | None, /, *, show_group: bool = False) -> list[str]: - """ - Format the exception part of a traceback. + """Format the exception part of a traceback. The return value is a list of strings, each ending in a newline. @@ -222,8 +207,7 @@ if sys.version_info >= (3, 13): elif sys.version_info >= (3, 10): @overload def format_exception_only(exc: BaseException | None, /) -> list[str]: - """ - Format the exception part of a traceback. + """Format the exception part of a traceback. The return value is a list of strings, each ending in a newline. @@ -239,8 +223,7 @@ elif sys.version_info >= (3, 10): else: def format_exception_only(etype: type[BaseException] | None, value: BaseException | None) -> list[str]: - """ - Format the exception part of a traceback. + """Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. The return value is a list of @@ -256,36 +239,26 @@ else: """ def format_exc(limit: int | None = None, chain: bool = True) -> str: - """ - Like print_exc() but return a string. - """ + """Like print_exc() but return a string.""" def format_tb(tb: TracebackType | None, limit: int | None = None) -> list[str]: - """ - A shorthand for 'format_list(extract_tb(tb, limit))'. - """ + """A shorthand for 'format_list(extract_tb(tb, limit))'.""" def format_stack(f: FrameType | None = None, limit: int | None = None) -> list[str]: - """ - Shorthand for 'format_list(extract_stack(f, limit))'. - """ + """Shorthand for 'format_list(extract_stack(f, limit))'.""" def clear_frames(tb: TracebackType | None) -> None: - """ - Clear all references to local variables in the frames of a traceback. - """ + """Clear all references to local variables in the frames of a traceback.""" def walk_stack(f: FrameType | None) -> Iterator[tuple[FrameType, int]]: - """ - Walk a stack yielding the frame and line number for each frame. + """Walk a stack yielding the frame and line number for each frame. This will follow f.f_back from the given frame. If no frame is given, the current stack is used. Usually used with StackSummary.extract. """ def walk_tb(tb: TracebackType | None) -> Iterator[tuple[FrameType, int]]: - """ - Walk a traceback yielding the frame and line number for each frame. + """Walk a traceback yielding the frame and line number for each frame. This will follow tb.tb_next (and thus is in the opposite order to walk_stack). Usually used with StackSummary.extract. @@ -297,8 +270,7 @@ if sys.version_info >= (3, 11): def emit(self, text_gen: str | Iterable[str], margin_char: str | None = None) -> Generator[str, None, None]: ... class TracebackException: - """ - An exception ready for rendering. + """An exception ready for rendering. The traceback module captures enough attributes from the original exception to this intermediary form to ensure that no references are held, while @@ -435,9 +407,7 @@ class TracebackException: max_group_width: int = 15, max_group_depth: int = 10, ) -> Self: - """ - Create a TracebackException from an exception. - """ + """Create a TracebackException from an exception.""" elif sys.version_info >= (3, 10): @classmethod def from_exception( @@ -449,24 +419,19 @@ class TracebackException: capture_locals: bool = False, compact: bool = False, ) -> Self: - """ - Create a TracebackException from an exception. - """ + """Create a TracebackException from an exception.""" else: @classmethod def from_exception( cls, exc: BaseException, *, limit: int | None = None, lookup_lines: bool = True, capture_locals: bool = False ) -> Self: - """ - Create a TracebackException from an exception. - """ + """Create a TracebackException from an exception.""" def __eq__(self, other: object) -> bool: ... __hash__: ClassVar[None] # type: ignore[assignment] if sys.version_info >= (3, 11): def format(self, *, chain: bool = True, _ctx: _ExceptionPrintContext | None = None) -> Generator[str, None, None]: - """ - Format the exception. + """Format the exception. If chain is not *True*, *__cause__* and *__context__* will not be formatted. @@ -479,8 +444,7 @@ class TracebackException: """ else: def format(self, *, chain: bool = True) -> Generator[str, None, None]: - """ - Format the exception. + """Format the exception. If chain is not *True*, *__cause__* and *__context__* will not be formatted. @@ -493,8 +457,7 @@ class TracebackException: """ if sys.version_info >= (3, 13): def format_exception_only(self, *, show_group: bool = False, _depth: int = 0) -> Generator[str, None, None]: - """ - Format the exception part of the traceback. + """Format the exception part of the traceback. The return value is a generator of strings, each ending in a newline. @@ -512,8 +475,7 @@ class TracebackException: """ else: def format_exception_only(self) -> Generator[str, None, None]: - """ - Format the exception part of the traceback. + """Format the exception part of the traceback. The return value is a generator of strings, each ending in a newline. @@ -531,13 +493,10 @@ class TracebackException: """ if sys.version_info >= (3, 11): def print(self, *, file: SupportsWrite[str] | None = None, chain: bool = True) -> None: - """ - Print the result of self.format(chain=chain) to 'file'. - """ + """Print the result of self.format(chain=chain) to 'file'.""" class FrameSummary: - """ - Information about a single frame from a traceback. + """Information about a single frame from a traceback. - :attr:`filename` The filename for the frame. - :attr:`lineno` The line within filename for the frame that was @@ -564,8 +523,7 @@ class FrameSummary: colno: int | None = None, end_colno: int | None = None, ) -> None: - """ - Construct a FrameSummary. + """Construct a FrameSummary. :param lookup_line: If True, `linecache` is consulted for the source code line. Otherwise, the line will be looked up when first needed. @@ -588,8 +546,7 @@ class FrameSummary: locals: Mapping[str, str] | None = None, line: str | None = None, ) -> None: - """ - Construct a FrameSummary. + """Construct a FrameSummary. :param lookup_line: If True, `linecache` is consulted for the source code line. Otherwise, the line will be looked up when first needed. @@ -622,9 +579,7 @@ class FrameSummary: __hash__: ClassVar[None] # type: ignore[assignment] class StackSummary(list[FrameSummary]): - """ - A list of FrameSummary objects, representing a stack of frames. - """ + """A list of FrameSummary objects, representing a stack of frames.""" @classmethod def extract( @@ -635,8 +590,7 @@ class StackSummary(list[FrameSummary]): lookup_lines: bool = True, capture_locals: bool = False, ) -> StackSummary: - """ - Create a StackSummary from a traceback or stack object. + """Create a StackSummary from a traceback or stack object. :param frame_gen: A generator that yields (frame, lineno) tuples whose summaries are to be included in the stack. @@ -650,22 +604,19 @@ class StackSummary(list[FrameSummary]): @classmethod def from_list(cls, a_list: Iterable[FrameSummary | _FrameSummaryTuple]) -> StackSummary: - """ - Create a StackSummary object from a supplied list of + """Create a StackSummary object from a supplied list of FrameSummary objects or old-style list of tuples. """ if sys.version_info >= (3, 11): def format_frame_summary(self, frame_summary: FrameSummary) -> str: - """ - Format the lines for a single FrameSummary. + """Format the lines for a single FrameSummary. Returns a string representing one frame involved in the stack. This gets called for every frame to be printed in the stack summary. """ def format(self) -> list[str]: - """ - Format the stack ready for printing. + """Format the stack ready for printing. Returns a list of strings ready for printing. Each string in the resulting list corresponds to a single frame from the stack. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/tracemalloc.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/tracemalloc.pyi index 6b4419a47c..3f1ff3cf57 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/tracemalloc.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/tracemalloc.pyi @@ -5,8 +5,7 @@ from typing import Any, SupportsIndex, overload from typing_extensions import TypeAlias def get_object_traceback(obj: object) -> Traceback | None: - """ - Get the traceback where the Python object *obj* was allocated. + """Get the traceback where the Python object *obj* was allocated. Return a Traceback instance. Return None if the tracemalloc module is not tracing memory allocations or @@ -14,9 +13,7 @@ def get_object_traceback(obj: object) -> Traceback | None: """ def take_snapshot() -> Snapshot: - """ - Take a snapshot of traces of memory blocks allocated by Python. - """ + """Take a snapshot of traces of memory blocks allocated by Python.""" class BaseFilter: inclusive: bool @@ -43,9 +40,7 @@ class Filter(BaseFilter): ) -> None: ... class Statistic: - """ - Statistic difference on memory allocations between two Snapshot instance. - """ + """Statistic difference on memory allocations between two Snapshot instance.""" count: int size: int @@ -55,8 +50,7 @@ class Statistic: def __hash__(self) -> int: ... class StatisticDiff: - """ - Statistic difference on memory allocations between an old and a new + """Statistic difference on memory allocations between an old and a new Snapshot instance. """ @@ -72,9 +66,7 @@ class StatisticDiff: _FrameTuple: TypeAlias = tuple[str, int] class Frame: - """ - Frame of a traceback. - """ + """Frame of a traceback.""" @property def filename(self) -> str: ... @@ -86,41 +78,27 @@ class Frame: def __lt__(self, other: Frame) -> bool: ... if sys.version_info >= (3, 11): def __gt__(self, other: Frame) -> bool: - """ - Return a > b. Computed by @total_ordering from (not a < b) and (a != b). - """ + """Return a > b. Computed by @total_ordering from (not a < b) and (a != b).""" def __ge__(self, other: Frame) -> bool: - """ - Return a >= b. Computed by @total_ordering from (not a < b). - """ + """Return a >= b. Computed by @total_ordering from (not a < b).""" def __le__(self, other: Frame) -> bool: - """ - Return a <= b. Computed by @total_ordering from (a < b) or (a == b). - """ + """Return a <= b. Computed by @total_ordering from (a < b) or (a == b).""" else: def __gt__(self, other: Frame, NotImplemented: Any = ...) -> bool: - """ - Return a > b. Computed by @total_ordering from (not a < b) and (a != b). - """ + """Return a > b. Computed by @total_ordering from (not a < b) and (a != b).""" def __ge__(self, other: Frame, NotImplemented: Any = ...) -> bool: - """ - Return a >= b. Computed by @total_ordering from (not a < b). - """ + """Return a >= b. Computed by @total_ordering from (not a < b).""" def __le__(self, other: Frame, NotImplemented: Any = ...) -> bool: - """ - Return a <= b. Computed by @total_ordering from (a < b) or (a == b). - """ + """Return a <= b. Computed by @total_ordering from (a < b) or (a == b).""" _TraceTuple: TypeAlias = tuple[int, int, Sequence[_FrameTuple], int | None] | tuple[int, int, Sequence[_FrameTuple]] class Trace: - """ - Trace of a memory block. - """ + """Trace of a memory block.""" @property def domain(self) -> int: ... @@ -133,8 +111,7 @@ class Trace: def __hash__(self) -> int: ... class Traceback(Sequence[Frame]): - """ - Sequence of Frame instances sorted from the oldest frame + """Sequence of Frame instances sorted from the oldest frame to the most recent frame. """ @@ -153,69 +130,48 @@ class Traceback(Sequence[Frame]): def __lt__(self, other: Traceback) -> bool: ... if sys.version_info >= (3, 11): def __gt__(self, other: Traceback) -> bool: - """ - Return a > b. Computed by @total_ordering from (not a < b) and (a != b). - """ + """Return a > b. Computed by @total_ordering from (not a < b) and (a != b).""" def __ge__(self, other: Traceback) -> bool: - """ - Return a >= b. Computed by @total_ordering from (not a < b). - """ + """Return a >= b. Computed by @total_ordering from (not a < b).""" def __le__(self, other: Traceback) -> bool: - """ - Return a <= b. Computed by @total_ordering from (a < b) or (a == b). - """ + """Return a <= b. Computed by @total_ordering from (a < b) or (a == b).""" else: def __gt__(self, other: Traceback, NotImplemented: Any = ...) -> bool: - """ - Return a > b. Computed by @total_ordering from (not a < b) and (a != b). - """ + """Return a > b. Computed by @total_ordering from (not a < b) and (a != b).""" def __ge__(self, other: Traceback, NotImplemented: Any = ...) -> bool: - """ - Return a >= b. Computed by @total_ordering from (not a < b). - """ + """Return a >= b. Computed by @total_ordering from (not a < b).""" def __le__(self, other: Traceback, NotImplemented: Any = ...) -> bool: - """ - Return a <= b. Computed by @total_ordering from (a < b) or (a == b). - """ + """Return a <= b. Computed by @total_ordering from (a < b) or (a == b).""" class Snapshot: - """ - Snapshot of traces of memory blocks allocated by Python. - """ + """Snapshot of traces of memory blocks allocated by Python.""" def __init__(self, traces: Sequence[_TraceTuple], traceback_limit: int) -> None: ... def compare_to(self, old_snapshot: Snapshot, key_type: str, cumulative: bool = False) -> list[StatisticDiff]: - """ - Compute the differences with an old snapshot old_snapshot. Get + """Compute the differences with an old snapshot old_snapshot. Get statistics as a sorted list of StatisticDiff instances, grouped by group_by. """ def dump(self, filename: str) -> None: - """ - Write the snapshot into a file. - """ + """Write the snapshot into a file.""" def filter_traces(self, filters: Sequence[DomainFilter | Filter]) -> Snapshot: - """ - Create a new Snapshot instance with a filtered traces sequence, filters + """Create a new Snapshot instance with a filtered traces sequence, filters is a list of Filter or DomainFilter instances. If filters is an empty list, return a new Snapshot instance with a copy of the traces. """ @staticmethod def load(filename: str) -> Snapshot: - """ - Load a snapshot from a file. - """ + """Load a snapshot from a file.""" def statistics(self, key_type: str, cumulative: bool = False) -> list[Statistic]: - """ - Group statistics by key_type. Return a sorted list of Statistic + """Group statistics by key_type. Return a sorted list of Statistic instances. """ traceback_limit: int diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/tty.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/tty.pyi index 584467f47f..e000b33fef 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/tty.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/tty.pyi @@ -27,21 +27,13 @@ if sys.platform != "win32": OSPEED: Final[int] CC: Final[int] def setraw(fd: _FD, when: int = 2) -> _ModeSetterReturn: - """ - Put terminal into raw mode. - """ + """Put terminal into raw mode.""" def setcbreak(fd: _FD, when: int = 2) -> _ModeSetterReturn: - """ - Put terminal into cbreak mode. - """ + """Put terminal into cbreak mode.""" if sys.version_info >= (3, 12): def cfmakeraw(mode: termios._Attr) -> None: - """ - Make termios mode raw. - """ + """Make termios mode raw.""" def cfmakecbreak(mode: termios._Attr) -> None: - """ - Make termios mode cbreak. - """ + """Make termios mode cbreak.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/turtle.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/turtle.pyi index e9345a18d1..b2447c94a6 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/turtle.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/turtle.pyi @@ -1,4 +1,5 @@ """ + Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzig and Seymour Papert in 1966. @@ -240,8 +241,7 @@ _Speed: TypeAlias = str | float _PolygonCoords: TypeAlias = Sequence[tuple[float, float]] class Vec2D(tuple[float, float]): - """ - A 2 dimensional vector class, used as a helper class + """A 2 dimensional vector class, used as a helper class for implementing turtle graphics. May be useful for turtle graphics programs also. Derived from tuple, so a vector is a tuple! @@ -266,14 +266,11 @@ class Vec2D(tuple[float, float]): def __neg__(self) -> Vec2D: ... def __abs__(self) -> float: ... def rotate(self, angle: float) -> Vec2D: - """ - rotate self counterclockwise by angle - """ + """rotate self counterclockwise by angle""" # Does not actually inherit from Canvas, but dynamically gets all methods of Canvas class ScrolledCanvas(Canvas, Frame): # type: ignore[misc] - """ - Modeled after the scrolled canvas class from Grayons's Tkinter book. + """Modeled after the scrolled canvas class from Grayons's Tkinter book. Used as the default canvas, which pops up automatically when using turtle graphics functions or the Turtle class. @@ -288,13 +285,10 @@ class ScrolledCanvas(Canvas, Frame): # type: ignore[misc] canvwidth: int canvheight: int def reset(self, canvwidth: int | None = None, canvheight: int | None = None, bg: str | None = None) -> None: - """ - Adjust canvas and scrollbars according to given canvas size. - """ + """Adjust canvas and scrollbars according to given canvas size.""" class TurtleScreenBase: - """ - Provide the basic graphics functionality. + """Provide the basic graphics functionality. Interface between Tkinter and turtle.py. To port turtle.py to some different graphics toolkit @@ -308,8 +302,7 @@ class TurtleScreenBase: yscale: float def __init__(self, cv: Canvas) -> None: ... def mainloop(self) -> None: - """ - Starts event loop - calling Tkinter's mainloop function. + """Starts event loop - calling Tkinter's mainloop function. No argument. @@ -322,8 +315,7 @@ class TurtleScreenBase: """ def textinput(self, title: str, prompt: str) -> str | None: - """ - Pop up a dialog window for input of a string. + """Pop up a dialog window for input of a string. Arguments: title is the title of the dialog window, prompt is a text mostly describing what information to input. @@ -338,8 +330,7 @@ class TurtleScreenBase: def numinput( self, title: str, prompt: str, default: float | None = None, minval: float | None = None, maxval: float | None = None ) -> float | None: - """ - Pop up a dialog window for input of a number. + """Pop up a dialog window for input of a number. Arguments: title is the title of the dialog window, prompt is a text mostly describing what numerical information to input. @@ -357,21 +348,17 @@ class TurtleScreenBase: """ class Terminator(Exception): - """ - Will be raised in TurtleScreen.update, if _RUNNING becomes False. + """Will be raised in TurtleScreen.update, if _RUNNING becomes False. This stops execution of a turtle graphics script. Main purpose: use in the Demo-Viewer turtle.Demo.py. """ class TurtleGraphicsError(Exception): - """ - Some TurtleGraphics Error - """ + """Some TurtleGraphics Error""" class Shape: - """ - Data structure modeling shapes. + """Data structure modeling shapes. attribute _type is one of "polygon", "image", "compound" attribute _data is - depending on _type a poygon-tuple, @@ -380,8 +367,7 @@ class Shape: def __init__(self, type_: str, data: _PolygonCoords | PhotoImage | None = None) -> None: ... def addcomponent(self, poly: _PolygonCoords, fill: _Color, outline: _Color | None = None) -> None: - """ - Add component to a shape of type compound. + """Add component to a shape of type compound. Arguments: poly is a polygon, i. e. a tuple of number pairs. fill is the fillcolor of the component, @@ -398,8 +384,7 @@ class Shape: """ class TurtleScreen(TurtleScreenBase): - """ - Provides screen oriented methods like bgcolor etc. + """Provides screen oriented methods like bgcolor etc. Only relies upon the methods of TurtleScreenBase and NOT upon components of the underlying graphics toolkit - @@ -408,8 +393,7 @@ class TurtleScreen(TurtleScreenBase): def __init__(self, cv: Canvas, mode: str = "standard", colormode: float = 1.0, delay: int = 10) -> None: ... def clear(self) -> None: - """ - Delete all drawings and all turtles from the TurtleScreen. + """Delete all drawings and all turtles from the TurtleScreen. No argument. @@ -424,8 +408,7 @@ class TurtleScreen(TurtleScreenBase): @overload def mode(self, mode: None = None) -> str: - """ - Set turtle-mode ('standard', 'logo' or 'world') and perform reset. + """Set turtle-mode ('standard', 'logo' or 'world') and perform reset. Optional argument: mode -- one of the strings 'standard', 'logo' or 'world' @@ -450,8 +433,7 @@ class TurtleScreen(TurtleScreenBase): @overload def mode(self, mode: str) -> None: ... def setworldcoordinates(self, llx: float, lly: float, urx: float, ury: float) -> None: - """ - Set up a user defined coordinate-system. + """Set up a user defined coordinate-system. Arguments: llx -- a number, x-coordinate of lower left corner of canvas @@ -474,8 +456,7 @@ class TurtleScreen(TurtleScreenBase): """ def register_shape(self, name: str, shape: _PolygonCoords | Shape | None = None) -> None: - """ - Adds a turtle shape to TurtleScreen's shapelist. + """Adds a turtle shape to TurtleScreen's shapelist. Arguments: (1) name is the name of an image file (PNG, GIF, PGM, and PPM) and shape is None. @@ -503,8 +484,7 @@ class TurtleScreen(TurtleScreenBase): @overload def colormode(self, cmode: None = None) -> float: - """ - Return the colormode or set it to 1.0 or 255. + """Return the colormode or set it to 1.0 or 255. Optional argument: cmode -- one of the values 1.0 or 255 @@ -521,8 +501,7 @@ class TurtleScreen(TurtleScreenBase): @overload def colormode(self, cmode: float) -> None: ... def reset(self) -> None: - """ - Reset all Turtles on the Screen to their initial state. + """Reset all Turtles on the Screen to their initial state. No argument. @@ -531,8 +510,7 @@ class TurtleScreen(TurtleScreenBase): """ def turtles(self) -> list[Turtle]: - """ - Return the list of turtles on the screen. + """Return the list of turtles on the screen. Example (for a TurtleScreen instance named screen): >>> screen.turtles() @@ -541,8 +519,7 @@ class TurtleScreen(TurtleScreenBase): @overload def bgcolor(self) -> _AnyColor: - """ - Set or return backgroundcolor of the TurtleScreen. + """Set or return backgroundcolor of the TurtleScreen. Arguments (if given): a color string or three numbers in the range 0..colormode or a 3-tuple of such numbers. @@ -562,8 +539,7 @@ class TurtleScreen(TurtleScreenBase): def bgcolor(self, r: float, g: float, b: float) -> None: ... @overload def tracer(self, n: None = None) -> int: - """ - Turns turtle animation on/off and set delay for update drawings. + """Turns turtle animation on/off and set delay for update drawings. Optional arguments: n -- nonnegative integer @@ -586,8 +562,7 @@ class TurtleScreen(TurtleScreenBase): def tracer(self, n: int, delay: int | None = None) -> None: ... @overload def delay(self, delay: None = None) -> int: - """ - Return or set the drawing delay in milliseconds. + """Return or set the drawing delay in milliseconds. Optional argument: delay -- positive integer @@ -603,8 +578,7 @@ class TurtleScreen(TurtleScreenBase): if sys.version_info >= (3, 14): @contextmanager def no_animation(self) -> Generator[None]: - """ - Temporarily turn off auto-updating the screen. + """Temporarily turn off auto-updating the screen. This is useful for drawing complex shapes where even the fastest setting is too slow. Once this context manager is exited, the drawing will @@ -617,13 +591,10 @@ class TurtleScreen(TurtleScreenBase): """ def update(self) -> None: - """ - Perform a TurtleScreen update. - """ + """Perform a TurtleScreen update.""" def window_width(self) -> int: - """ - Return the width of the turtle window. + """Return the width of the turtle window. Example (for a TurtleScreen instance named screen): >>> screen.window_width() @@ -631,8 +602,7 @@ class TurtleScreen(TurtleScreenBase): """ def window_height(self) -> int: - """ - Return the height of the turtle window. + """Return the height of the turtle window. Example (for a TurtleScreen instance named screen): >>> screen.window_height() @@ -640,8 +610,7 @@ class TurtleScreen(TurtleScreenBase): """ def getcanvas(self) -> Canvas: - """ - Return the Canvas of this TurtleScreen. + """Return the Canvas of this TurtleScreen. No argument. @@ -652,8 +621,7 @@ class TurtleScreen(TurtleScreenBase): """ def getshapes(self) -> list[str]: - """ - Return a list of names of all currently available turtle shapes. + """Return a list of names of all currently available turtle shapes. No argument. @@ -663,8 +631,7 @@ class TurtleScreen(TurtleScreenBase): """ def onclick(self, fun: Callable[[float, float], object], btn: int = 1, add: Any | None = None) -> None: - """ - Bind fun to mouse-click event on canvas. + """Bind fun to mouse-click event on canvas. Arguments: fun -- a function with two arguments, the coordinates of the @@ -680,8 +647,7 @@ class TurtleScreen(TurtleScreenBase): """ def onkey(self, fun: Callable[[], object], key: str) -> None: - """ - Bind fun to key-release event of key. + """Bind fun to key-release event of key. Arguments: fun -- a function with no arguments @@ -704,8 +670,7 @@ class TurtleScreen(TurtleScreenBase): """ def listen(self, xdummy: float | None = None, ydummy: float | None = None) -> None: - """ - Set focus on TurtleScreen (in order to collect key-events) + """Set focus on TurtleScreen (in order to collect key-events) No arguments. Dummy arguments are provided in order @@ -716,8 +681,7 @@ class TurtleScreen(TurtleScreenBase): """ def ontimer(self, fun: Callable[[], object], t: int = 0) -> None: - """ - Install a timer, which calls fun after t milliseconds. + """Install a timer, which calls fun after t milliseconds. Arguments: fun -- a function with no arguments. @@ -738,8 +702,7 @@ class TurtleScreen(TurtleScreenBase): @overload def bgpic(self, picname: None = None) -> str: - """ - Set background image or return name of current backgroundimage. + """Set background image or return name of current backgroundimage. Optional argument: picname -- a string, name of an image file (PNG, GIF, PGM, and PPM) or "nopic". @@ -760,8 +723,7 @@ class TurtleScreen(TurtleScreenBase): def bgpic(self, picname: str) -> None: ... @overload def screensize(self, canvwidth: None = None, canvheight: None = None, bg: None = None) -> tuple[int, int]: - """ - Resize the canvas the turtles are drawing on. + """Resize the canvas the turtles are drawing on. Optional arguments: canvwidth -- positive integer, new width of canvas in pixels @@ -782,8 +744,7 @@ class TurtleScreen(TurtleScreenBase): def screensize(self, canvwidth: int, canvheight: int, bg: _Color | None = None) -> None: ... if sys.version_info >= (3, 14): def save(self, filename: StrPath, *, overwrite: bool = False) -> None: - """ - Save the drawing as a PostScript file + """Save the drawing as a PostScript file Arguments: filename -- a string, the path of the created file. @@ -800,8 +761,7 @@ class TurtleScreen(TurtleScreenBase): clearscreen = clear addshape = register_shape def onkeypress(self, fun: Callable[[], object], key: str | None = None) -> None: - """ - Bind fun to key-press event of key if key is given, + """Bind fun to key-press event of key if key is given, or to any key-press-event if no key is given. Arguments: @@ -828,8 +788,7 @@ class TurtleScreen(TurtleScreenBase): onkeyrelease = onkey class TNavigator: - """ - Navigation part of the RawTurtle. + """Navigation part of the RawTurtle. Implements methods for turtle movement. """ @@ -839,15 +798,13 @@ class TNavigator: DEFAULT_ANGLEORIENT: int def __init__(self, mode: str = "standard") -> None: ... def reset(self) -> None: - """ - reset turtle to its initial values + """reset turtle to its initial values Will be overwritten by parent class """ def degrees(self, fullcircle: float = 360.0) -> None: - """ - Set angle measurement units to degrees. + """Set angle measurement units to degrees. Optional argument: fullcircle - a number @@ -869,8 +826,7 @@ class TNavigator: """ def radians(self) -> None: - """ - Set the angle measurement units to radians. + """Set the angle measurement units to radians. No arguments. @@ -883,14 +839,12 @@ class TNavigator: """ if sys.version_info >= (3, 12): def teleport(self, x: float | None = None, y: float | None = None, *, fill_gap: bool = False) -> None: - """ - To be overwritten by child class RawTurtle. + """To be overwritten by child class RawTurtle. Includes no TPen references. """ def forward(self, distance: float) -> None: - """ - Move the turtle forward by the specified distance. + """Move the turtle forward by the specified distance. Aliases: forward | fd @@ -912,8 +866,7 @@ class TNavigator: """ def back(self, distance: float) -> None: - """ - Move the turtle backward by distance. + """Move the turtle backward by distance. Aliases: back | backward | bk @@ -932,8 +885,7 @@ class TNavigator: """ def right(self, angle: float) -> None: - """ - Turn turtle right by angle units. + """Turn turtle right by angle units. Aliases: right | rt @@ -953,8 +905,7 @@ class TNavigator: """ def left(self, angle: float) -> None: - """ - Turn turtle left by angle units. + """Turn turtle left by angle units. Aliases: left | lt @@ -974,8 +925,7 @@ class TNavigator: """ def pos(self) -> Vec2D: - """ - Return the turtle's current location (x,y), as a Vec2D-vector. + """Return the turtle's current location (x,y), as a Vec2D-vector. Aliases: pos | position @@ -987,8 +937,7 @@ class TNavigator: """ def xcor(self) -> float: - """ - Return the turtle's x coordinate. + """Return the turtle's x coordinate. No arguments. @@ -1001,8 +950,7 @@ class TNavigator: """ def ycor(self) -> float: - """ - Return the turtle's y coordinate + """Return the turtle's y coordinate --- No arguments. @@ -1016,8 +964,7 @@ class TNavigator: @overload def goto(self, x: tuple[float, float], y: None = None) -> None: - """ - Move turtle to an absolute position. + """Move turtle to an absolute position. Aliases: setpos | setposition | goto: @@ -1050,8 +997,7 @@ class TNavigator: @overload def goto(self, x: float, y: float) -> None: ... def home(self) -> None: - """ - Move turtle to the origin - coordinates (0,0). + """Move turtle to the origin - coordinates (0,0). No arguments. @@ -1063,8 +1009,7 @@ class TNavigator: """ def setx(self, x: float) -> None: - """ - Set the turtle's first coordinate to x + """Set the turtle's first coordinate to x Argument: x -- a number (integer or float) @@ -1081,8 +1026,7 @@ class TNavigator: """ def sety(self, y: float) -> None: - """ - Set the turtle's second coordinate to y + """Set the turtle's second coordinate to y Argument: y -- a number (integer or float) @@ -1100,8 +1044,7 @@ class TNavigator: @overload def distance(self, x: TNavigator | tuple[float, float], y: None = None) -> float: - """ - Return the distance from the turtle to (x,y) in turtle step units. + """Return the distance from the turtle to (x,y) in turtle step units. Arguments: x -- a number or a pair/vector of numbers or a turtle instance @@ -1127,8 +1070,7 @@ class TNavigator: def distance(self, x: float, y: float) -> float: ... @overload def towards(self, x: TNavigator | tuple[float, float], y: None = None) -> float: - """ - Return the angle of the line from the turtle's position to (x, y). + """Return the angle of the line from the turtle's position to (x, y). Arguments: x -- a number or a pair/vector of numbers or a turtle instance @@ -1153,8 +1095,7 @@ class TNavigator: @overload def towards(self, x: float, y: float) -> float: ... def heading(self) -> float: - """ - Return the turtle's current heading. + """Return the turtle's current heading. No arguments. @@ -1165,8 +1106,7 @@ class TNavigator: """ def setheading(self, to_angle: float) -> None: - """ - Set the orientation of the turtle to to_angle. + """Set the orientation of the turtle to to_angle. Aliases: setheading | seth @@ -1190,8 +1130,7 @@ class TNavigator: """ def circle(self, radius: float, extent: float | None = None, steps: int | None = None) -> None: - """ - Draw a circle with given radius. + """Draw a circle with given radius. Arguments: radius -- a number @@ -1222,9 +1161,7 @@ class TNavigator: """ def speed(self, s: int | None = 0) -> int | None: - """ - dummy method - to be overwritten by child class - """ + """dummy method - to be overwritten by child class""" fd = forward bk = back backward = back @@ -1236,16 +1173,14 @@ class TNavigator: seth = setheading class TPen: - """ - Drawing part of the RawTurtle. + """Drawing part of the RawTurtle. Implements drawing properties. """ def __init__(self, resizemode: str = "noresize") -> None: ... @overload def resizemode(self, rmode: None = None) -> str: - """ - Set resizemode to one of the values: "auto", "user", "noresize". + """Set resizemode to one of the values: "auto", "user", "noresize". (Optional) Argument: rmode -- one of the strings "auto", "user", "noresize" @@ -1271,8 +1206,7 @@ class TPen: def resizemode(self, rmode: str) -> None: ... @overload def pensize(self, width: None = None) -> int: - """ - Set or return the line thickness. + """Set or return the line thickness. Aliases: pensize | width @@ -1293,8 +1227,7 @@ class TPen: @overload def pensize(self, width: int) -> None: ... def penup(self) -> None: - """ - Pull the pen up -- no drawing when moving. + """Pull the pen up -- no drawing when moving. Aliases: penup | pu | up @@ -1305,8 +1238,7 @@ class TPen: """ def pendown(self) -> None: - """ - Pull the pen down -- drawing when moving. + """Pull the pen down -- drawing when moving. Aliases: pendown | pd | down @@ -1317,8 +1249,7 @@ class TPen: """ def isdown(self) -> bool: - """ - Return True if pen is down, False if it's up. + """Return True if pen is down, False if it's up. No argument. @@ -1333,8 +1264,7 @@ class TPen: @overload def speed(self, speed: None = None) -> int: - """ - Return or set the turtle's speed. + """Return or set the turtle's speed. Optional argument: speed -- an integer in the range 0..10 or a speedstring (see below) @@ -1365,8 +1295,7 @@ class TPen: def speed(self, speed: _Speed) -> None: ... @overload def pencolor(self) -> _AnyColor: - """ - Return or set the pencolor. + """Return or set the pencolor. Arguments: Four input formats are allowed: @@ -1401,8 +1330,7 @@ class TPen: def pencolor(self, r: float, g: float, b: float) -> None: ... @overload def fillcolor(self) -> _AnyColor: - """ - Return or set the fillcolor. + """Return or set the fillcolor. Arguments: Four input formats are allowed: @@ -1436,8 +1364,7 @@ class TPen: def fillcolor(self, r: float, g: float, b: float) -> None: ... @overload def color(self) -> tuple[_AnyColor, _AnyColor]: - """ - Return or set the pencolor and fillcolor. + """Return or set the pencolor and fillcolor. Arguments: Several input formats are allowed. @@ -1477,14 +1404,12 @@ class TPen: def color(self, color1: _Color, color2: _Color) -> None: ... if sys.version_info >= (3, 12): def teleport(self, x: float | None = None, y: float | None = None, *, fill_gap: bool = False) -> None: - """ - To be overwritten by child class RawTurtle. + """To be overwritten by child class RawTurtle. Includes no TNavigator references. """ def showturtle(self) -> None: - """ - Makes the turtle visible. + """Makes the turtle visible. Aliases: showturtle | st @@ -1496,8 +1421,7 @@ class TPen: """ def hideturtle(self) -> None: - """ - Makes the turtle invisible. + """Makes the turtle invisible. Aliases: hideturtle | ht @@ -1512,8 +1436,7 @@ class TPen: """ def isvisible(self) -> bool: - """ - Return True if the Turtle is shown, False if it's hidden. + """Return True if the Turtle is shown, False if it's hidden. No argument. @@ -1525,8 +1448,7 @@ class TPen: # Note: signatures 1 and 2 overlap unsafely when no arguments are provided @overload def pen(self) -> _PenState: - """ - Return or set the pen's attributes. + """Return or set the pen's attributes. Arguments: pen -- a dictionary with some or all of the below listed keys. @@ -1598,8 +1520,7 @@ class TPen: ht = hideturtle class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods in base classes - """ - Animation part of the RawTurtle. + """Animation part of the RawTurtle. Puts RawTurtle upon a TurtleScreen and provides tools for its animation. """ @@ -1614,8 +1535,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods visible: bool = True, ) -> None: ... def reset(self) -> None: - """ - Delete the turtle's drawings and restore its default values. + """Delete the turtle's drawings and restore its default values. No argument. @@ -1635,8 +1555,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ def setundobuffer(self, size: int | None) -> None: - """ - Set or disable undobuffer. + """Set or disable undobuffer. Argument: size -- an integer or None @@ -1651,8 +1570,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ def undobufferentries(self) -> int: - """ - Return count of entries in the undobuffer. + """Return count of entries in the undobuffer. No argument. @@ -1662,8 +1580,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ def clear(self) -> None: - """ - Delete the turtle's drawings from the screen. Do not move turtle. + """Delete the turtle's drawings from the screen. Do not move turtle. No arguments. @@ -1676,8 +1593,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ def clone(self) -> Self: - """ - Create and return a clone of the turtle. + """Create and return a clone of the turtle. No argument. @@ -1691,8 +1607,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods @overload def shape(self, name: None = None) -> str: - """ - Set turtle shape to shape with given name / return current shapename. + """Set turtle shape to shape with given name / return current shapename. Optional argument: name -- a string, which is a valid shapename @@ -1717,8 +1632,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods # Unsafely overlaps when no arguments are provided @overload def shapesize(self) -> tuple[float, float, float]: - """ - Set/return turtle's stretchfactors/outline. Set resizemode to "user". + """Set/return turtle's stretchfactors/outline. Set resizemode to "user". Optional arguments: stretch_wid : positive number @@ -1745,8 +1659,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods ) -> None: ... @overload def shearfactor(self, shear: None = None) -> float: - """ - Set or return the current shearfactor. + """Set or return the current shearfactor. Optional argument: shear -- number, tangent of the shear angle @@ -1770,8 +1683,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods # Unsafely overlaps when no arguments are provided @overload def shapetransform(self) -> tuple[float, float, float, float]: - """ - Set or return the current transformation matrix of the turtle shape. + """Set or return the current transformation matrix of the turtle shape. Optional arguments: t11, t12, t21, t22 -- numbers. @@ -1796,8 +1708,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods self, t11: float | None = None, t12: float | None = None, t21: float | None = None, t22: float | None = None ) -> None: ... def get_shapepoly(self) -> _PolygonCoords | None: - """ - Return the current shape polygon as tuple of coordinate pairs. + """Return the current shape polygon as tuple of coordinate pairs. No argument. @@ -1812,8 +1723,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods @overload def tiltangle(self, angle: None = None) -> float: - """ - Set or return the current tilt-angle. + """Set or return the current tilt-angle. Optional argument: angle -- number @@ -1844,8 +1754,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods @overload def tiltangle(self, angle: float) -> None: ... def tilt(self, angle: float) -> None: - """ - Rotate the turtleshape by angle. + """Rotate the turtleshape by angle. Argument: angle - a number @@ -1865,8 +1774,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods # a compound stamp or not. So, as per the "no Union return" policy, # we return Any. def stamp(self) -> Any: - """ - Stamp a copy of the turtleshape onto the canvas and return its id. + """Stamp a copy of the turtleshape onto the canvas and return its id. No argument. @@ -1882,8 +1790,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ def clearstamp(self, stampid: int | tuple[int, ...]) -> None: - """ - Delete stamp with given stampid + """Delete stamp with given stampid Argument: stampid - an integer, must be return value of previous stamp() call. @@ -1896,8 +1803,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ def clearstamps(self, n: int | None = None) -> None: - """ - Delete all or first/last n of turtle's stamps. + """Delete all or first/last n of turtle's stamps. Optional argument: n -- an integer @@ -1916,8 +1822,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ def filling(self) -> bool: - """ - Return fillstate (True if filling, False else). + """Return fillstate (True if filling, False else). No argument. @@ -1931,8 +1836,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods if sys.version_info >= (3, 14): @contextmanager def fill(self) -> Generator[None]: - """ - A context manager for filling a shape. + """A context manager for filling a shape. Implicitly ensures the code block is wrapped with begin_fill() and end_fill(). @@ -1944,8 +1848,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ def begin_fill(self) -> None: - """ - Called just before drawing a shape to be filled. + """Called just before drawing a shape to be filled. No argument. @@ -1957,8 +1860,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ def end_fill(self) -> None: - """ - Fill the shape drawn after the call begin_fill(). + """Fill the shape drawn after the call begin_fill(). No argument. @@ -1970,8 +1872,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ def dot(self, size: int | None = None, *color: _Color) -> None: - """ - Draw a dot with diameter size, using color. + """Draw a dot with diameter size, using color. Optional arguments: size -- an integer >= 1 (if given) @@ -1988,8 +1889,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods def write( self, arg: object, move: bool = False, align: str = "left", font: tuple[str, int, str] = ("Arial", 8, "normal") ) -> None: - """ - Write text at the current turtle position. + """Write text at the current turtle position. Arguments: arg -- info, which is to be written to the TurtleScreen @@ -2010,8 +1910,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods if sys.version_info >= (3, 14): @contextmanager def poly(self) -> Generator[None]: - """ - A context manager for recording the vertices of a polygon. + """A context manager for recording the vertices of a polygon. Implicitly ensures that the code block is wrapped with begin_poly() and end_poly() @@ -2026,8 +1925,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ def begin_poly(self) -> None: - """ - Start recording the vertices of a polygon. + """Start recording the vertices of a polygon. No argument. @@ -2039,8 +1937,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ def end_poly(self) -> None: - """ - Stop recording the vertices of a polygon. + """Stop recording the vertices of a polygon. No argument. @@ -2052,8 +1949,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ def get_poly(self) -> _PolygonCoords | None: - """ - Return the lastly recorded polygon. + """Return the lastly recorded polygon. No argument. @@ -2063,8 +1959,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ def getscreen(self) -> TurtleScreen: - """ - Return the TurtleScreen object, the turtle is drawing on. + """Return the TurtleScreen object, the turtle is drawing on. No argument. @@ -2079,8 +1974,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ def getturtle(self) -> Self: - """ - Return the Turtleobject itself. + """Return the Turtleobject itself. No argument. @@ -2096,8 +1990,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ getpen = getturtle def onclick(self, fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: - """ - Bind fun to mouse-click event on this turtle on canvas. + """Bind fun to mouse-click event on this turtle on canvas. Arguments: fun -- a function with two arguments, to which will be assigned @@ -2116,8 +2009,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ def onrelease(self, fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: - """ - Bind fun to mouse-button-release event on this turtle on canvas. + """Bind fun to mouse-button-release event on this turtle on canvas. Arguments: fun -- a function with two arguments, to which will be assigned @@ -2140,8 +2032,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ def ondrag(self, fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: - """ - Bind fun to mouse-move event on this turtle on canvas. + """Bind fun to mouse-move event on this turtle on canvas. Arguments: fun -- a function with two arguments, to which will be assigned @@ -2160,8 +2051,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods """ def undo(self) -> None: - """ - undo (repeatedly) the last turtle action. + """undo (repeatedly) the last turtle action. No argument. @@ -2189,8 +2079,7 @@ class _Screen(TurtleScreen): startx: int | None = None, starty: int | None = None, ) -> None: - """ - Set the size and position of the main window. + """Set the size and position of the main window. Arguments: width: as integer a size in pixels, as float a fraction of the screen. @@ -2215,8 +2104,7 @@ class _Screen(TurtleScreen): """ def title(self, titlestring: str) -> None: - """ - Set title of turtle-window + """Set title of turtle-window Argument: titlestring -- a string, to appear in the titlebar of the @@ -2230,16 +2118,14 @@ class _Screen(TurtleScreen): """ def bye(self) -> None: - """ - Shut the turtlegraphics window. + """Shut the turtlegraphics window. Example (for a TurtleScreen instance named screen): >>> screen.bye() """ def exitonclick(self) -> None: - """ - Go into mainloop until the mouse is clicked. + """Go into mainloop until the mouse is clicked. No arguments. @@ -2258,8 +2144,7 @@ class _Screen(TurtleScreen): """ class Turtle(RawTurtle): - """ - RawTurtle auto-creating (scrolled) canvas. + """RawTurtle auto-creating (scrolled) canvas. When a Turtle object is created or a function derived from some Turtle method is called a TurtleScreen object is automatically created. @@ -2271,8 +2156,7 @@ RawPen = RawTurtle Pen = Turtle def write_docstringdict(filename: str = "turtle_docstringdict") -> None: - """ - Create and write docstring-dictionary to file. + """Create and write docstring-dictionary to file. Optional argument: filename -- a string, used as filename @@ -2298,8 +2182,7 @@ def write_docstringdict(filename: str = "turtle_docstringdict") -> None: # Note: mainloop() was always present in the global scope, but was added to # TurtleScreenBase in Python 3.0 def mainloop() -> None: - """ - Starts event loop - calling Tkinter's mainloop function. + """Starts event loop - calling Tkinter's mainloop function. No argument. @@ -2312,8 +2195,7 @@ def mainloop() -> None: """ def textinput(title: str, prompt: str) -> str | None: - """ - Pop up a dialog window for input of a string. + """Pop up a dialog window for input of a string. Arguments: title is the title of the dialog window, prompt is a text mostly describing what information to input. @@ -2328,8 +2210,7 @@ def textinput(title: str, prompt: str) -> str | None: def numinput( title: str, prompt: str, default: float | None = None, minval: float | None = None, maxval: float | None = None ) -> float | None: - """ - Pop up a dialog window for input of a number. + """Pop up a dialog window for input of a number. Arguments: title is the title of the dialog window, prompt is a text mostly describing what numerical information to input. @@ -2349,8 +2230,7 @@ def numinput( # Functions copied from TurtleScreen: def clear() -> None: - """ - Delete the turtle's drawings from the screen. Do not move + """Delete the turtle's drawings from the screen. Do not move No arguments. @@ -2364,8 +2244,7 @@ def clear() -> None: @overload def mode(mode: None = None) -> str: - """ - Set turtle-mode ('standard', 'logo' or 'world') and perform reset. + """Set turtle-mode ('standard', 'logo' or 'world') and perform reset. Optional argument: mode -- one of the strings 'standard', 'logo' or 'world' @@ -2390,8 +2269,7 @@ def mode(mode: None = None) -> str: @overload def mode(mode: str) -> None: ... def setworldcoordinates(llx: float, lly: float, urx: float, ury: float) -> None: - """ - Set up a user defined coordinate-system. + """Set up a user defined coordinate-system. Arguments: llx -- a number, x-coordinate of lower left corner of canvas @@ -2414,8 +2292,7 @@ def setworldcoordinates(llx: float, lly: float, urx: float, ury: float) -> None: """ def register_shape(name: str, shape: _PolygonCoords | Shape | None = None) -> None: - """ - Adds a turtle shape to TurtleScreen's shapelist. + """Adds a turtle shape to TurtleScreen's shapelist. Arguments: (1) name is the name of an image file (PNG, GIF, PGM, and PPM) and shape is None. @@ -2443,8 +2320,7 @@ def register_shape(name: str, shape: _PolygonCoords | Shape | None = None) -> No @overload def colormode(cmode: None = None) -> float: - """ - Return the colormode or set it to 1.0 or 255. + """Return the colormode or set it to 1.0 or 255. Optional argument: cmode -- one of the values 1.0 or 255 @@ -2461,8 +2337,7 @@ def colormode(cmode: None = None) -> float: @overload def colormode(cmode: float) -> None: ... def reset() -> None: - """ - Delete the turtle's drawings and restore its default values. + """Delete the turtle's drawings and restore its default values. No argument. @@ -2482,8 +2357,7 @@ def reset() -> None: """ def turtles() -> list[Turtle]: - """ - Return the list of turtles on the + """Return the list of turtles on the Example: >>> turtles() @@ -2492,8 +2366,7 @@ def turtles() -> list[Turtle]: @overload def bgcolor() -> _AnyColor: - """ - Set or return backgroundcolor of the TurtleScreen. + """Set or return backgroundcolor of the TurtleScreen. Arguments (if given): a color string or three numbers in the range 0..colormode or a 3-tuple of such numbers. @@ -2513,8 +2386,7 @@ def bgcolor(color: _Color) -> None: ... def bgcolor(r: float, g: float, b: float) -> None: ... @overload def tracer(n: None = None) -> int: - """ - Turns turtle animation on/off and set delay for update drawings. + """Turns turtle animation on/off and set delay for update drawings. Optional arguments: n -- nonnegative integer @@ -2537,8 +2409,7 @@ def tracer(n: None = None) -> int: def tracer(n: int, delay: int | None = None) -> None: ... @overload def delay(delay: None = None) -> int: - """ - Return or set the drawing delay in milliseconds. + """Return or set the drawing delay in milliseconds. Optional argument: delay -- positive integer @@ -2555,8 +2426,7 @@ def delay(delay: int) -> None: ... if sys.version_info >= (3, 14): @contextmanager def no_animation() -> Generator[None]: - """ - Temporarily turn off auto-updating the + """Temporarily turn off auto-updating the This is useful for drawing complex shapes where even the fastest setting is too slow. Once this context manager is exited, the drawing will @@ -2569,13 +2439,10 @@ if sys.version_info >= (3, 14): """ def update() -> None: - """ - Perform a TurtleScreen update. - """ + """Perform a TurtleScreen update.""" def window_width() -> int: - """ - Return the width of the turtle window. + """Return the width of the turtle window. Example: >>> window_width() @@ -2583,8 +2450,7 @@ def window_width() -> int: """ def window_height() -> int: - """ - Return the height of the turtle window. + """Return the height of the turtle window. Example: >>> window_height() @@ -2592,8 +2458,7 @@ def window_height() -> int: """ def getcanvas() -> Canvas: - """ - Return the Canvas of this TurtleScreen. + """Return the Canvas of this TurtleScreen. No argument. @@ -2604,8 +2469,7 @@ def getcanvas() -> Canvas: """ def getshapes() -> list[str]: - """ - Return a list of names of all currently available turtle shapes. + """Return a list of names of all currently available turtle shapes. No argument. @@ -2615,8 +2479,7 @@ def getshapes() -> list[str]: """ def onclick(fun: Callable[[float, float], object], btn: int = 1, add: Any | None = None) -> None: - """ - Bind fun to mouse-click event on this turtle on canvas. + """Bind fun to mouse-click event on this turtle on canvas. Arguments: fun -- a function with two arguments, to which will be assigned @@ -2635,8 +2498,7 @@ def onclick(fun: Callable[[float, float], object], btn: int = 1, add: Any | None """ def onkey(fun: Callable[[], object], key: str) -> None: - """ - Bind fun to key-release event of key. + """Bind fun to key-release event of key. Arguments: fun -- a function with no arguments @@ -2659,8 +2521,7 @@ def onkey(fun: Callable[[], object], key: str) -> None: """ def listen(xdummy: float | None = None, ydummy: float | None = None) -> None: - """ - Set focus on TurtleScreen (in order to collect key-events) + """Set focus on TurtleScreen (in order to collect key-events) No arguments. Dummy arguments are provided in order @@ -2671,8 +2532,7 @@ def listen(xdummy: float | None = None, ydummy: float | None = None) -> None: """ def ontimer(fun: Callable[[], object], t: int = 0) -> None: - """ - Install a timer, which calls fun after t milliseconds. + """Install a timer, which calls fun after t milliseconds. Arguments: fun -- a function with no arguments. @@ -2693,8 +2553,7 @@ def ontimer(fun: Callable[[], object], t: int = 0) -> None: @overload def bgpic(picname: None = None) -> str: - """ - Set background image or return name of current backgroundimage. + """Set background image or return name of current backgroundimage. Optional argument: picname -- a string, name of an image file (PNG, GIF, PGM, and PPM) or "nopic". @@ -2715,8 +2574,7 @@ def bgpic(picname: None = None) -> str: def bgpic(picname: str) -> None: ... @overload def screensize(canvwidth: None = None, canvheight: None = None, bg: None = None) -> tuple[int, int]: - """ - Resize the canvas the turtles are drawing on. + """Resize the canvas the turtles are drawing on. Optional arguments: canvwidth -- positive integer, new width of canvas in pixels @@ -2738,8 +2596,7 @@ def screensize(canvwidth: int, canvheight: int, bg: _Color | None = None) -> Non if sys.version_info >= (3, 14): def save(filename: StrPath, *, overwrite: bool = False) -> None: - """ - Save the drawing as a PostScript file + """Save the drawing as a PostScript file Arguments: filename -- a string, the path of the created file. @@ -2758,8 +2615,7 @@ clearscreen = clear addshape = register_shape def onkeypress(fun: Callable[[], object], key: str | None = None) -> None: - """ - Bind fun to key-press event of key if key is given, + """Bind fun to key-press event of key if key is given, or to any key-press-event if no key is given. Arguments: @@ -2789,8 +2645,7 @@ onkeyrelease = onkey # Functions copied from _Screen: def setup(width: float = 0.5, height: float = 0.75, startx: int | None = None, starty: int | None = None) -> None: - """ - Set the size and position of the main window. + """Set the size and position of the main window. Arguments: width: as integer a size in pixels, as float a fraction of the @@ -2815,8 +2670,7 @@ def setup(width: float = 0.5, height: float = 0.75, startx: int | None = None, s """ def title(titlestring: str) -> None: - """ - Set title of turtle-window + """Set title of turtle-window Argument: titlestring -- a string, to appear in the titlebar of the @@ -2830,16 +2684,14 @@ def title(titlestring: str) -> None: """ def bye() -> None: - """ - Shut the turtlegraphics window. + """Shut the turtlegraphics window. Example: >>> bye() """ def exitonclick() -> None: - """ - Go into mainloop until the mouse is clicked. + """Go into mainloop until the mouse is clicked. No arguments. @@ -2858,8 +2710,7 @@ def exitonclick() -> None: """ def Screen() -> _Screen: - """ - Return the singleton screen object. + """Return the singleton screen object. If none exists at the moment, create a new one and return it, else return the existing one. """ @@ -2867,8 +2718,7 @@ def Screen() -> _Screen: # Functions copied from TNavigator: def degrees(fullcircle: float = 360.0) -> None: - """ - Set angle measurement units to degrees. + """Set angle measurement units to degrees. Optional argument: fullcircle - a number @@ -2890,8 +2740,7 @@ def degrees(fullcircle: float = 360.0) -> None: """ def radians() -> None: - """ - Set the angle measurement units to radians. + """Set the angle measurement units to radians. No arguments. @@ -2904,8 +2753,7 @@ def radians() -> None: """ def forward(distance: float) -> None: - """ - Move the turtle forward by the specified distance. + """Move the turtle forward by the specified distance. Aliases: forward | fd @@ -2927,8 +2775,7 @@ def forward(distance: float) -> None: """ def back(distance: float) -> None: - """ - Move the turtle backward by distance. + """Move the turtle backward by distance. Aliases: back | backward | bk @@ -2947,8 +2794,7 @@ def back(distance: float) -> None: """ def right(angle: float) -> None: - """ - Turn turtle right by angle units. + """Turn turtle right by angle units. Aliases: right | rt @@ -2968,8 +2814,7 @@ def right(angle: float) -> None: """ def left(angle: float) -> None: - """ - Turn turtle left by angle units. + """Turn turtle left by angle units. Aliases: left | lt @@ -2989,8 +2834,7 @@ def left(angle: float) -> None: """ def pos() -> Vec2D: - """ - Return the turtle's current location (x,y), as a Vec2D-vector. + """Return the turtle's current location (x,y), as a Vec2D-vector. Aliases: pos | position @@ -3002,8 +2846,7 @@ def pos() -> Vec2D: """ def xcor() -> float: - """ - Return the turtle's x coordinate. + """Return the turtle's x coordinate. No arguments. @@ -3016,8 +2859,7 @@ def xcor() -> float: """ def ycor() -> float: - """ - Return the turtle's y coordinate + """Return the turtle's y coordinate --- No arguments. @@ -3031,8 +2873,7 @@ def ycor() -> float: @overload def goto(x: tuple[float, float], y: None = None) -> None: - """ - Move turtle to an absolute position. + """Move turtle to an absolute position. Aliases: setpos | setposition | goto: @@ -3065,8 +2906,7 @@ def goto(x: tuple[float, float], y: None = None) -> None: @overload def goto(x: float, y: float) -> None: ... def home() -> None: - """ - Move turtle to the origin - coordinates (0,0). + """Move turtle to the origin - coordinates (0,0). No arguments. @@ -3078,8 +2918,7 @@ def home() -> None: """ def setx(x: float) -> None: - """ - Set the turtle's first coordinate to x + """Set the turtle's first coordinate to x Argument: x -- a number (integer or float) @@ -3096,8 +2935,7 @@ def setx(x: float) -> None: """ def sety(y: float) -> None: - """ - Set the turtle's second coordinate to y + """Set the turtle's second coordinate to y Argument: y -- a number (integer or float) @@ -3115,8 +2953,7 @@ def sety(y: float) -> None: @overload def distance(x: TNavigator | tuple[float, float], y: None = None) -> float: - """ - Return the distance from the turtle to (x,y) in turtle step units. + """Return the distance from the turtle to (x,y) in turtle step units. Arguments: x -- a number or a pair/vector of numbers or a turtle instance @@ -3142,8 +2979,7 @@ def distance(x: TNavigator | tuple[float, float], y: None = None) -> float: def distance(x: float, y: float) -> float: ... @overload def towards(x: TNavigator | tuple[float, float], y: None = None) -> float: - """ - Return the angle of the line from the turtle's position to (x, y). + """Return the angle of the line from the turtle's position to (x, y). Arguments: x -- a number or a pair/vector of numbers or a turtle instance @@ -3168,8 +3004,7 @@ def towards(x: TNavigator | tuple[float, float], y: None = None) -> float: @overload def towards(x: float, y: float) -> float: ... def heading() -> float: - """ - Return the turtle's current heading. + """Return the turtle's current heading. No arguments. @@ -3180,8 +3015,7 @@ def heading() -> float: """ def setheading(to_angle: float) -> None: - """ - Set the orientation of the turtle to to_angle. + """Set the orientation of the turtle to to_angle. Aliases: setheading | seth @@ -3205,8 +3039,7 @@ def setheading(to_angle: float) -> None: """ def circle(radius: float, extent: float | None = None, steps: int | None = None) -> None: - """ - Draw a circle with given radius. + """Draw a circle with given radius. Arguments: radius -- a number @@ -3249,8 +3082,7 @@ seth = setheading # Functions copied from TPen: @overload def resizemode(rmode: None = None) -> str: - """ - Set resizemode to one of the values: "auto", "user", "noresize". + """Set resizemode to one of the values: "auto", "user", "noresize". (Optional) Argument: rmode -- one of the strings "auto", "user", "noresize" @@ -3276,8 +3108,7 @@ def resizemode(rmode: None = None) -> str: def resizemode(rmode: str) -> None: ... @overload def pensize(width: None = None) -> int: - """ - Set or return the line thickness. + """Set or return the line thickness. Aliases: pensize | width @@ -3298,8 +3129,7 @@ def pensize(width: None = None) -> int: @overload def pensize(width: int) -> None: ... def penup() -> None: - """ - Pull the pen up -- no drawing when moving. + """Pull the pen up -- no drawing when moving. Aliases: penup | pu | up @@ -3310,8 +3140,7 @@ def penup() -> None: """ def pendown() -> None: - """ - Pull the pen down -- drawing when moving. + """Pull the pen down -- drawing when moving. Aliases: pendown | pd | down @@ -3322,8 +3151,7 @@ def pendown() -> None: """ def isdown() -> bool: - """ - Return True if pen is down, False if it's up. + """Return True if pen is down, False if it's up. No argument. @@ -3338,8 +3166,7 @@ def isdown() -> bool: @overload def speed(speed: None = None) -> int: - """ - Return or set the turtle's speed. + """Return or set the turtle's speed. Optional argument: speed -- an integer in the range 0..10 or a speedstring (see below) @@ -3370,8 +3197,7 @@ def speed(speed: None = None) -> int: def speed(speed: _Speed) -> None: ... @overload def pencolor() -> _AnyColor: - """ - Return or set the pencolor. + """Return or set the pencolor. Arguments: Four input formats are allowed: @@ -3406,8 +3232,7 @@ def pencolor(color: _Color) -> None: ... def pencolor(r: float, g: float, b: float) -> None: ... @overload def fillcolor() -> _AnyColor: - """ - Return or set the fillcolor. + """Return or set the fillcolor. Arguments: Four input formats are allowed: @@ -3441,8 +3266,7 @@ def fillcolor(color: _Color) -> None: ... def fillcolor(r: float, g: float, b: float) -> None: ... @overload def color() -> tuple[_AnyColor, _AnyColor]: - """ - Return or set the pencolor and fillcolor. + """Return or set the pencolor and fillcolor. Arguments: Several input formats are allowed. @@ -3481,8 +3305,7 @@ def color(r: float, g: float, b: float) -> None: ... @overload def color(color1: _Color, color2: _Color) -> None: ... def showturtle() -> None: - """ - Makes the turtle visible. + """Makes the turtle visible. Aliases: showturtle | st @@ -3494,8 +3317,7 @@ def showturtle() -> None: """ def hideturtle() -> None: - """ - Makes the turtle invisible. + """Makes the turtle invisible. Aliases: hideturtle | ht @@ -3510,8 +3332,7 @@ def hideturtle() -> None: """ def isvisible() -> bool: - """ - Return True if the Turtle is shown, False if it's hidden. + """Return True if the Turtle is shown, False if it's hidden. No argument. @@ -3524,8 +3345,7 @@ def isvisible() -> bool: # Note: signatures 1 and 2 overlap unsafely when no arguments are provided @overload def pen() -> _PenState: - """ - Return or set the pen's attributes. + """Return or set the pen's attributes. Arguments: pen -- a dictionary with some or all of the below listed keys. @@ -3599,8 +3419,7 @@ ht = hideturtle # Functions copied from RawTurtle: def setundobuffer(size: int | None) -> None: - """ - Set or disable undobuffer. + """Set or disable undobuffer. Argument: size -- an integer or None @@ -3615,8 +3434,7 @@ def setundobuffer(size: int | None) -> None: """ def undobufferentries() -> int: - """ - Return count of entries in the undobuffer. + """Return count of entries in the undobuffer. No argument. @@ -3627,8 +3445,7 @@ def undobufferentries() -> int: @overload def shape(name: None = None) -> str: - """ - Set turtle shape to shape with given name / return current shapename. + """Set turtle shape to shape with given name / return current shapename. Optional argument: name -- a string, which is a valid shapename @@ -3653,8 +3470,7 @@ def shape(name: str) -> None: ... if sys.version_info >= (3, 12): def teleport(x: float | None = None, y: float | None = None, *, fill_gap: bool = False) -> None: - """ - Instantly move turtle to an absolute position. + """Instantly move turtle to an absolute position. Arguments: x -- a number or None @@ -3692,8 +3508,7 @@ if sys.version_info >= (3, 12): # Unsafely overlaps when no arguments are provided @overload def shapesize() -> tuple[float, float, float]: - """ - Set/return turtle's stretchfactors/outline. Set resizemode to "user". + """Set/return turtle's stretchfactors/outline. Set resizemode to "user". Optional arguments: stretch_wid : positive number @@ -3718,8 +3533,7 @@ def shapesize() -> tuple[float, float, float]: def shapesize(stretch_wid: float | None = None, stretch_len: float | None = None, outline: float | None = None) -> None: ... @overload def shearfactor(shear: None = None) -> float: - """ - Set or return the current shearfactor. + """Set or return the current shearfactor. Optional argument: shear -- number, tangent of the shear angle @@ -3744,8 +3558,7 @@ def shearfactor(shear: float) -> None: ... # Unsafely overlaps when no arguments are provided @overload def shapetransform() -> tuple[float, float, float, float]: - """ - Set or return the current transformation matrix of the turtle shape. + """Set or return the current transformation matrix of the turtle shape. Optional arguments: t11, t12, t21, t22 -- numbers. @@ -3770,8 +3583,7 @@ def shapetransform( t11: float | None = None, t12: float | None = None, t21: float | None = None, t22: float | None = None ) -> None: ... def get_shapepoly() -> _PolygonCoords | None: - """ - Return the current shape polygon as tuple of coordinate pairs. + """Return the current shape polygon as tuple of coordinate pairs. No argument. @@ -3784,8 +3596,7 @@ def get_shapepoly() -> _PolygonCoords | None: if sys.version_info < (3, 13): def settiltangle(angle: float) -> None: - """ - Rotate the turtleshape to point in the specified direction + """Rotate the turtleshape to point in the specified direction Argument: angle -- number @@ -3808,8 +3619,7 @@ if sys.version_info < (3, 13): @overload def tiltangle(angle: None = None) -> float: - """ - Set or return the current tilt-angle. + """Set or return the current tilt-angle. Optional argument: angle -- number @@ -3840,8 +3650,7 @@ def tiltangle(angle: None = None) -> float: @overload def tiltangle(angle: float) -> None: ... def tilt(angle: float) -> None: - """ - Rotate the turtleshape by angle. + """Rotate the turtleshape by angle. Argument: angle - a number @@ -3862,8 +3671,7 @@ def tilt(angle: float) -> None: # a compound stamp or not. So, as per the "no Union return" policy, # we return Any. def stamp() -> Any: - """ - Stamp a copy of the turtleshape onto the canvas and return its id. + """Stamp a copy of the turtleshape onto the canvas and return its id. No argument. @@ -3879,8 +3687,7 @@ def stamp() -> Any: """ def clearstamp(stampid: int | tuple[int, ...]) -> None: - """ - Delete stamp with given stampid + """Delete stamp with given stampid Argument: stampid - an integer, must be return value of previous stamp() call. @@ -3893,8 +3700,7 @@ def clearstamp(stampid: int | tuple[int, ...]) -> None: """ def clearstamps(n: int | None = None) -> None: - """ - Delete all or first/last n of turtle's stamps. + """Delete all or first/last n of turtle's stamps. Optional argument: n -- an integer @@ -3913,8 +3719,7 @@ def clearstamps(n: int | None = None) -> None: """ def filling() -> bool: - """ - Return fillstate (True if filling, False else). + """Return fillstate (True if filling, False else). No argument. @@ -3929,8 +3734,7 @@ def filling() -> bool: if sys.version_info >= (3, 14): @contextmanager def fill() -> Generator[None]: - """ - A context manager for filling a shape. + """A context manager for filling a shape. Implicitly ensures the code block is wrapped with begin_fill() and end_fill(). @@ -3942,8 +3746,7 @@ if sys.version_info >= (3, 14): """ def begin_fill() -> None: - """ - Called just before drawing a shape to be filled. + """Called just before drawing a shape to be filled. No argument. @@ -3955,8 +3758,7 @@ def begin_fill() -> None: """ def end_fill() -> None: - """ - Fill the shape drawn after the call begin_fill(). + """Fill the shape drawn after the call begin_fill(). No argument. @@ -3968,8 +3770,7 @@ def end_fill() -> None: """ def dot(size: int | None = None, *color: _Color) -> None: - """ - Draw a dot with diameter size, using color. + """Draw a dot with diameter size, using color. Optional arguments: size -- an integer >= 1 (if given) @@ -3984,8 +3785,7 @@ def dot(size: int | None = None, *color: _Color) -> None: """ def write(arg: object, move: bool = False, align: str = "left", font: tuple[str, int, str] = ("Arial", 8, "normal")) -> None: - """ - Write text at the current turtle position. + """Write text at the current turtle position. Arguments: arg -- info, which is to be written to the TurtleScreen @@ -4007,8 +3807,7 @@ def write(arg: object, move: bool = False, align: str = "left", font: tuple[str, if sys.version_info >= (3, 14): @contextmanager def poly() -> Generator[None]: - """ - A context manager for recording the vertices of a polygon. + """A context manager for recording the vertices of a polygon. Implicitly ensures that the code block is wrapped with begin_poly() and end_poly() @@ -4023,8 +3822,7 @@ if sys.version_info >= (3, 14): """ def begin_poly() -> None: - """ - Start recording the vertices of a polygon. + """Start recording the vertices of a polygon. No argument. @@ -4036,8 +3834,7 @@ def begin_poly() -> None: """ def end_poly() -> None: - """ - Stop recording the vertices of a polygon. + """Stop recording the vertices of a polygon. No argument. @@ -4049,8 +3846,7 @@ def end_poly() -> None: """ def get_poly() -> _PolygonCoords | None: - """ - Return the lastly recorded polygon. + """Return the lastly recorded polygon. No argument. @@ -4060,8 +3856,7 @@ def get_poly() -> _PolygonCoords | None: """ def getscreen() -> TurtleScreen: - """ - Return the TurtleScreen object, the turtle is drawing on. + """Return the TurtleScreen object, the turtle is drawing on. No argument. @@ -4076,8 +3871,7 @@ def getscreen() -> TurtleScreen: """ def getturtle() -> Turtle: - """ - Return the Turtleobject itself. + """Return the Turtleobject itself. No argument. @@ -4095,8 +3889,7 @@ def getturtle() -> Turtle: getpen = getturtle def onrelease(fun: Callable[[float, float], object], btn: int = 1, add: Any | None = None) -> None: - """ - Bind fun to mouse-button-release event on this turtle on canvas. + """Bind fun to mouse-button-release event on this turtle on canvas. Arguments: fun -- a function with two arguments, to which will be assigned @@ -4119,8 +3912,7 @@ def onrelease(fun: Callable[[float, float], object], btn: int = 1, add: Any | No """ def ondrag(fun: Callable[[float, float], object], btn: int = 1, add: Any | None = None) -> None: - """ - Bind fun to mouse-move event on this turtle on canvas. + """Bind fun to mouse-move event on this turtle on canvas. Arguments: fun -- a function with two arguments, to which will be assigned @@ -4139,8 +3931,7 @@ def ondrag(fun: Callable[[float, float], object], btn: int = 1, add: Any | None """ def undo() -> None: - """ - undo (repeatedly) the last turtle action. + """undo (repeatedly) the last turtle action. No argument. @@ -4162,8 +3953,7 @@ turtlesize = shapesize # Functions copied from RawTurtle with a few tweaks: def clone() -> Turtle: - """ - Create and return a clone of the + """Create and return a clone of the No argument. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/types.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/types.pyi index 04629a4a93..a4c444015c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/types.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/types.pyi @@ -1,4 +1,5 @@ """ + Define names for built-in types that aren't directly accessible as a builtin. """ @@ -75,8 +76,7 @@ _VT_co = TypeVar("_VT_co", covariant=True) # Make sure this class definition stays roughly in line with `builtins.function` @final class FunctionType: - """ - Create a function object. + """Create a function object. code a code object @@ -133,15 +133,11 @@ class FunctionType: ) -> Self: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: - """ - Call self as a function. - """ + """Call self as a function.""" @overload def __get__(self, instance: None, owner: type, /) -> FunctionType: - """ - Return an attribute of instance, which is of type owner. - """ + """Return an attribute of instance, which is of type owner.""" @overload def __get__(self, instance: object, owner: type | None = None, /) -> MethodType: ... @@ -150,9 +146,7 @@ LambdaType = FunctionType @final class CodeType: - """ - Create a code object. Not for the faint of heart. - """ + """Create a code object. Not for the faint of heart.""" def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... @@ -295,9 +289,7 @@ class CodeType: co_linetable: bytes = ..., co_exceptiontable: bytes = ..., ) -> Self: - """ - Return a copy of the code object with new values for the specified fields. - """ + """Return a copy of the code object with new values for the specified fields.""" elif sys.version_info >= (3, 10): def replace( self, @@ -319,9 +311,7 @@ class CodeType: co_name: str = ..., co_linetable: bytes = ..., ) -> Self: - """ - Return a copy of the code object with new values for the specified fields. - """ + """Return a copy of the code object with new values for the specified fields.""" else: def replace( self, @@ -343,90 +333,60 @@ class CodeType: co_name: str = ..., co_lnotab: bytes = ..., ) -> Self: - """ - Return a copy of the code object with new values for the specified fields. - """ + """Return a copy of the code object with new values for the specified fields.""" if sys.version_info >= (3, 13): __replace__ = replace @final class MappingProxyType(Mapping[_KT, _VT_co]): - """ - Read-only proxy of a mapping. - """ + """Read-only proxy of a mapping.""" __hash__: ClassVar[None] # type: ignore[assignment] def __new__(cls, mapping: SupportsKeysAndGetItem[_KT, _VT_co]) -> Self: ... def __getitem__(self, key: _KT, /) -> _VT_co: - """ - Return self[key]. - """ + """Return self[key].""" def __iter__(self) -> Iterator[_KT]: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" def __eq__(self, value: object, /) -> bool: ... def copy(self) -> dict[_KT, _VT_co]: - """ - D.copy() -> a shallow copy of D - """ + """D.copy() -> a shallow copy of D""" def keys(self) -> KeysView[_KT]: - """ - D.keys() -> a set-like object providing a view on D's keys - """ + """D.keys() -> a set-like object providing a view on D's keys""" def values(self) -> ValuesView[_VT_co]: - """ - D.values() -> an object providing a view on D's values - """ + """D.values() -> an object providing a view on D's values""" def items(self) -> ItemsView[_KT, _VT_co]: - """ - D.items() -> a set-like object providing a view on D's items - """ + """D.items() -> a set-like object providing a view on D's items""" @overload def get(self, key: _KT, /) -> _VT_co | None: - """ - Return the value for key if key is in the mapping, else default. - """ + """Return the value for key if key is in the mapping, else default.""" @overload def get(self, key: _KT, default: _VT_co, /) -> _VT_co: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter @overload def get(self, key: _KT, default: _T2, /) -> _VT_co | _T2: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" def __reversed__(self) -> Iterator[_KT]: - """ - D.__reversed__() -> reverse iterator - """ + """D.__reversed__() -> reverse iterator""" def __or__(self, value: Mapping[_T1, _T2], /) -> dict[_KT | _T1, _VT_co | _T2]: - """ - Return self|value. - """ + """Return self|value.""" def __ror__(self, value: Mapping[_T1, _T2], /) -> dict[_KT | _T1, _VT_co | _T2]: - """ - Return value|self. - """ + """Return value|self.""" class SimpleNamespace: - """ - A simple attribute-based namespace. - """ + """A simple attribute-based namespace.""" __hash__: ClassVar[None] # type: ignore[assignment] if sys.version_info >= (3, 13): @@ -440,13 +400,10 @@ class SimpleNamespace: def __delattr__(self, name: str, /) -> None: ... if sys.version_info >= (3, 13): def __replace__(self, **kwargs: Any) -> Self: - """ - Return a copy of the namespace object with new values for the specified attributes. - """ + """Return a copy of the namespace object with new values for the specified attributes.""" class ModuleType: - """ - Create a module object. + """Create a module object. The name must be a string; the optional doc argument can have any type. """ @@ -478,8 +435,7 @@ class ModuleType: @final class CellType: - """ - Create a new cell object. + """Create a new cell object. contents the contents of the cell. If not specified, the cell will be empty, @@ -506,34 +462,26 @@ class GeneratorType(Generator[_YieldT_co, _SendT_contra, _ReturnT_co]): def gi_running(self) -> bool: ... @property def gi_yieldfrom(self) -> Iterator[_YieldT_co] | None: - """ - object being iterated by yield from, or None - """ + """object being iterated by yield from, or None""" if sys.version_info >= (3, 11): @property def gi_suspended(self) -> bool: ... __name__: str __qualname__: str def __iter__(self) -> Self: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __next__(self) -> _YieldT_co: - """ - Implement next(self). - """ + """Implement next(self).""" def send(self, arg: _SendT_contra, /) -> _YieldT_co: - """ - send(arg) -> send 'arg' into generator, + """send(arg) -> send 'arg' into generator, return next yielded value or raise StopIteration. """ @overload def throw(self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ..., /) -> _YieldT_co: - """ - throw(value) + """throw(value) throw(type[,value[,tb]]) Raise exception in generator, return next yielded value or raise @@ -546,17 +494,13 @@ class GeneratorType(Generator[_YieldT_co, _SendT_contra, _ReturnT_co]): def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ... if sys.version_info >= (3, 13): def __class_getitem__(cls, item: Any, /) -> Any: - """ - See PEP 585 - """ + """See PEP 585""" @final class AsyncGeneratorType(AsyncGenerator[_YieldT_co, _SendT_contra]): @property def ag_await(self) -> Awaitable[Any] | None: - """ - object being awaited on, or None - """ + """object being awaited on, or None""" @property def ag_code(self) -> CodeType: ... @@ -571,26 +515,19 @@ class AsyncGeneratorType(AsyncGenerator[_YieldT_co, _SendT_contra]): def ag_suspended(self) -> bool: ... def __aiter__(self) -> Self: - """ - Return an awaitable, that resolves in asynchronous iterator. - """ + """Return an awaitable, that resolves in asynchronous iterator.""" def __anext__(self) -> Coroutine[Any, Any, _YieldT_co]: - """ - Return a value or raise StopAsyncIteration. - """ + """Return a value or raise StopAsyncIteration.""" def asend(self, val: _SendT_contra, /) -> Coroutine[Any, Any, _YieldT_co]: - """ - asend(v) -> send 'v' in generator. - """ + """asend(v) -> send 'v' in generator.""" @overload async def athrow( self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ..., / ) -> _YieldT_co: - """ - athrow(value) + """athrow(value) athrow(type[,value[,tb]]) raise exception in generator. @@ -601,14 +538,10 @@ class AsyncGeneratorType(AsyncGenerator[_YieldT_co, _SendT_contra]): @overload async def athrow(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ... def aclose(self) -> Coroutine[Any, Any, None]: - """ - aclose() -> raise GeneratorExit inside generator. - """ + """aclose() -> raise GeneratorExit inside generator.""" def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" @final class CoroutineType(Coroutine[_YieldT_co, _SendT_contra, _ReturnT_co]): @@ -616,9 +549,7 @@ class CoroutineType(Coroutine[_YieldT_co, _SendT_contra, _ReturnT_co]): __qualname__: str @property def cr_await(self) -> Any | None: - """ - object being awaited on, or None - """ + """object being awaited on, or None""" @property def cr_code(self) -> CodeType: ... @@ -633,25 +564,19 @@ class CoroutineType(Coroutine[_YieldT_co, _SendT_contra, _ReturnT_co]): def cr_suspended(self) -> bool: ... def close(self) -> None: - """ - close() -> raise GeneratorExit inside coroutine. - """ + """close() -> raise GeneratorExit inside coroutine.""" def __await__(self) -> Generator[Any, None, _ReturnT_co]: - """ - Return an iterator to be used in await expression. - """ + """Return an iterator to be used in await expression.""" def send(self, arg: _SendT_contra, /) -> _YieldT_co: - """ - send(arg) -> send 'arg' into coroutine, + """send(arg) -> send 'arg' into coroutine, return next iterated value or raise StopIteration. """ @overload def throw(self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ..., /) -> _YieldT_co: - """ - throw(value) + """throw(value) throw(type[,value[,traceback]]) Raise exception in coroutine, return next iterated value or raise @@ -664,15 +589,11 @@ class CoroutineType(Coroutine[_YieldT_co, _SendT_contra, _ReturnT_co]): def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ... if sys.version_info >= (3, 13): def __class_getitem__(cls, item: Any, /) -> Any: - """ - See PEP 585 - """ + """See PEP 585""" @final class MethodType: - """ - Create a bound instance method object. - """ + """Create a bound instance method object.""" @property def __closure__(self) -> tuple[CellType, ...] | None: ... # inherited from the added function @@ -682,15 +603,11 @@ class MethodType: def __defaults__(self) -> tuple[Any, ...] | None: ... # inherited from the added function @property def __func__(self) -> Callable[..., Any]: - """ - the function (or other callable) implementing a method - """ + """the function (or other callable) implementing a method""" @property def __self__(self) -> object: - """ - the instance to which a method is bound - """ + """the instance to which a method is bound""" @property def __name__(self) -> str: ... # inherited from the added function @@ -698,14 +615,10 @@ class MethodType: def __qualname__(self) -> str: ... # inherited from the added function def __new__(cls, func: Callable[..., Any], instance: object, /) -> Self: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: - """ - Call self as a function. - """ + """Call self as a function.""" if sys.version_info >= (3, 13): def __get__(self, instance: object, owner: type | None = None, /) -> Self: - """ - Return an attribute of instance, which is of type owner. - """ + """Return an attribute of instance, which is of type owner.""" def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... @@ -719,9 +632,7 @@ class BuiltinFunctionType: @property def __qualname__(self) -> str: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: - """ - Call self as a function. - """ + """Call self as a function.""" def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... @@ -737,14 +648,10 @@ class WrapperDescriptorType: @property def __objclass__(self) -> type: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: - """ - Call self as a function. - """ + """Call self as a function.""" def __get__(self, instance: Any, owner: type | None = None, /) -> Any: - """ - Return an attribute of instance, which is of type owner. - """ + """Return an attribute of instance, which is of type owner.""" @final class MethodWrapperType: @@ -757,9 +664,7 @@ class MethodWrapperType: @property def __objclass__(self) -> type: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: - """ - Call self as a function. - """ + """Call self as a function.""" def __eq__(self, value: object, /) -> bool: ... def __ne__(self, value: object, /) -> bool: ... @@ -774,14 +679,10 @@ class MethodDescriptorType: @property def __objclass__(self) -> type: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: - """ - Call self as a function. - """ + """Call self as a function.""" def __get__(self, instance: Any, owner: type | None = None, /) -> Any: - """ - Return an attribute of instance, which is of type owner. - """ + """Return an attribute of instance, which is of type owner.""" @final class ClassMethodDescriptorType: @@ -792,20 +693,14 @@ class ClassMethodDescriptorType: @property def __objclass__(self) -> type: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: - """ - Call self as a function. - """ + """Call self as a function.""" def __get__(self, instance: Any, owner: type | None = None, /) -> Any: - """ - Return an attribute of instance, which is of type owner. - """ + """Return an attribute of instance, which is of type owner.""" @final class TracebackType: - """ - Create a new traceback object. - """ + """Create a new traceback object.""" def __new__(cls, tb_next: TracebackType | None, tb_frame: FrameType, tb_lasti: int, tb_lineno: int) -> Self: ... tb_next: TracebackType | None @@ -823,54 +718,38 @@ class FrameType: def f_back(self) -> FrameType | None: ... @property def f_builtins(self) -> dict[str, Any]: - """ - Return the built-in variables in the frame. - """ + """Return the built-in variables in the frame.""" @property def f_code(self) -> CodeType: - """ - Return the code object being executed in this frame. - """ + """Return the code object being executed in this frame.""" @property def f_globals(self) -> dict[str, Any]: - """ - Return the global variables in the frame. - """ + """Return the global variables in the frame.""" @property def f_lasti(self) -> int: - """ - Return the index of the last attempted instruction in the frame. - """ + """Return the index of the last attempted instruction in the frame.""" # see discussion in #6769: f_lineno *can* sometimes be None, # but you should probably file a bug report with CPython if you encounter it being None in the wild. # An `int | None` annotation here causes too many false-positive errors, so applying `int | Any`. @property def f_lineno(self) -> int | MaybeNone: - """ - Return the current line number in the frame. - """ + """Return the current line number in the frame.""" @property def f_locals(self) -> dict[str, Any]: - """ - Return the mapping used by the frame to look up local variables. - """ + """Return the mapping used by the frame to look up local variables.""" f_trace: Callable[[FrameType, str, Any], Any] | None f_trace_lines: bool f_trace_opcodes: bool def clear(self) -> None: - """ - Clear all references held by the frame. - """ + """Clear all references held by the frame.""" if sys.version_info >= (3, 14): @property def f_generator(self) -> GeneratorType[Any, Any, Any] | CoroutineType[Any, Any, Any] | None: - """ - Return the generator or coroutine associated with this frame, or None. - """ + """Return the generator or coroutine associated with this frame, or None.""" @final class GetSetDescriptorType: @@ -881,19 +760,13 @@ class GetSetDescriptorType: @property def __objclass__(self) -> type: ... def __get__(self, instance: Any, owner: type | None = None, /) -> Any: - """ - Return an attribute of instance, which is of type owner. - """ + """Return an attribute of instance, which is of type owner.""" def __set__(self, instance: Any, value: Any, /) -> None: - """ - Set an attribute of instance to value. - """ + """Set an attribute of instance to value.""" def __delete__(self, instance: Any, /) -> None: - """ - Delete an attribute of instance. - """ + """Delete an attribute of instance.""" @final class MemberDescriptorType: @@ -904,19 +777,13 @@ class MemberDescriptorType: @property def __objclass__(self) -> type: ... def __get__(self, instance: Any, owner: type | None = None, /) -> Any: - """ - Return an attribute of instance, which is of type owner. - """ + """Return an attribute of instance, which is of type owner.""" def __set__(self, instance: Any, value: Any, /) -> None: - """ - Set an attribute of instance to value. - """ + """Set an attribute of instance to value.""" def __delete__(self, instance: Any, /) -> None: - """ - Delete an attribute of instance. - """ + """Delete an attribute of instance.""" def new_class( name: str, @@ -924,20 +791,15 @@ def new_class( kwds: dict[str, Any] | None = None, exec_body: Callable[[dict[str, Any]], object] | None = None, ) -> type: - """ - Create a class object dynamically using the appropriate metaclass. - """ + """Create a class object dynamically using the appropriate metaclass.""" def resolve_bases(bases: Iterable[object]) -> tuple[Any, ...]: - """ - Resolve MRO entries dynamically as specified by PEP 560. - """ + """Resolve MRO entries dynamically as specified by PEP 560.""" def prepare_class( name: str, bases: tuple[type, ...] = (), kwds: dict[str, Any] | None = None ) -> tuple[type, dict[str, Any], dict[str, Any]]: - """ - Call the __prepare__ method of the appropriate metaclass. + """Call the __prepare__ method of the appropriate metaclass. Returns (metaclass, namespace, kwds) as a 3-tuple @@ -950,8 +812,7 @@ def prepare_class( if sys.version_info >= (3, 12): def get_original_bases(cls: type, /) -> tuple[Any, ...]: - """ - Return the class's "original" bases prior to modification by `__mro_entries__`. + """Return the class's "original" bases prior to modification by `__mro_entries__`. Examples:: @@ -974,8 +835,7 @@ if sys.version_info >= (3, 12): # Does not actually inherit from property, but saying it does makes sure that # pyright handles this class correctly. class DynamicClassAttribute(property): - """ - Route attribute access on a class to __getattr__. + """Route attribute access on a class to __getattr__. This is a descriptor, used to define attributes that act differently when accessed through an instance and through a class. Instance access remains @@ -1017,16 +877,13 @@ _P = ParamSpec("_P") # it's not really an Awaitable, but can be used in an await expression. Real type: Generator & Awaitable @overload def coroutine(func: Callable[_P, Generator[Any, Any, _R]]) -> Callable[_P, Awaitable[_R]]: - """ - Convert regular generator function to a coroutine. - """ + """Convert regular generator function to a coroutine.""" @overload def coroutine(func: _Fn) -> _Fn: ... class GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ @@ -1037,15 +894,11 @@ class GenericAlias: def __args__(self) -> tuple[Any, ...]: ... @property def __parameters__(self) -> tuple[Any, ...]: - """ - Type variables in the GenericAlias. - """ + """Type variables in the GenericAlias.""" def __new__(cls, origin: type, args: Any, /) -> Self: ... def __getitem__(self, typeargs: Any, /) -> GenericAlias: - """ - Return self[key]. - """ + """Return self[key].""" def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... @@ -1057,42 +910,31 @@ class GenericAlias: def __typing_unpacked_tuple_args__(self) -> tuple[Any, ...] | None: ... if sys.version_info >= (3, 10): def __or__(self, value: Any, /) -> UnionType: - """ - Return self|value. - """ + """Return self|value.""" def __ror__(self, value: Any, /) -> UnionType: - """ - Return value|self. - """ + """Return value|self.""" # GenericAlias delegates attr access to `__origin__` def __getattr__(self, name: str) -> Any: ... if sys.version_info >= (3, 10): @final class NoneType: - """ - The type of the None singleton. - """ + """The type of the None singleton.""" def __bool__(self) -> Literal[False]: - """ - True if self else False - """ + """True if self else False""" @final class EllipsisType: - """ - The type of the Ellipsis singleton. - """ + """The type of the Ellipsis singleton.""" from builtins import _NotImplementedType NotImplementedType = _NotImplementedType @final class UnionType: - """ - Represent a union type + """Represent a union type E.g. for int | str """ @@ -1101,19 +943,13 @@ if sys.version_info >= (3, 10): def __args__(self) -> tuple[Any, ...]: ... @property def __parameters__(self) -> tuple[Any, ...]: - """ - Type variables in the types.UnionType. - """ + """Type variables in the types.UnionType.""" def __or__(self, value: Any, /) -> UnionType: - """ - Return self|value. - """ + """Return self|value.""" def __ror__(self, value: Any, /) -> UnionType: - """ - Return value|self. - """ + """Return value|self.""" def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... @@ -1121,8 +957,7 @@ if sys.version_info >= (3, 10): if sys.version_info >= (3, 13): @final class CapsuleType: - """ - Capsule objects let you wrap a C "void *" pointer in a Python + """Capsule objects let you wrap a C "void *" pointer in a Python object. They're a way of passing data through the Python interpreter without creating your own custom type. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/typing.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/typing.pyi index 7a15da8e17..5e5d7c9cee 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/typing.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/typing.pyi @@ -1,4 +1,5 @@ """ + The typing module: Support for gradual typing as defined by PEP 484 and subsequent PEPs. Among other things, the module includes the following: @@ -166,8 +167,7 @@ if sys.version_info >= (3, 13): # from _typeshed import AnnotationForm class Any: - """ - Special type indicating an unconstrained type. + """Special type indicating an unconstrained type. - Any is compatible with every type. - Any assumed to have all methods. @@ -179,13 +179,10 @@ class Any: """ class _Final: - """ - Mixin to prohibit subclassing. - """ + """Mixin to prohibit subclassing.""" def final(f: _T) -> _T: - """ - Decorator to indicate final methods and final classes. + """Decorator to indicate final methods and final classes. Use this decorator to indicate to type checkers that the decorated method cannot be overridden, and decorated class cannot be subclassed. @@ -213,8 +210,7 @@ def final(f: _T) -> _T: @final class TypeVar: - """ - Type variable. + """Type variable. The preferred way to construct a type variable is via the dedicated syntax for generic functions, classes, and type aliases:: @@ -316,14 +312,10 @@ class TypeVar: ) -> None: ... if sys.version_info >= (3, 10): def __or__(self, right: Any) -> _SpecialForm: # AnnotationForm - """ - Return self|value. - """ + """Return self|value.""" def __ror__(self, left: Any) -> _SpecialForm: # AnnotationForm - """ - Return value|self. - """ + """Return value|self.""" if sys.version_info >= (3, 11): def __typing_subst__(self, arg: Any) -> Any: ... if sys.version_info >= (3, 13): @@ -374,8 +366,7 @@ if sys.version_info >= (3, 11): @final class TypeVarTuple: - """ - Type variable tuple. A specialized form of type variable that enables + """Type variable tuple. A specialized form of type variable that enables variadic generics. The preferred way to construct a type variable tuple is via the @@ -419,9 +410,7 @@ if sys.version_info >= (3, 11): if sys.version_info >= (3, 13): @property def __default__(self) -> Any: # AnnotationForm - """ - The default value for this TypeVarTuple. - """ + """The default value for this TypeVarTuple.""" def has_default(self) -> bool: ... if sys.version_info >= (3, 13): @@ -432,9 +421,7 @@ if sys.version_info >= (3, 11): def __init__(self, name: str) -> None: ... def __iter__(self) -> Any: - """ - Implement iter(self). - """ + """Implement iter(self).""" def __typing_subst__(self, arg: Never) -> Never: ... def __typing_prepare_subst__(self, alias: Any, args: Any) -> tuple[Any, ...]: ... @@ -445,8 +432,7 @@ if sys.version_info >= (3, 11): if sys.version_info >= (3, 10): @final class ParamSpecArgs: - """ - The args for a ParamSpec object. + """The args for a ParamSpec object. Given a ParamSpec object P, P.args is an instance of ParamSpecArgs. @@ -472,8 +458,7 @@ if sys.version_info >= (3, 10): @final class ParamSpecKwargs: - """ - The kwargs for a ParamSpec object. + """The kwargs for a ParamSpec object. Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs. @@ -499,8 +484,7 @@ if sys.version_info >= (3, 10): @final class ParamSpec: - """ - Parameter specification variable. + """Parameter specification variable. The preferred way to construct a parameter specification is via the dedicated syntax for generic functions, classes, and type aliases, @@ -566,9 +550,7 @@ if sys.version_info >= (3, 10): if sys.version_info >= (3, 13): @property def __default__(self) -> Any: # AnnotationForm - """ - The default value for this ParamSpec. - """ + """The default value for this ParamSpec.""" if sys.version_info >= (3, 13): def __new__( cls, @@ -611,28 +593,20 @@ if sys.version_info >= (3, 10): @property def args(self) -> ParamSpecArgs: - """ - Represents positional arguments. - """ + """Represents positional arguments.""" @property def kwargs(self) -> ParamSpecKwargs: - """ - Represents keyword arguments. - """ + """Represents keyword arguments.""" if sys.version_info >= (3, 11): def __typing_subst__(self, arg: Any) -> Any: ... def __typing_prepare_subst__(self, alias: Any, args: Any) -> tuple[Any, ...]: ... def __or__(self, right: Any) -> _SpecialForm: - """ - Return self|value. - """ + """Return self|value.""" def __ror__(self, left: Any) -> _SpecialForm: - """ - Return value|self. - """ + """Return value|self.""" if sys.version_info >= (3, 13): def has_default(self) -> bool: ... if sys.version_info >= (3, 14): @@ -644,8 +618,7 @@ if sys.version_info >= (3, 10): TypeGuard: _SpecialForm class NewType: - """ - NewType creates simple unique types with almost zero runtime overhead. + """NewType creates simple unique types with almost zero runtime overhead. NewType(name, tp) is considered a subtype of tp by static type checkers. At runtime, NewType(name, tp) returns @@ -679,8 +652,7 @@ if sys.version_info >= (3, 10): else: def NewType(name: str, tp: Any) -> Any: - """ - NewType creates simple unique types with almost zero + """NewType creates simple unique types with almost zero runtime overhead. NewType(name, tp) is considered a subtype of tp by static type checkers. At runtime, NewType(name, tp) returns a dummy function that simply returns its argument. Usage:: @@ -714,8 +686,7 @@ _VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers. _TC = TypeVar("_TC", bound=type[object]) def overload(func: _F) -> _F: - """ - Decorator for overloaded functions/methods. + """Decorator for overloaded functions/methods. In a stub file, place two or more stub definitions for the same function in a row, each decorated with @overload. @@ -747,8 +718,7 @@ def overload(func: _F) -> _F: """ def no_type_check(arg: _F) -> _F: - """ - Decorator to indicate that annotations are not type hints. + """Decorator to indicate that annotations are not type hints. The argument must be a class or function; if it is a class, it applies recursively to all methods and classes defined in that class @@ -758,8 +728,7 @@ def no_type_check(arg: _F) -> _F: """ def no_type_check_decorator(decorator: Callable[_P, _T]) -> Callable[_P, _T]: - """ - Decorator to give another decorator the @no_type_check effect. + """Decorator to give another decorator the @no_type_check effect. This wraps the decorator with something that wraps the decorated function in @no_type_check. @@ -797,8 +766,7 @@ class _ProtocolMeta(ABCMeta): # Abstract base classes. def runtime_checkable(cls: _TC) -> _TC: - """ - Mark a protocol class as a runtime protocol. + """Mark a protocol class as a runtime protocol. Such protocol can be used with isinstance() and issubclass(). Raise TypeError if applied to a non-protocol class. @@ -819,63 +787,49 @@ def runtime_checkable(cls: _TC) -> _TC: @runtime_checkable class SupportsInt(Protocol, metaclass=ABCMeta): - """ - An ABC with one abstract method __int__. - """ + """An ABC with one abstract method __int__.""" @abstractmethod def __int__(self) -> int: ... @runtime_checkable class SupportsFloat(Protocol, metaclass=ABCMeta): - """ - An ABC with one abstract method __float__. - """ + """An ABC with one abstract method __float__.""" @abstractmethod def __float__(self) -> float: ... @runtime_checkable class SupportsComplex(Protocol, metaclass=ABCMeta): - """ - An ABC with one abstract method __complex__. - """ + """An ABC with one abstract method __complex__.""" @abstractmethod def __complex__(self) -> complex: ... @runtime_checkable class SupportsBytes(Protocol, metaclass=ABCMeta): - """ - An ABC with one abstract method __bytes__. - """ + """An ABC with one abstract method __bytes__.""" @abstractmethod def __bytes__(self) -> bytes: ... @runtime_checkable class SupportsIndex(Protocol, metaclass=ABCMeta): - """ - An ABC with one abstract method __index__. - """ + """An ABC with one abstract method __index__.""" @abstractmethod def __index__(self) -> int: ... @runtime_checkable class SupportsAbs(Protocol[_T_co]): - """ - An ABC with one abstract method __abs__ that is covariant in its return type. - """ + """An ABC with one abstract method __abs__ that is covariant in its return type.""" @abstractmethod def __abs__(self) -> _T_co: ... @runtime_checkable class SupportsRound(Protocol[_T_co]): - """ - An ABC with one abstract method __round__ that is covariant in its return type. - """ + """An ABC with one abstract method __round__ that is covariant in its return type.""" @overload @abstractmethod @@ -906,9 +860,7 @@ class Iterable(Protocol[_T_co]): class Iterator(Iterable[_T_co], Protocol[_T_co]): @abstractmethod def __next__(self) -> _T_co: - """ - Return the next item from the iterator. When exhausted, raise StopIteration - """ + """Return the next item from the iterator. When exhausted, raise StopIteration""" def __iter__(self) -> Iterator[_T_co]: ... @@ -924,15 +876,13 @@ _ReturnT_co = TypeVar("_ReturnT_co", covariant=True, default=None) @runtime_checkable class Generator(Iterator[_YieldT_co], Protocol[_YieldT_co, _SendT_contra, _ReturnT_co]): def __next__(self) -> _YieldT_co: - """ - Return the next item from the generator. + """Return the next item from the generator. When exhausted, raise StopIteration. """ @abstractmethod def send(self, value: _SendT_contra, /) -> _YieldT_co: - """ - Send a value into the generator. + """Send a value into the generator. Return next yielded value or raise StopIteration. """ @@ -941,8 +891,7 @@ class Generator(Iterator[_YieldT_co], Protocol[_YieldT_co, _SendT_contra, _Retur def throw( self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, / ) -> _YieldT_co: - """ - Raise an exception in the generator. + """Raise an exception in the generator. Return next yielded value or raise StopIteration. """ @@ -951,14 +900,10 @@ class Generator(Iterator[_YieldT_co], Protocol[_YieldT_co, _SendT_contra, _Retur def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = None, /) -> _YieldT_co: ... if sys.version_info >= (3, 13): def close(self) -> _ReturnT_co | None: - """ - Raise GeneratorExit inside generator. - """ + """Raise GeneratorExit inside generator.""" else: def close(self) -> None: - """ - Raise GeneratorExit inside generator. - """ + """Raise GeneratorExit inside generator.""" def __iter__(self) -> Generator[_YieldT_co, _SendT_contra, _ReturnT_co]: ... @@ -970,15 +915,11 @@ else: @runtime_checkable class ContextManager(AbstractContextManager[_T_co, bool | None], Protocol[_T_co]): - """ - An abstract base class for context managers. - """ + """An abstract base class for context managers.""" @runtime_checkable class AsyncContextManager(AbstractAsyncContextManager[_T_co, bool | None], Protocol[_T_co]): - """ - An abstract base class for asynchronous context managers. - """ + """An abstract base class for asynchronous context managers.""" @runtime_checkable class Awaitable(Protocol[_T_co]): @@ -995,8 +936,7 @@ class Coroutine(Awaitable[_ReturnT_nd_co], Generic[_YieldT_co, _SendT_nd_contra, @abstractmethod def send(self, value: _SendT_nd_contra, /) -> _YieldT_co: - """ - Send a value into the coroutine. + """Send a value into the coroutine. Return next yielded value or raise StopIteration. """ @@ -1005,8 +945,7 @@ class Coroutine(Awaitable[_ReturnT_nd_co], Generic[_YieldT_co, _SendT_nd_contra, def throw( self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, / ) -> _YieldT_co: - """ - Raise an exception in the coroutine. + """Raise an exception in the coroutine. Return next yielded value or raise StopIteration. """ @@ -1015,9 +954,7 @@ class Coroutine(Awaitable[_ReturnT_nd_co], Generic[_YieldT_co, _SendT_nd_contra, def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = None, /) -> _YieldT_co: ... @abstractmethod def close(self) -> None: - """ - Raise GeneratorExit inside coroutine. - """ + """Raise GeneratorExit inside coroutine.""" # NOTE: This type does not exist in typing.py or PEP 484 but mypy needs it to exist. # The parameters correspond to Generator, but the 4th is the original type. @@ -1039,24 +976,20 @@ class AsyncIterable(Protocol[_T_co]): class AsyncIterator(AsyncIterable[_T_co], Protocol[_T_co]): @abstractmethod def __anext__(self) -> Awaitable[_T_co]: - """ - Return the next item or raise StopAsyncIteration when exhausted. - """ + """Return the next item or raise StopAsyncIteration when exhausted.""" def __aiter__(self) -> AsyncIterator[_T_co]: ... @runtime_checkable class AsyncGenerator(AsyncIterator[_YieldT_co], Protocol[_YieldT_co, _SendT_contra]): def __anext__(self) -> Coroutine[Any, Any, _YieldT_co]: - """ - Return the next item from the asynchronous generator. + """Return the next item from the asynchronous generator. When exhausted, raise StopAsyncIteration. """ @abstractmethod def asend(self, value: _SendT_contra, /) -> Coroutine[Any, Any, _YieldT_co]: - """ - Send a value into the asynchronous generator. + """Send a value into the asynchronous generator. Return next yielded value or raise StopAsyncIteration. """ @@ -1065,8 +998,7 @@ class AsyncGenerator(AsyncIterator[_YieldT_co], Protocol[_YieldT_co, _SendT_cont def athrow( self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, / ) -> Coroutine[Any, Any, _YieldT_co]: - """ - Raise an exception in the asynchronous generator. + """Raise an exception in the asynchronous generator. Return next yielded value or raise StopAsyncIteration. """ @@ -1076,9 +1008,7 @@ class AsyncGenerator(AsyncIterator[_YieldT_co], Protocol[_YieldT_co, _SendT_cont self, typ: BaseException, val: None = None, tb: TracebackType | None = None, / ) -> Coroutine[Any, Any, _YieldT_co]: ... def aclose(self) -> Coroutine[Any, Any, None]: - """ - Raise GeneratorExit inside coroutine. - """ + """Raise GeneratorExit inside coroutine.""" @runtime_checkable class Container(Protocol[_T_co]): @@ -1093,8 +1023,7 @@ class Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]): def __len__(self) -> int: ... class Sequence(Reversible[_T_co], Collection[_T_co]): - """ - All the operations on a read-only sequence. + """All the operations on a read-only sequence. Concrete subclasses must override __new__ or __init__, __getitem__, and __len__. @@ -1108,8 +1037,7 @@ class Sequence(Reversible[_T_co], Collection[_T_co]): def __getitem__(self, index: slice) -> Sequence[_T_co]: ... # Mixin methods def index(self, value: Any, start: int = 0, stop: int = ...) -> int: - """ - S.index(value, [start, [stop]]) -> integer -- return first index of value. + """S.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present. Supporting start and stop arguments is optional, but @@ -1117,17 +1045,14 @@ class Sequence(Reversible[_T_co], Collection[_T_co]): """ def count(self, value: Any) -> int: - """ - S.count(value) -> integer -- return number of occurrences of value - """ + """S.count(value) -> integer -- return number of occurrences of value""" def __contains__(self, value: object) -> bool: ... def __iter__(self) -> Iterator[_T_co]: ... def __reversed__(self) -> Iterator[_T_co]: ... class MutableSequence(Sequence[_T]): - """ - All the operations on a read-write sequence. + """All the operations on a read-write sequence. Concrete subclasses must provide __new__ or __init__, __getitem__, __setitem__, __delitem__, __len__, and insert(). @@ -1135,9 +1060,7 @@ class MutableSequence(Sequence[_T]): @abstractmethod def insert(self, index: int, value: _T) -> None: - """ - S.insert(index, value) -- insert value before index - """ + """S.insert(index, value) -- insert value before index""" @overload @abstractmethod @@ -1159,42 +1082,31 @@ class MutableSequence(Sequence[_T]): def __delitem__(self, index: slice) -> None: ... # Mixin methods def append(self, value: _T) -> None: - """ - S.append(value) -- append value to the end of the sequence - """ + """S.append(value) -- append value to the end of the sequence""" def clear(self) -> None: - """ - S.clear() -> None -- remove all items from S - """ + """S.clear() -> None -- remove all items from S""" def extend(self, values: Iterable[_T]) -> None: - """ - S.extend(iterable) -- extend sequence by appending elements from the iterable - """ + """S.extend(iterable) -- extend sequence by appending elements from the iterable""" def reverse(self) -> None: - """ - S.reverse() -- reverse *IN PLACE* - """ + """S.reverse() -- reverse *IN PLACE*""" def pop(self, index: int = -1) -> _T: - """ - S.pop([index]) -> item -- remove and return item at index (default last). + """S.pop([index]) -> item -- remove and return item at index (default last). Raise IndexError if list is empty or index is out of range. """ def remove(self, value: _T) -> None: - """ - S.remove(value) -- remove first occurrence of value. + """S.remove(value) -- remove first occurrence of value. Raise ValueError if the value is not present. """ def __iadd__(self, values: Iterable[_T]) -> typing_extensions.Self: ... class AbstractSet(Collection[_T_co]): - """ - A set is a finite, iterable container. + """A set is a finite, iterable container. This class provides concrete generic implementations of all methods except for __contains__, __iter__ and __len__. @@ -1207,8 +1119,7 @@ class AbstractSet(Collection[_T_co]): @abstractmethod def __contains__(self, x: object) -> bool: ... def _hash(self) -> int: - """ - Compute the hash value of a set. + """Compute the hash value of a set. Note that we don't define __hash__: not all sets are hashable. But if you define a hashable set type, its __hash__ should @@ -1233,13 +1144,10 @@ class AbstractSet(Collection[_T_co]): def __xor__(self, other: AbstractSet[_T]) -> AbstractSet[_T_co | _T]: ... def __eq__(self, other: object) -> bool: ... def isdisjoint(self, other: Iterable[Any]) -> bool: - """ - Return True if two sets have a null intersection. - """ + """Return True if two sets have a null intersection.""" class MutableSet(AbstractSet[_T]): - """ - A mutable set is a finite, iterable container. + """A mutable set is a finite, iterable container. This class provides concrete generic implementations of all methods except for __contains__, __iter__, __len__, @@ -1252,30 +1160,20 @@ class MutableSet(AbstractSet[_T]): @abstractmethod def add(self, value: _T) -> None: - """ - Add an element. - """ + """Add an element.""" @abstractmethod def discard(self, value: _T) -> None: - """ - Remove an element. Do not raise an exception if absent. - """ + """Remove an element. Do not raise an exception if absent.""" # Mixin methods def clear(self) -> None: - """ - This is slow (creates N new iterators!) but effective. - """ + """This is slow (creates N new iterators!) but effective.""" def pop(self) -> _T: - """ - Return the popped value. Raise KeyError if empty. - """ + """Return the popped value. Raise KeyError if empty.""" def remove(self, value: _T) -> None: - """ - Remove an element. If not a member, raise a KeyError. - """ + """Remove an element. If not a member, raise a KeyError.""" def __ior__(self, it: AbstractSet[_T]) -> typing_extensions.Self: ... # type: ignore[override,misc] def __iand__(self, it: AbstractSet[Any]) -> typing_extensions.Self: ... @@ -1318,8 +1216,7 @@ class ValuesView(MappingView, Collection[_VT_co]): def __iter__(self) -> Iterator[_VT_co]: ... class Mapping(Collection[_KT], Generic[_KT, _VT_co]): - """ - A Mapping is a generic container for associating key/value + """A Mapping is a generic container for associating key/value pairs. This class provides concrete generic implementations of all @@ -1333,35 +1230,26 @@ class Mapping(Collection[_KT], Generic[_KT, _VT_co]): # Mixin methods @overload def get(self, key: _KT, /) -> _VT_co | None: - """ - D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. - """ + """D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.""" @overload def get(self, key: _KT, /, default: _VT_co) -> _VT_co: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter @overload def get(self, key: _KT, /, default: _T) -> _VT_co | _T: ... def items(self) -> ItemsView[_KT, _VT_co]: - """ - D.items() -> a set-like object providing a view on D's items - """ + """D.items() -> a set-like object providing a view on D's items""" def keys(self) -> KeysView[_KT]: - """ - D.keys() -> a set-like object providing a view on D's keys - """ + """D.keys() -> a set-like object providing a view on D's keys""" def values(self) -> ValuesView[_VT_co]: - """ - D.values() -> an object providing a view on D's values - """ + """D.values() -> an object providing a view on D's values""" def __contains__(self, key: object, /) -> bool: ... def __eq__(self, other: object, /) -> bool: ... class MutableMapping(Mapping[_KT, _VT]): - """ - A MutableMapping is a generic container for associating + """A MutableMapping is a generic container for associating key/value pairs. This class provides concrete generic implementations of all @@ -1374,14 +1262,11 @@ class MutableMapping(Mapping[_KT, _VT]): @abstractmethod def __delitem__(self, key: _KT, /) -> None: ... def clear(self) -> None: - """ - D.clear() -> None. Remove all items from D. - """ + """D.clear() -> None. Remove all items from D.""" @overload def pop(self, key: _KT, /) -> _VT: - """ - D.pop(k[,d]) -> v, remove specified key and return the corresponding value. + """D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. """ @@ -1390,8 +1275,7 @@ class MutableMapping(Mapping[_KT, _VT]): @overload def pop(self, key: _KT, /, default: _T) -> _VT | _T: ... def popitem(self) -> tuple[_KT, _VT]: - """ - D.popitem() -> (k, v), remove and return some (key, value) pair + """D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. """ # This overload should be allowed only if the value type is compatible with None. @@ -1402,9 +1286,7 @@ class MutableMapping(Mapping[_KT, _VT]): # -- weakref.WeakKeyDictionary.setdefault @overload def setdefault(self: MutableMapping[_KT, _T | None], key: _KT, default: None = None, /) -> _T | None: - """ - D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D - """ + """D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D""" @overload def setdefault(self, key: _KT, default: _VT, /) -> _VT: ... @@ -1430,8 +1312,7 @@ class MutableMapping(Mapping[_KT, _VT]): # -- weakref.WeakKeyDictionary.__ior__ @overload def update(self, m: SupportsKeysAndGetItem[_KT, _VT], /) -> None: - """ - D.update([E, ]**F) -> None. Update D from mapping/iterable E and F. + """D.update([E, ]**F) -> None. Update D from mapping/iterable E and F. If E present and has a .keys() method, does: for k in E.keys(): D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v @@ -1454,8 +1335,7 @@ TYPE_CHECKING: Final[bool] # This differs from runtime, but better reflects the fact that in reality # classes deriving from IO use different names for the arguments. class IO(Generic[AnyStr]): - """ - Generic base class for TextIO and BinaryIO. + """Generic base class for TextIO and BinaryIO. This is an abstract, generic version of the return of open(). @@ -1528,17 +1408,13 @@ class IO(Generic[AnyStr]): ) -> None: ... class BinaryIO(IO[bytes]): - """ - Typed version of the return of open() in binary mode. - """ + """Typed version of the return of open() in binary mode.""" @abstractmethod def __enter__(self) -> BinaryIO: ... class TextIO(IO[str]): - """ - Typed version of the return of open() in text mode. - """ + """Typed version of the return of open() in text mode.""" # See comment regarding the @properties in the `IO` class @property @@ -1580,8 +1456,7 @@ if sys.version_info >= (3, 14): *, format: Format | None = None, ) -> dict[str, Any]: # AnnotationForm - """ - Return type hints for an object. + """Return type hints for an object. This is often the same as obj.__annotations__, but it handles forward references encoded as string literals and recursively replaces all @@ -1619,8 +1494,7 @@ else: localns: Mapping[str, Any] | None = None, include_extras: bool = False, ) -> dict[str, Any]: # AnnotationForm - """ - Return type hints for an object. + """Return type hints for an object. This is often the same as obj.__annotations__, but it handles forward references encoded as string literals and recursively replaces all @@ -1652,8 +1526,7 @@ else: """ def get_args(tp: Any) -> tuple[Any, ...]: # AnnotationForm - """ - Get type arguments with all substitutions performed. + """Get type arguments with all substitutions performed. For unions, basic simplifications used by Union constructor are performed. @@ -1670,8 +1543,7 @@ def get_args(tp: Any) -> tuple[Any, ...]: # AnnotationForm if sys.version_info >= (3, 10): @overload def get_origin(tp: ParamSpecArgs | ParamSpecKwargs) -> ParamSpec: - """ - Get the unsubscripted version of a type. + """Get the unsubscripted version of a type. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar, Annotated, and others. Return None for unsupported types. @@ -1694,8 +1566,7 @@ if sys.version_info >= (3, 10): @overload def get_origin(tp: GenericAlias) -> type: - """ - Get the unsubscripted version of a type. + """Get the unsubscripted version of a type. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar and Annotated. Return None for unsupported types. Examples:: @@ -1713,8 +1584,7 @@ def get_origin(tp: GenericAlias) -> type: def get_origin(tp: Any) -> Any | None: ... # AnnotationForm @overload def cast(typ: type[_T], val: Any) -> _T: - """ - Cast a value to a type. + """Cast a value to a type. This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at @@ -1729,8 +1599,7 @@ def cast(typ: object, val: Any) -> Any: ... if sys.version_info >= (3, 11): def reveal_type(obj: _T, /) -> _T: - """ - Ask a static type checker to reveal the inferred type of an expression. + """Ask a static type checker to reveal the inferred type of an expression. When a static type checker encounters a call to ``reveal_type()``, it will emit the inferred type of the argument:: @@ -1746,8 +1615,7 @@ if sys.version_info >= (3, 11): """ def assert_never(arg: Never, /) -> Never: - """ - Statically assert that a line of code is unreachable. + """Statically assert that a line of code is unreachable. Example:: @@ -1767,8 +1635,7 @@ if sys.version_info >= (3, 11): """ def assert_type(val: _T, typ: Any, /) -> _T: # AnnotationForm - """ - Ask a static type checker to confirm that the value is of the given type. + """Ask a static type checker to confirm that the value is of the given type. At runtime this does nothing: it returns the first argument unchanged with no checks or side effects, no matter the actual type of the argument. @@ -1782,14 +1649,10 @@ if sys.version_info >= (3, 11): """ def clear_overloads() -> None: - """ - Clear all overloads in the registry. - """ + """Clear all overloads in the registry.""" def get_overloads(func: Callable[..., object]) -> Sequence[Callable[..., object]]: - """ - Return all defined overloads for *func* as a sequence. - """ + """Return all defined overloads for *func* as a sequence.""" def dataclass_transform( *, @@ -1800,8 +1663,7 @@ if sys.version_info >= (3, 11): field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = (), **kwargs: Any, ) -> IdentityFunction: - """ - Decorator to mark an object as providing dataclass-like behaviour. + """Decorator to mark an object as providing dataclass-like behaviour. The decorator can be applied to a function, class, or metaclass. @@ -1868,8 +1730,7 @@ if sys.version_info >= (3, 11): # Obsolete, will be changed to a function. Use _typeshed._type_checker_internals.NamedTupleFallback instead. class NamedTuple(tuple[Any, ...]): - """ - Typed version of namedtuple. + """Typed version of namedtuple. Usage:: @@ -1939,17 +1800,13 @@ class _TypedDict(Mapping[str, object], metaclass=ABCMeta): def values(self) -> dict_values[str, object]: ... @overload def __or__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: - """ - Return self|value. - """ + """Return self|value.""" @overload def __or__(self, value: dict[str, Any], /) -> dict[str, object]: ... @overload def __ror__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: - """ - Return value|self. - """ + """Return value|self.""" @overload def __ror__(self, value: dict[str, Any], /) -> dict[str, object]: ... @@ -1968,8 +1825,7 @@ if sys.version_info >= (3, 14): type_params: tuple[TypeVar, ParamSpec, TypeVarTuple] | None = None, format: Format | None = None, ) -> Any: # AnnotationForm - """ - Evaluate a forward reference as a type hint. + """Evaluate a forward reference as a type hint. This is similar to calling the ForwardRef.evaluate() method, but unlike that method, evaluate_forward_ref() also @@ -1991,9 +1847,7 @@ if sys.version_info >= (3, 14): else: @final class ForwardRef(_Final): - """ - Internal wrapper to hold a forward reference. - """ + """Internal wrapper to hold a forward reference.""" __forward_arg__: str __forward_code__: CodeType @@ -2046,8 +1900,7 @@ else: if sys.version_info >= (3, 10): def is_typeddict(tp: object) -> bool: - """ - Check if an annotation is a TypedDict class. + """Check if an annotation is a TypedDict class. For example:: @@ -2063,8 +1916,7 @@ if sys.version_info >= (3, 10): """ def _type_repr(obj: object) -> str: - """ - Return the repr() of an object, special-casing types (internal helper). + """Return the repr() of an object, special-casing types (internal helper). If obj is a type, we return a shorter version than the default type.__repr__, based on the module and qualified name, which is @@ -2074,8 +1926,7 @@ def _type_repr(obj: object) -> str: if sys.version_info >= (3, 12): def override(method: _F, /) -> _F: - """ - Indicate that a method is intended to override a method in a base class. + """Indicate that a method is intended to override a method in a base class. Usage:: @@ -2102,8 +1953,7 @@ if sys.version_info >= (3, 12): @final class TypeAliasType: - """ - Type alias. + """Type alias. Type aliases are created through the type statement:: @@ -2140,27 +1990,20 @@ if sys.version_info >= (3, 12): @property def __module__(self) -> str | None: ... # type: ignore[override] def __getitem__(self, parameters: Any) -> GenericAlias: # AnnotationForm - """ - Return self[key]. - """ + """Return self[key].""" def __or__(self, right: Any) -> _SpecialForm: - """ - Return self|value. - """ + """Return self|value.""" def __ror__(self, left: Any) -> _SpecialForm: - """ - Return value|self. - """ + """Return value|self.""" if sys.version_info >= (3, 14): @property def evaluate_value(self) -> EvaluateFunc: ... if sys.version_info >= (3, 13): def is_protocol(tp: type, /) -> bool: - """ - Return True if the given type is a Protocol. + """Return True if the given type is a Protocol. Example:: @@ -2175,8 +2018,7 @@ if sys.version_info >= (3, 13): """ def get_protocol_members(tp: type, /) -> frozenset[str]: - """ - Return the set of members defined in a Protocol. + """Return the set of members defined in a Protocol. Example:: diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/typing_extensions.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/typing_extensions.pyi index 3630e50256..e2bf68b53a 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/typing_extensions.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/typing_extensions.pyi @@ -221,8 +221,7 @@ class _SpecialForm(_Final): Protocol: _SpecialForm def runtime_checkable(cls: _TC) -> _TC: - """ - Mark a protocol class as a runtime protocol. + """Mark a protocol class as a runtime protocol. Such protocol can be used with isinstance() and issubclass(). Raise TypeError if applied to a non-protocol class. @@ -246,8 +245,7 @@ runtime = runtime_checkable Final: _SpecialForm def final(f: _F) -> _F: - """ - Decorator to indicate final methods and final classes. + """Decorator to indicate final methods and final classes. Use this decorator to indicate to type checkers that the decorated method cannot be overridden, and decorated class cannot be subclassed. @@ -304,17 +302,13 @@ class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): def __delitem__(self, k: Never) -> None: ... @overload def __or__(self, value: Self, /) -> Self: - """ - Return self|value. - """ + """Return self|value.""" @overload def __or__(self, value: dict[str, Any], /) -> dict[str, object]: ... @overload def __ror__(self, value: Self, /) -> Self: - """ - Return value|self. - """ + """Return value|self.""" @overload def __ror__(self, value: dict[str, Any], /) -> dict[str, object]: ... @@ -330,8 +324,7 @@ else: def get_type_hints( obj: Any, globalns: dict[str, Any] | None = None, localns: Mapping[str, Any] | None = None, include_extras: bool = False ) -> dict[str, AnnotationForm]: - """ - Return type hints for an object. + """Return type hints for an object. This is often the same as obj.__annotations__, but it handles forward references encoded as string literals, adds Optional[t] if a @@ -364,8 +357,7 @@ else: """ def get_args(tp: AnnotationForm) -> tuple[AnnotationForm, ...]: - """ - Get type arguments with all substitutions performed. + """Get type arguments with all substitutions performed. For unions, basic simplifications used by Union constructor are performed. @@ -382,8 +374,7 @@ def get_args(tp: AnnotationForm) -> tuple[AnnotationForm, ...]: if sys.version_info >= (3, 10): @overload def get_origin(tp: UnionType) -> type[UnionType]: - """ - Get the unsubscripted version of a type. + """Get the unsubscripted version of a type. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar, Annotated, and others. Return None for unsupported types. @@ -403,8 +394,7 @@ if sys.version_info >= (3, 10): @overload def get_origin(tp: GenericAlias) -> type: - """ - Get the unsubscripted version of a type. + """Get the unsubscripted version of a type. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar and Annotated. Return None for unsupported types. Examples:: @@ -440,8 +430,7 @@ if sys.version_info >= (3, 10): else: @final class ParamSpecArgs: - """ - The args for a ParamSpec object. + """The args for a ParamSpec object. Given a ParamSpec object P, P.args is an instance of ParamSpecArgs. @@ -459,8 +448,7 @@ else: @final class ParamSpecKwargs: - """ - The kwargs for a ParamSpec object. + """The kwargs for a ParamSpec object. Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs. @@ -480,8 +468,7 @@ else: TypeAlias: _SpecialForm TypeGuard: _SpecialForm def is_typeddict(tp: object) -> bool: - """ - Check if an annotation is a TypedDict class + """Check if an annotation is a TypedDict class For example:: class Film(TypedDict): @@ -514,8 +501,7 @@ else: Self: _SpecialForm Never: _SpecialForm def reveal_type(obj: _T, /) -> _T: - """ - Reveal the inferred type of a variable. + """Reveal the inferred type of a variable. When a static type checker encounters a call to ``reveal_type()``, it will emit the inferred type of the argument:: @@ -531,8 +517,7 @@ else: """ def assert_never(arg: Never, /) -> Never: - """ - Assert to the type checker that a line of code is unreachable. + """Assert to the type checker that a line of code is unreachable. Example:: @@ -552,8 +537,7 @@ else: """ def assert_type(val: _T, typ: AnnotationForm, /) -> _T: - """ - Assert (to the type checker) that the value is of the given type. + """Assert (to the type checker) that the value is of the given type. When the type checker encounters a call to assert_type(), it emits an error if the value is not of the specified type:: @@ -567,14 +551,10 @@ else: """ def clear_overloads() -> None: - """ - Clear all overloads in the registry. - """ + """Clear all overloads in the registry.""" def get_overloads(func: Callable[..., object]) -> Sequence[Callable[..., object]]: - """ - Return all defined overloads for *func* as a sequence. - """ + """Return all defined overloads for *func* as a sequence.""" Required: _SpecialForm NotRequired: _SpecialForm LiteralString: _SpecialForm @@ -589,8 +569,7 @@ else: field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = (), **kwargs: object, ) -> IdentityFunction: - """ - Decorator that marks a function, class, or metaclass as providing + """Decorator that marks a function, class, or metaclass as providing dataclass-like behavior. Example: @@ -652,8 +631,7 @@ else: """ class NamedTuple(tuple[Any, ...]): - """ - Typed version of namedtuple. + """Typed version of namedtuple. Usage:: @@ -686,8 +664,7 @@ else: def _replace(self, **kwargs: Any) -> Self: ... class NewType: - """ - NewType creates simple unique types with almost zero + """NewType creates simple unique types with almost zero runtime overhead. NewType(name, tp) is considered a subtype of tp by static type checkers. At runtime, NewType(name, tp) returns a dummy callable that simply returns its argument. Usage:: @@ -722,8 +699,7 @@ if sys.version_info >= (3, 12): ) else: def override(arg: _F, /) -> _F: - """ - Indicate that a method is intended to override a method in a base class. + """Indicate that a method is intended to override a method in a base class. Usage: @@ -749,8 +725,7 @@ else: """ def get_original_bases(cls: type, /) -> tuple[Any, ...]: - """ - Return the class's "original" bases prior to modification by `__mro_entries__`. + """Return the class's "original" bases prior to modification by `__mro_entries__`. Examples:: @@ -775,8 +750,7 @@ else: # allowlist for use as a Protocol. @runtime_checkable class Buffer(Protocol, abc.ABC): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] - """ - Base class for classes that implement the buffer protocol. + """Base class for classes that implement the buffer protocol. The buffer protocol allows Python objects to expose a low-level memory buffer interface. Before Python 3.12, it is not possible @@ -800,36 +774,28 @@ else: @runtime_checkable class SupportsInt(Protocol, metaclass=abc.ABCMeta): - """ - An ABC with one abstract method __int__. - """ + """An ABC with one abstract method __int__.""" @abc.abstractmethod def __int__(self) -> int: ... @runtime_checkable class SupportsFloat(Protocol, metaclass=abc.ABCMeta): - """ - An ABC with one abstract method __float__. - """ + """An ABC with one abstract method __float__.""" @abc.abstractmethod def __float__(self) -> float: ... @runtime_checkable class SupportsComplex(Protocol, metaclass=abc.ABCMeta): - """ - An ABC with one abstract method __complex__. - """ + """An ABC with one abstract method __complex__.""" @abc.abstractmethod def __complex__(self) -> complex: ... @runtime_checkable class SupportsBytes(Protocol, metaclass=abc.ABCMeta): - """ - An ABC with one abstract method __bytes__. - """ + """An ABC with one abstract method __bytes__.""" @abc.abstractmethod def __bytes__(self) -> bytes: ... @@ -841,18 +807,14 @@ else: @runtime_checkable class SupportsAbs(Protocol[_T_co]): - """ - An ABC with one abstract method __abs__ that is covariant in its return type. - """ + """An ABC with one abstract method __abs__ that is covariant in its return type.""" @abc.abstractmethod def __abs__(self) -> _T_co: ... @runtime_checkable class SupportsRound(Protocol[_T_co]): - """ - An ABC with one abstract method __round__ that is covariant in its return type. - """ + """An ABC with one abstract method __round__ that is covariant in its return type.""" @overload @abc.abstractmethod @@ -866,16 +828,14 @@ if sys.version_info >= (3, 14): else: @runtime_checkable class Reader(Protocol[_T_co]): - """ - Protocol for simple I/O reader instances. + """Protocol for simple I/O reader instances. This protocol only supports blocking I/O. """ @abc.abstractmethod def read(self, size: int = ..., /) -> _T_co: - """ - Read data from the input stream and return it. + """Read data from the input stream and return it. If *size* is specified, at most *size* items (bytes/characters) will be read. @@ -883,17 +843,14 @@ else: @runtime_checkable class Writer(Protocol[_T_contra]): - """ - Protocol for simple I/O writer instances. + """Protocol for simple I/O writer instances. This protocol only supports blocking I/O. """ @abc.abstractmethod def write(self, data: _T_contra, /) -> int: - """ - Write *data* to the output stream and return the number of items written. - """ + """Write *data* to the output stream and return the number of items written.""" if sys.version_info >= (3, 13): from types import CapsuleType as CapsuleType @@ -910,8 +867,7 @@ if sys.version_info >= (3, 13): from warnings import deprecated as deprecated else: def is_protocol(tp: type, /) -> bool: - """ - Return True if the given type is a Protocol. + """Return True if the given type is a Protocol. Example:: @@ -926,8 +882,7 @@ else: """ def get_protocol_members(tp: type, /) -> frozenset[str]: - """ - Return the set of members defined in a Protocol. + """Return the set of members defined in a Protocol. Example:: @@ -947,8 +902,7 @@ else: NoDefault: _NoDefaultType @final class CapsuleType: - """ - Capsule objects let you wrap a C "void *" pointer in a Python + """Capsule objects let you wrap a C "void *" pointer in a Python object. They're a way of passing data through the Python interpreter without creating your own custom type. @@ -959,8 +913,7 @@ else: """ class deprecated: - """ - Indicate that a class, function or overload is deprecated. + """Indicate that a class, function or overload is deprecated. When this decorator is applied to an object, the type checker will generate a diagnostic on usage of the deprecated object. @@ -1009,9 +962,7 @@ else: @final class TypeVar: - """ - Type variable. - """ + """Type variable.""" @property def __name__(self) -> str: ... @@ -1041,22 +992,16 @@ else: def __typing_prepare_subst__(self, alias: Any, args: Any) -> tuple[Any, ...]: ... if sys.version_info >= (3, 10): def __or__(self, right: Any) -> _SpecialForm: - """ - Return self|value. - """ + """Return self|value.""" def __ror__(self, left: Any) -> _SpecialForm: - """ - Return value|self. - """ + """Return value|self.""" if sys.version_info >= (3, 11): def __typing_subst__(self, arg: Any) -> Any: ... @final class ParamSpec: - """ - Parameter specification. - """ + """Parameter specification.""" @property def __name__(self) -> str: ... @@ -1087,20 +1032,14 @@ else: def __typing_prepare_subst__(self, alias: Any, args: Any) -> tuple[Any, ...]: ... if sys.version_info >= (3, 10): def __or__(self, right: Any) -> _SpecialForm: - """ - Return self|value. - """ + """Return self|value.""" def __ror__(self, left: Any) -> _SpecialForm: - """ - Return value|self. - """ + """Return value|self.""" @final class TypeVarTuple: - """ - Type variable tuple. - """ + """Type variable tuple.""" @property def __name__(self) -> str: ... @@ -1120,8 +1059,7 @@ if sys.version_info >= (3, 14): else: @final class TypeAliasType: - """ - Create named, parameterized type aliases. + """Create named, parameterized type aliases. This provides a backport of the new `type` statement in Python 3.12: @@ -1163,8 +1101,7 @@ else: # It's writable on types, but not on instances of TypeAliasType. @property def __module__(self) -> str | None: # type: ignore[override] - """ - str(object='') -> str + """str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or @@ -1184,8 +1121,7 @@ else: # PEP 727 class Doc: - """ - Define the documentation of a type annotation using ``Annotated``, to be + """Define the documentation of a type annotation using ``Annotated``, to be used in class attributes, function and method parameters, return values, and variables. @@ -1222,9 +1158,7 @@ if sys.version_info >= (3, 14): from annotationlib import Format as Format, get_annotations as get_annotations else: class Format(enum.IntEnum): - """ - An enumeration. - """ + """An enumeration.""" VALUE = 1 VALUE_WITH_FAKE_GLOBALS = 2 @@ -1240,8 +1174,7 @@ else: eval_str: bool = False, format: Literal[Format.STRING], ) -> dict[str, str]: - """ - Compute the annotations dict for an object. + """Compute the annotations dict for an object. obj may be a callable, class, or module. Passing in an object of any other type raises TypeError. @@ -1305,8 +1238,7 @@ else: format: Literal[Format.STRING], _recursive_guard: Container[str] = ..., ) -> str: - """ - Evaluate a forward reference as a type hint. + """Evaluate a forward reference as a type hint. This is similar to calling the ForwardRef.evaluate() method, but unlike that method, evaluate_forward_ref() also: @@ -1353,8 +1285,7 @@ else: # PEP 661 class Sentinel: - """ - Create a unique sentinel object. + """Create a unique sentinel object. *name* should be the name of the variable to which the return value shall be assigned. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/unicodedata.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/unicodedata.pyi index 5afdafab2b..dcbe2a5cdb 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/unicodedata.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/unicodedata.pyi @@ -24,28 +24,23 @@ _T = TypeVar("_T") _NormalizationForm: TypeAlias = Literal["NFC", "NFD", "NFKC", "NFKD"] def bidirectional(chr: str, /) -> str: - """ - Returns the bidirectional class assigned to the character chr as string. + """Returns the bidirectional class assigned to the character chr as string. If no such value is defined, an empty string is returned. """ def category(chr: str, /) -> str: - """ - Returns the general category assigned to the character chr as string. - """ + """Returns the general category assigned to the character chr as string.""" def combining(chr: str, /) -> int: - """ - Returns the canonical combining class assigned to the character chr as integer. + """Returns the canonical combining class assigned to the character chr as integer. Returns 0 if no combining class is defined. """ @overload def decimal(chr: str, /) -> int: - """ - Converts a Unicode character into its equivalent decimal value. + """Converts a Unicode character into its equivalent decimal value. Returns the decimal value assigned to the character chr as integer. If no such value is defined, default is returned, or, if not given, @@ -55,16 +50,14 @@ def decimal(chr: str, /) -> int: @overload def decimal(chr: str, default: _T, /) -> int | _T: ... def decomposition(chr: str, /) -> str: - """ - Returns the character decomposition mapping assigned to the character chr as string. + """Returns the character decomposition mapping assigned to the character chr as string. An empty string is returned in case no such mapping is defined. """ @overload def digit(chr: str, /) -> int: - """ - Converts a Unicode character into its equivalent digit value. + """Converts a Unicode character into its equivalent digit value. Returns the digit value assigned to the character chr as integer. If no such value is defined, default is returned, or, if not given, @@ -77,28 +70,23 @@ def digit(chr: str, default: _T, /) -> int | _T: ... _EastAsianWidth: TypeAlias = Literal["F", "H", "W", "Na", "A", "N"] def east_asian_width(chr: str, /) -> _EastAsianWidth: - """ - Returns the east asian width assigned to the character chr as string. - """ + """Returns the east asian width assigned to the character chr as string.""" def is_normalized(form: _NormalizationForm, unistr: str, /) -> bool: - """ - Return whether the Unicode string unistr is in the normal form 'form'. + """Return whether the Unicode string unistr is in the normal form 'form'. Valid values for form are 'NFC', 'NFKC', 'NFD', and 'NFKD'. """ def lookup(name: str | ReadOnlyBuffer, /) -> str: - """ - Look up character by name. + """Look up character by name. If a character with the given name is found, return the corresponding character. If not found, KeyError is raised. """ def mirrored(chr: str, /) -> int: - """ - Returns the mirrored property assigned to the character chr as integer. + """Returns the mirrored property assigned to the character chr as integer. Returns 1 if the character has been identified as a "mirrored" character in bidirectional text, 0 otherwise. @@ -106,8 +94,7 @@ def mirrored(chr: str, /) -> int: @overload def name(chr: str, /) -> str: - """ - Returns the name assigned to the character chr as a string. + """Returns the name assigned to the character chr as a string. If no name is defined, default is returned, or, if not given, ValueError is raised. @@ -116,16 +103,14 @@ def name(chr: str, /) -> str: @overload def name(chr: str, default: _T, /) -> str | _T: ... def normalize(form: _NormalizationForm, unistr: str, /) -> str: - """ - Return the normal form 'form' for the Unicode string unistr. + """Return the normal form 'form' for the Unicode string unistr. Valid values for form are 'NFC', 'NFKC', 'NFD', and 'NFKD'. """ @overload def numeric(chr: str, /) -> float: - """ - Converts a Unicode character into its equivalent numeric value. + """Converts a Unicode character into its equivalent numeric value. Returns the numeric value assigned to the character chr as float. If no such value is defined, default is returned, or, if not given, @@ -140,28 +125,23 @@ class UCD: # (unicodedata_functions) and hence identical to the functions above. unidata_version: str def bidirectional(self, chr: str, /) -> str: - """ - Returns the bidirectional class assigned to the character chr as string. + """Returns the bidirectional class assigned to the character chr as string. If no such value is defined, an empty string is returned. """ def category(self, chr: str, /) -> str: - """ - Returns the general category assigned to the character chr as string. - """ + """Returns the general category assigned to the character chr as string.""" def combining(self, chr: str, /) -> int: - """ - Returns the canonical combining class assigned to the character chr as integer. + """Returns the canonical combining class assigned to the character chr as integer. Returns 0 if no combining class is defined. """ @overload def decimal(self, chr: str, /) -> int: - """ - Converts a Unicode character into its equivalent decimal value. + """Converts a Unicode character into its equivalent decimal value. Returns the decimal value assigned to the character chr as integer. If no such value is defined, default is returned, or, if not given, @@ -171,16 +151,14 @@ class UCD: @overload def decimal(self, chr: str, default: _T, /) -> int | _T: ... def decomposition(self, chr: str, /) -> str: - """ - Returns the character decomposition mapping assigned to the character chr as string. + """Returns the character decomposition mapping assigned to the character chr as string. An empty string is returned in case no such mapping is defined. """ @overload def digit(self, chr: str, /) -> int: - """ - Converts a Unicode character into its equivalent digit value. + """Converts a Unicode character into its equivalent digit value. Returns the digit value assigned to the character chr as integer. If no such value is defined, default is returned, or, if not given, @@ -190,28 +168,23 @@ class UCD: @overload def digit(self, chr: str, default: _T, /) -> int | _T: ... def east_asian_width(self, chr: str, /) -> _EastAsianWidth: - """ - Returns the east asian width assigned to the character chr as string. - """ + """Returns the east asian width assigned to the character chr as string.""" def is_normalized(self, form: _NormalizationForm, unistr: str, /) -> bool: - """ - Return whether the Unicode string unistr is in the normal form 'form'. + """Return whether the Unicode string unistr is in the normal form 'form'. Valid values for form are 'NFC', 'NFKC', 'NFD', and 'NFKD'. """ def lookup(self, name: str | ReadOnlyBuffer, /) -> str: - """ - Look up character by name. + """Look up character by name. If a character with the given name is found, return the corresponding character. If not found, KeyError is raised. """ def mirrored(self, chr: str, /) -> int: - """ - Returns the mirrored property assigned to the character chr as integer. + """Returns the mirrored property assigned to the character chr as integer. Returns 1 if the character has been identified as a "mirrored" character in bidirectional text, 0 otherwise. @@ -219,8 +192,7 @@ class UCD: @overload def name(self, chr: str, /) -> str: - """ - Returns the name assigned to the character chr as a string. + """Returns the name assigned to the character chr as a string. If no name is defined, default is returned, or, if not given, ValueError is raised. @@ -229,16 +201,14 @@ class UCD: @overload def name(self, chr: str, default: _T, /) -> str | _T: ... def normalize(self, form: _NormalizationForm, unistr: str, /) -> str: - """ - Return the normal form 'form' for the Unicode string unistr. + """Return the normal form 'form' for the Unicode string unistr. Valid values for form are 'NFC', 'NFKC', 'NFD', and 'NFKD'. """ @overload def numeric(self, chr: str, /) -> float: - """ - Converts a Unicode character into its equivalent numeric value. + """Converts a Unicode character into its equivalent numeric value. Returns the numeric value assigned to the character chr as float. If no such value is defined, default is returned, or, if not given, diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/__init__.pyi index 0d0cf6b528..921c450081 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/__init__.pyi @@ -1,4 +1,5 @@ """ + Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's Smalltalk testing framework (used with permission). diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/_log.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/_log.pyi index 368b34ee03..dddae53132 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/_log.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/_log.pyi @@ -7,17 +7,13 @@ from unittest.case import TestCase, _BaseTestCaseContext _L = TypeVar("_L", None, _LoggingWatcher) class _LoggingWatcher(NamedTuple): - """ - _LoggingWatcher(records, output) - """ + """_LoggingWatcher(records, output)""" records: list[logging.LogRecord] output: list[str] class _AssertLogsContext(_BaseTestCaseContext, Generic[_L]): - """ - A context manager for assertLogs() and assertNoLogs() - """ + """A context manager for assertLogs() and assertNoLogs()""" LOGGING_FORMAT: ClassVar[str] logger_name: str diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/async_case.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/async_case.pyi index ece06f5ec3..07dc69509e 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/async_case.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/async_case.pyi @@ -21,8 +21,7 @@ class IsolatedAsyncioTestCase(TestCase): def addAsyncCleanup(self, func: Callable[_P, Awaitable[object]], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... if sys.version_info >= (3, 11): async def enterAsyncContext(self, cm: AbstractAsyncContextManager[_T]) -> _T: - """ - Enters the supplied asynchronous context manager. + """Enters the supplied asynchronous context manager. If successful, also adds its __aexit__ method as a cleanup function and returns the result of the __aenter__ method. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/case.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/case.pyi index 75af230214..a80568e315 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/case.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/case.pyi @@ -47,50 +47,38 @@ class _AssertRaisesBaseContext(_BaseTestCaseContext): # This returns Self if args is the empty list, and None otherwise. # but it's not possible to construct an overload which expresses that def handle(self, name: str, args: list[Any], kwargs: dict[str, Any]) -> Any: - """ - If args is empty, assertRaises/Warns is being used as a + """If args is empty, assertRaises/Warns is being used as a context manager, so check for a 'msg' kwarg and return self. If args is not empty, call a callable passing positional and keyword arguments. """ def addModuleCleanup(function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: - """ - Same as addCleanup, except the cleanup items are called even if + """Same as addCleanup, except the cleanup items are called even if setUpModule fails (unlike tearDownModule). """ def doModuleCleanups() -> None: - """ - Execute all module cleanup functions. Normally called for you after + """Execute all module cleanup functions. Normally called for you after tearDownModule. """ if sys.version_info >= (3, 11): def enterModuleContext(cm: AbstractContextManager[_T]) -> _T: - """ - Same as enterContext, but module-wide. - """ + """Same as enterContext, but module-wide.""" def expectedFailure(test_item: _FT) -> _FT: ... def skip(reason: str) -> Callable[[_FT], _FT]: - """ - Unconditionally skip a test. - """ + """Unconditionally skip a test.""" def skipIf(condition: object, reason: str) -> Callable[[_FT], _FT]: - """ - Skip a test if the condition is true. - """ + """Skip a test if the condition is true.""" def skipUnless(condition: object, reason: str) -> Callable[[_FT], _FT]: - """ - Skip a test unless the condition is true. - """ + """Skip a test unless the condition is true.""" class SkipTest(Exception): - """ - Raise this exception in a test to skip it. + """Raise this exception in a test to skip it. Usually you can use TestCase.skipTest() or one of the skipping decorators instead of raising this directly. @@ -109,8 +97,7 @@ else: _ClassInfo: TypeAlias = type | tuple[_ClassInfo, ...] class TestCase: - """ - A class whose instances are single test cases. + """A class whose instances are single test cases. By default, the test code itself should be placed in a method named 'runTest'. @@ -150,8 +137,7 @@ class TestCase: # undocumented _testMethodDoc: str def __init__(self, methodName: str = "runTest") -> None: - """ - Create an instance of the class that will use the named test + """Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name. """ @@ -159,37 +145,26 @@ class TestCase: def __eq__(self, other: object) -> bool: ... def __hash__(self) -> int: ... def setUp(self) -> None: - """ - Hook method for setting up the test fixture before exercising it. - """ + """Hook method for setting up the test fixture before exercising it.""" def tearDown(self) -> None: - """ - Hook method for deconstructing the test fixture after testing it. - """ + """Hook method for deconstructing the test fixture after testing it.""" @classmethod def setUpClass(cls) -> None: - """ - Hook method for setting up class fixture before running tests in the class. - """ + """Hook method for setting up class fixture before running tests in the class.""" @classmethod def tearDownClass(cls) -> None: - """ - Hook method for deconstructing the class fixture after running all tests in the class. - """ + """Hook method for deconstructing the class fixture after running all tests in the class.""" 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: - """ - Skip this test. - """ + """Skip this test.""" def subTest(self, msg: Any = ..., **params: Any) -> AbstractContextManager[None]: - """ - Return a context manager that will return the enclosed block + """Return a context manager that will return the enclosed block of code in a subtest identified by the optional message and keyword parameters. A failure in the subtest marks the test case as failed but resumes execution at the end of the enclosed @@ -197,104 +172,73 @@ class TestCase: """ def debug(self) -> None: - """ - Run the test without collecting errors in a TestResult - """ + """Run the test without collecting errors in a TestResult""" if sys.version_info < (3, 11): def _addSkip(self, result: unittest.result.TestResult, test_case: TestCase, reason: str) -> None: ... def assertEqual(self, first: Any, second: Any, msg: Any = None) -> None: - """ - Fail if the two objects are unequal as determined by the '==' + """Fail if the two objects are unequal as determined by the '==' operator. """ def assertNotEqual(self, first: Any, second: Any, msg: Any = None) -> None: - """ - Fail if the two objects are equal as determined by the '!=' + """Fail if the two objects are equal as determined by the '!=' operator. """ def assertTrue(self, expr: Any, msg: Any = None) -> None: - """ - Check that the expression is true. - """ + """Check that the expression is true.""" def assertFalse(self, expr: Any, msg: Any = None) -> None: - """ - Check that the expression is false. - """ + """Check that the expression is false.""" def assertIs(self, expr1: object, expr2: object, msg: Any = None) -> None: - """ - Just like self.assertTrue(a is b), but with a nicer default message. - """ + """Just like self.assertTrue(a is b), but with a nicer default message.""" def assertIsNot(self, expr1: object, expr2: object, msg: Any = None) -> None: - """ - Just like self.assertTrue(a is not b), but with a nicer default message. - """ + """Just like self.assertTrue(a is not b), but with a nicer default message.""" def assertIsNone(self, obj: object, msg: Any = None) -> None: - """ - Same as self.assertTrue(obj is None), with a nicer default message. - """ + """Same as self.assertTrue(obj is None), with a nicer default message.""" def assertIsNotNone(self, obj: object, msg: Any = None) -> None: - """ - Included for symmetry with assertIsNone. - """ + """Included for symmetry with assertIsNone.""" def assertIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = None) -> None: - """ - Just like self.assertTrue(a in b), but with a nicer default message. - """ + """Just like self.assertTrue(a in b), but with a nicer default message.""" def assertNotIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = None) -> None: - """ - Just like self.assertTrue(a not in b), but with a nicer default message. - """ + """Just like self.assertTrue(a not in b), but with a nicer default message.""" def assertIsInstance(self, obj: object, cls: _ClassInfo, msg: Any = None) -> None: - """ - Same as self.assertTrue(isinstance(obj, cls)), with a nicer + """Same as self.assertTrue(isinstance(obj, cls)), with a nicer default message. """ def assertNotIsInstance(self, obj: object, cls: _ClassInfo, msg: Any = None) -> None: - """ - Included for symmetry with assertIsInstance. - """ + """Included for symmetry with assertIsInstance.""" @overload def assertGreater(self, a: SupportsDunderGT[_T], b: _T, msg: Any = None) -> None: - """ - Just like self.assertTrue(a > b), but with a nicer default message. - """ + """Just like self.assertTrue(a > b), but with a nicer default message.""" @overload def assertGreater(self, a: _T, b: SupportsDunderLT[_T], msg: Any = None) -> None: ... @overload def assertGreaterEqual(self, a: SupportsDunderGE[_T], b: _T, msg: Any = None) -> None: - """ - Just like self.assertTrue(a >= b), but with a nicer default message. - """ + """Just like self.assertTrue(a >= b), but with a nicer default message.""" @overload def assertGreaterEqual(self, a: _T, b: SupportsDunderLE[_T], msg: Any = None) -> None: ... @overload def assertLess(self, a: SupportsDunderLT[_T], b: _T, msg: Any = None) -> None: - """ - Just like self.assertTrue(a < b), but with a nicer default message. - """ + """Just like self.assertTrue(a < b), but with a nicer default message.""" @overload def assertLess(self, a: _T, b: SupportsDunderGT[_T], msg: Any = None) -> None: ... @overload def assertLessEqual(self, a: SupportsDunderLE[_T], b: _T, msg: Any = None) -> None: - """ - Just like self.assertTrue(a <= b), but with a nicer default message. - """ + """Just like self.assertTrue(a <= b), but with a nicer default message.""" @overload def assertLessEqual(self, a: _T, b: SupportsDunderGE[_T], msg: Any = None) -> None: ... @@ -309,8 +253,7 @@ class TestCase: *args: Any, **kwargs: Any, ) -> None: - """ - Fail unless an exception of class expected_exception is raised + """Fail unless an exception of class expected_exception is raised by the callable when invoked with specified positional and keyword arguments. If a different type of exception is raised, it will not be caught, and the test case will be @@ -349,8 +292,7 @@ class TestCase: *args: Any, **kwargs: Any, ) -> None: - """ - Asserts that the message in a raised exception matches a regex. + """Asserts that the message in a raised exception matches a regex. Args: expected_exception: Exception class expected to be raised. @@ -374,8 +316,7 @@ class TestCase: *args: _P.args, **kwargs: _P.kwargs, ) -> None: - """ - Fail unless a warning of class warnClass is triggered + """Fail unless a warning of class warnClass is triggered by the callable when invoked with specified positional and keyword arguments. If a different type of warning is triggered, it will not be handled: depending on the other @@ -416,8 +357,7 @@ class TestCase: *args: _P.args, **kwargs: _P.kwargs, ) -> None: - """ - Asserts that the message in a triggered warning matches a regexp. + """Asserts that the message in a triggered warning matches a regexp. Basic functioning is similar to assertWarns() with the addition that only warnings whose messages also match the regular expression are considered successful matches. @@ -439,8 +379,7 @@ class TestCase: def assertLogs( self, logger: str | logging.Logger | None = None, level: int | str | None = None ) -> _AssertLogsContext[_LoggingWatcher]: - """ - Fail unless a log message of level *level* or higher is emitted + """Fail unless a log message of level *level* or higher is emitted on *logger_name* or its children. If omitted, *level* defaults to INFO and *logger* defaults to the root logger. @@ -463,8 +402,7 @@ class TestCase: def assertNoLogs( self, logger: str | logging.Logger | None = None, level: int | str | None = None ) -> _AssertLogsContext[None]: - """ - Fail unless no log messages of level *level* or higher are emitted + """Fail unless no log messages of level *level* or higher are emitted on *logger_name* or its children. This method must be used as a context manager. @@ -472,8 +410,7 @@ class TestCase: @overload def assertAlmostEqual(self, first: _S, second: _S, places: None, msg: Any, delta: _SupportsAbsAndDunderGE) -> None: - """ - Fail if the two objects are unequal as determined by their + """Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is more than the given @@ -510,8 +447,7 @@ class TestCase: ) -> None: ... @overload def assertNotAlmostEqual(self, first: _S, second: _S, places: None, msg: Any, delta: _SupportsAbsAndDunderGE) -> None: - """ - Fail if the two objects are equal as determined by their + """Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is less than the given delta. @@ -545,18 +481,13 @@ class TestCase: delta: None = None, ) -> None: ... def assertRegex(self, text: AnyStr, expected_regex: AnyStr | Pattern[AnyStr], msg: Any = None) -> None: - """ - Fail the test unless the text matches the regular expression. - """ + """Fail the test unless the text matches the regular expression.""" def assertNotRegex(self, text: AnyStr, unexpected_regex: AnyStr | Pattern[AnyStr], msg: Any = None) -> None: - """ - Fail the test if the text matches the regular expression. - """ + """Fail the test if the text matches the regular expression.""" def assertCountEqual(self, first: Iterable[Any], second: Iterable[Any], msg: Any = None) -> None: - """ - Asserts that two iterables have the same elements, the same number of + """Asserts that two iterables have the same elements, the same number of times, without regard to order. self.assertEqual(Counter(list(first)), @@ -568,8 +499,7 @@ class TestCase: """ def addTypeEqualityFunc(self, typeobj: type[Any], function: Callable[..., None]) -> None: - """ - Add a type specific assertEqual style function to compare a type. + """Add a type specific assertEqual style function to compare a type. This method is for use by TestCase subclasses that need to register their own type equality functions to provide nicer error messages. @@ -583,15 +513,12 @@ class TestCase: """ def assertMultiLineEqual(self, first: str, second: str, msg: Any = None) -> None: - """ - Assert that two multi-line strings are equal. - """ + """Assert that two multi-line strings are equal.""" def assertSequenceEqual( self, seq1: Sequence[Any], seq2: Sequence[Any], msg: Any = None, seq_type: type[Sequence[Any]] | None = None ) -> None: - """ - An equality assertion for ordered sequences (like lists and tuples). + """An equality assertion for ordered sequences (like lists and tuples). For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator. @@ -606,8 +533,7 @@ class TestCase: """ def assertListEqual(self, list1: list[Any], list2: list[Any], msg: Any = None) -> None: - """ - A list-specific equality assertion. + """A list-specific equality assertion. Args: list1: The first list to compare. @@ -617,8 +543,7 @@ class TestCase: """ def assertTupleEqual(self, tuple1: tuple[Any, ...], tuple2: tuple[Any, ...], msg: Any = None) -> None: - """ - A tuple-specific equality assertion. + """A tuple-specific equality assertion. Args: tuple1: The first tuple to compare. @@ -628,8 +553,7 @@ class TestCase: """ def assertSetEqual(self, set1: AbstractSet[object], set2: AbstractSet[object], msg: Any = None) -> None: - """ - A set-specific equality assertion. + """A set-specific equality assertion. Args: set1: The first set to compare. @@ -645,16 +569,13 @@ class TestCase: # 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: - """ - Fail immediately, with the given message. - """ + """Fail immediately, with the given message.""" def countTestCases(self) -> int: ... def defaultTestResult(self) -> unittest.result.TestResult: ... def id(self) -> str: ... def shortDescription(self) -> str | None: - """ - Returns a one-line description of the test, or None if no + """Returns a one-line description of the test, or None if no description has been provided. The default implementation of this method returns the first line of @@ -662,8 +583,7 @@ class TestCase: """ def addCleanup(self, function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: - """ - Add a function, with arguments, to be called when the test is + """Add a function, with arguments, to be called when the test is completed. Functions added are called on a LIFO basis and are called after tearDown on test failure or success. @@ -671,42 +591,35 @@ class TestCase: """ if sys.version_info >= (3, 11): def enterContext(self, cm: AbstractContextManager[_T]) -> _T: - """ - Enters the supplied context manager. + """Enters the supplied context manager. If successful, also adds its __exit__ method as a cleanup function and returns the result of the __enter__ method. """ def doCleanups(self) -> None: - """ - Execute all cleanup functions. Normally called for you after + """Execute all cleanup functions. Normally called for you after tearDown. """ @classmethod def addClassCleanup(cls, function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: - """ - Same as addCleanup, except the cleanup items are called even if + """Same as addCleanup, except the cleanup items are called even if setUpClass fails (unlike tearDownClass). """ @classmethod def doClassCleanups(cls) -> None: - """ - Execute all class cleanup functions. Normally called for you after + """Execute all class cleanup functions. Normally called for you after tearDownClass. """ if sys.version_info >= (3, 11): @classmethod def enterClassContext(cls, cm: AbstractContextManager[_T]) -> _T: - """ - Same as enterContext, but class-wide. - """ + """Same as enterContext, but class-wide.""" def _formatMessage(self, msg: str | None, standardMsg: str) -> str: # undocumented - """ - Honour the longMessage attribute when generating failure messages. + """Honour the longMessage attribute when generating failure messages. If longMessage is False this means: * Use only an explicit message if it is provided * Otherwise use the standard message for the assert @@ -717,8 +630,7 @@ class TestCase: """ def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]: # undocumented - """ - Get a detailed comparison function for the types of the two args. + """Get a detailed comparison function for the types of the two args. Returns: A callable accepting (first, second, msg=None) that will raise a failure exception if first != second with a useful human @@ -759,8 +671,7 @@ class TestCase: def assertNotEndsWith(self, s: _SB, suffix: _SB | tuple[_SB, ...], msg: Any = None) -> None: ... class FunctionTestCase(TestCase): - """ - A test case that wraps a test function. + """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the unittest framework. Optionally, set-up and tidy-up functions can be @@ -780,9 +691,7 @@ class FunctionTestCase(TestCase): def __eq__(self, other: object) -> bool: ... class _AssertRaisesContext(_AssertRaisesBaseContext, Generic[_E]): - """ - A context manager used to implement TestCase.assertRaises* methods. - """ + """A context manager used to implement TestCase.assertRaises* methods.""" exception: _E def __enter__(self) -> Self: ... @@ -790,16 +699,13 @@ class _AssertRaisesContext(_AssertRaisesBaseContext, Generic[_E]): self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None ) -> bool: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ class _AssertWarnsContext(_AssertRaisesBaseContext): - """ - A context manager used to implement TestCase.assertWarns* methods. - """ + """A context manager used to implement TestCase.assertWarns* methods.""" warning: WarningMessage filename: str diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/loader.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/loader.pyi index b4539cea05..b74a2836b9 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/loader.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/loader.pyi @@ -17,8 +17,7 @@ _SuiteClass: TypeAlias = Callable[[list[unittest.case.TestCase]], unittest.suite VALID_MODULE_NAME: Final[Pattern[str]] class TestLoader: - """ - This class is responsible for loading tests according to various criteria + """This class is responsible for loading tests according to various criteria and returning them wrapped in a TestSuite """ @@ -28,23 +27,16 @@ class TestLoader: testNamePatterns: list[str] | None suiteClass: _SuiteClass def loadTestsFromTestCase(self, testCaseClass: type[unittest.case.TestCase]) -> unittest.suite.TestSuite: - """ - Return a suite of all test cases contained in testCaseClass - """ + """Return a suite of all test cases contained in testCaseClass""" if sys.version_info >= (3, 12): def loadTestsFromModule(self, module: ModuleType, *, pattern: str | None = None) -> unittest.suite.TestSuite: - """ - Return a suite of all test cases contained in the given module - """ + """Return a suite of all test cases contained in the given module""" else: def loadTestsFromModule(self, module: ModuleType, *args: Any, pattern: str | None = None) -> unittest.suite.TestSuite: - """ - Return a suite of all test cases contained in the given module - """ + """Return a suite of all test cases contained in the given module""" def loadTestsFromName(self, name: str, module: ModuleType | None = None) -> unittest.suite.TestSuite: - """ - Return a suite of all test cases given a string specifier. + """Return a suite of all test cases given a string specifier. The name may resolve either to a module, a test case class, a test method within a test case class, or a callable object which @@ -54,19 +46,15 @@ class TestLoader: """ def loadTestsFromNames(self, names: Sequence[str], module: ModuleType | None = None) -> unittest.suite.TestSuite: - """ - Return a suite of all test cases found using the given sequence + """Return a suite of all test cases found using the given sequence of string specifiers. See 'loadTestsFromName()'. """ def getTestCaseNames(self, testCaseClass: type[unittest.case.TestCase]) -> Sequence[str]: - """ - Return a sorted sequence of method names found within testCaseClass - """ + """Return a sorted sequence of method names found within testCaseClass""" def discover(self, start_dir: str, pattern: str = "test*.py", top_level_dir: str | None = None) -> unittest.suite.TestSuite: - """ - Find and return all test modules from the specified start + """Find and return all test modules from the specified start directory, recursing into subdirectories to find them and return all tests found within them. Only test files that match the pattern will be loaded. (Using shell style pattern matching.) diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/main.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/main.pyi index aff5d72fe8..da35593d58 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/main.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/main.pyi @@ -20,8 +20,7 @@ class _TestRunner(Protocol): # not really documented class TestProgram: - """ - A command-line program that runs a set of tests; this is primarily + """A command-line program that runs a set of tests; this is primarily for making test modules conveniently executable. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/mock.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/mock.pyi index 27ca19870b..7c5544f87f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/mock.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/mock.pyi @@ -55,17 +55,13 @@ else: FILTER_DIR: Any class _SentinelObject: - """ - A unique, named, sentinel object. - """ + """A unique, named, sentinel object.""" name: Any def __init__(self, name: Any) -> None: ... class _Sentinel: - """ - Access attributes to return a named object, usable as a sentinel. - """ + """Access attributes to return a named object, usable as a sentinel.""" def __getattr__(self, name: str) -> Any: ... @@ -77,8 +73,7 @@ _NameArgsKwargs: TypeAlias = tuple[str, tuple[Any, ...], Mapping[str, Any]] _CallValue: TypeAlias = str | tuple[Any, ...] | Mapping[str, Any] | _ArgsKwargs | _NameArgsKwargs class _Call(tuple[Any, ...]): - """ - A tuple for holding the results of a call to a mock, either in the form + """A tuple for holding the results of a call to a mock, either in the form `(args, kwargs)` or `(name, args, kwargs)`. If args or kwargs are empty then a call tuple will compare equal to @@ -118,8 +113,7 @@ class _Call(tuple[Any, ...]): @property def kwargs(self) -> Mapping[str, Any]: ... def call_list(self) -> Any: - """ - For a call object that represents multiple calls, `call_list` + """For a call object that represents multiple calls, `call_list` returns a list of all the intermediate calls as well as the final call. """ @@ -135,9 +129,7 @@ class Base: # We subclass with "Any" because mocks are explicitly designed to stand in for other types, # something that can't be expressed with our static type system. class NonCallableMock(Base, Any): - """ - A non-callable version of `Mock` - """ + """A non-callable version of `Mock`""" if sys.version_info >= (3, 12): def __new__( @@ -177,49 +169,36 @@ class NonCallableMock(Base, Any): def __delattr__(self, name: str) -> None: ... def __setattr__(self, name: str, value: Any) -> None: ... def __dir__(self) -> list[str]: - """ - Filter the output of `dir(mock)` to only useful members. - """ + """Filter the output of `dir(mock)` to only useful members.""" def assert_called_with(self, *args: Any, **kwargs: Any) -> None: - """ - assert that the last call was made with the specified arguments. + """assert that the last call was made with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock. """ def assert_not_called(self) -> None: - """ - assert that the mock was never called. - """ + """assert that the mock was never called.""" def assert_called_once_with(self, *args: Any, **kwargs: Any) -> None: - """ - assert that the mock was called exactly once and that that call was + """assert that the mock was called exactly once and that that call was with the specified arguments. """ def _format_mock_failure_message(self, args: Any, kwargs: Any, action: str = "call") -> str: ... def assert_called(self) -> None: - """ - assert that the mock was called at least once - """ + """assert that the mock was called at least once""" def assert_called_once(self) -> None: - """ - assert that the mock was called only once. - """ + """assert that the mock was called only once.""" def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: - """ - Restore the mock object to its initial state. - """ + """Restore the mock object to its initial state.""" def _extract_mock_name(self) -> str: ... def _get_call_signature_from_name(self, name: str) -> Any: - """ - * If call objects are asserted against a method/function like obj.meth1 + """* If call objects are asserted against a method/function like obj.meth1 then there could be no name for the call object to lookup. Hence just return the spec_signature of the method/function being asserted against. * If the name is not empty then remove () and split by '.' to get @@ -230,8 +209,7 @@ class NonCallableMock(Base, Any): """ def assert_any_call(self, *args: Any, **kwargs: Any) -> None: - """ - assert the mock has been called with the specified arguments. + """assert the mock has been called with the specified arguments. The assert passes if the mock has *ever* been called, unlike `assert_called_with` and `assert_called_once_with` that only pass if @@ -239,8 +217,7 @@ class NonCallableMock(Base, Any): """ def assert_has_calls(self, calls: Sequence[_Call], any_order: bool = False) -> None: - """ - assert the mock has been called with the specified calls. + """assert the mock has been called with the specified calls. The `mock_calls` list is checked for the calls. If `any_order` is False (the default) then the calls must be @@ -252,8 +229,7 @@ class NonCallableMock(Base, Any): """ def mock_add_spec(self, spec: Any, spec_set: bool = False) -> None: - """ - Add a spec to a mock. `spec` can either be an object or a + """Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. @@ -262,15 +238,13 @@ class NonCallableMock(Base, Any): def _mock_add_spec(self, spec: Any, spec_set: bool, _spec_as_instance: bool = False, _eat_self: bool = False) -> None: ... def attach_mock(self, mock: NonCallableMock, attribute: str) -> None: - """ - Attach a mock as an attribute of this one, replacing its name and + """Attach a mock as an attribute of this one, replacing its name and parent. Calls to the attached mock will be recorded in the `method_calls` and `mock_calls` attributes of this one. """ def configure_mock(self, **kwargs: Any) -> None: - """ - Set attributes on the mock through keyword arguments. + """Set attributes on the mock through keyword arguments. Attributes plus return values and side effects can be set on child mocks using standard dot notation and unpacking a dictionary in the @@ -288,16 +262,14 @@ class NonCallableMock(Base, Any): mock_calls: _CallList def _format_mock_call_signature(self, args: Any, kwargs: Any) -> str: ... def _call_matcher(self, _call: tuple[_Call, ...]) -> _Call: - """ - Given a call (or simply an (args, kwargs) tuple), return a + """Given a call (or simply an (args, kwargs) tuple), return a comparison key suitable for matching with other calls. This is a best effort method which relies on the spec's signature, if available, or falls back on the arguments themselves. """ def _get_child_mock(self, **kw: Any) -> NonCallableMock: - """ - Create the child mocks for attributes and return value. + """Create the child mocks for attributes and return value. By default child mocks will be the same type as the parent. Subclasses of Mock may want to override this to customize the way child mocks are made. @@ -307,8 +279,7 @@ class NonCallableMock(Base, Any): """ if sys.version_info >= (3, 13): def _calls_repr(self) -> str: - """ - Renders self.mock_calls as a string. + """Renders self.mock_calls as a string. Example: " Calls: [call(1), call(2)]." @@ -318,8 +289,7 @@ class NonCallableMock(Base, Any): """ else: def _calls_repr(self, prefix: str = "Calls") -> str: - """ - Renders self.mock_calls as a string. + """Renders self.mock_calls as a string. Example: " Calls: [call(1), call(2)]." @@ -347,8 +317,7 @@ class CallableMixin(Base): def __call__(self, *args: Any, **kwargs: Any) -> Any: ... class Mock(CallableMixin, NonCallableMock): - """ - Create a new `Mock` object. `Mock` takes several optional arguments + """Create a new `Mock` object. `Mock` takes several optional arguments that specify the behaviour of the Mock object: * `spec`: This can be either a list of strings or an existing object (a @@ -466,26 +435,18 @@ class _patch(Generic[_T]): temp_original: Any is_local: bool def __enter__(self) -> _T: - """ - Perform the patch. - """ + """Perform the patch.""" def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / ) -> None: - """ - Undo the patch. - """ + """Undo the patch.""" def start(self) -> _T: - """ - Activate a patch, returning any created mock. - """ + """Activate a patch, returning any created mock.""" def stop(self) -> None: - """ - Stop an active patch. - """ + """Stop an active patch.""" # This class does not exist at runtime, it's a hack to make this work: # @patch("foo") @@ -499,8 +460,7 @@ class _patch_default_new(_patch[MagicMock | AsyncMock]): def __call__(self, func: Callable[..., _R]) -> Callable[..., _R]: ... class _patch_dict: - """ - Patch a dictionary, or dictionary like object, and restore the dictionary + """Patch a dictionary, or dictionary like object, and restore the dictionary to its original state after the test, where the restored dictionary is a copy of the dictionary as it was before the test. @@ -539,14 +499,10 @@ class _patch_dict: def decorate_class(self, klass: Any) -> Any: ... def __enter__(self) -> Any: - """ - Patch the dict. - """ + """Patch the dict.""" def __exit__(self, *args: object) -> Any: - """ - Unpatch the dict. - """ + """Unpatch the dict.""" start: Any stop: Any @@ -627,13 +583,10 @@ class MagicMixin(Base): def __init__(self, *args: Any, **kw: Any) -> None: ... class NonCallableMagicMock(MagicMixin, NonCallableMock): - """ - A version of `MagicMock` that isn't callable. - """ + """A version of `MagicMock` that isn't callable.""" class MagicMock(MagicMixin, Mock): - """ - MagicMock is a subclass of Mock with default implementations + """MagicMock is a subclass of Mock with default implementations of most of the magic methods. You can use MagicMock without having to configure the magic methods yourself. @@ -647,34 +600,24 @@ class AsyncMockMixin(Base): def __init__(self, *args: Any, **kwargs: Any) -> None: ... async def _execute_mock_call(self, *args: Any, **kwargs: Any) -> Any: ... def assert_awaited(self) -> None: - """ - Assert that the mock was awaited at least once. - """ + """Assert that the mock was awaited at least once.""" def assert_awaited_once(self) -> None: - """ - Assert that the mock was awaited exactly once. - """ + """Assert that the mock was awaited exactly once.""" def assert_awaited_with(self, *args: Any, **kwargs: Any) -> None: - """ - Assert that the last await was with the specified arguments. - """ + """Assert that the last await was with the specified arguments.""" def assert_awaited_once_with(self, *args: Any, **kwargs: Any) -> None: - """ - Assert that the mock was awaited exactly once and with the specified + """Assert that the mock was awaited exactly once and with the specified arguments. """ def assert_any_await(self, *args: Any, **kwargs: Any) -> None: - """ - Assert the mock has ever been awaited with the specified arguments. - """ + """Assert the mock has ever been awaited with the specified arguments.""" def assert_has_awaits(self, calls: Iterable[_Call], any_order: bool = False) -> None: - """ - Assert the mock has been awaited with the specified calls. + """Assert the mock has been awaited with the specified calls. The :attr:`await_args_list` list is checked for the awaits. If `any_order` is False (the default) then the awaits must be @@ -686,14 +629,10 @@ class AsyncMockMixin(Base): """ def assert_not_awaited(self) -> None: - """ - Assert that the mock was never awaited. - """ + """Assert that the mock was never awaited.""" def reset_mock(self, *args: Any, **kwargs: Any) -> None: - """ - See :func:`.Mock.reset_mock()` - """ + """See :func:`.Mock.reset_mock()`""" await_count: int await_args: _Call | None await_args_list: _CallList @@ -702,8 +641,7 @@ class AsyncMagicMixin(MagicMixin): def __init__(self, *args: Any, **kw: Any) -> None: ... class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): - """ - Enhance :class:`Mock` with features allowing to mock + """Enhance :class:`Mock` with features allowing to mock an async function. The :class:`AsyncMock` object will behave so the object is @@ -747,9 +685,7 @@ class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): # It is defined on `AsyncMockMixin` with `*args, **kwargs`, which is not ideal. # But, `NonCallableMock` super-class has the better version. def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: - """ - See :func:`.Mock.reset_mock()` - """ + """See :func:`.Mock.reset_mock()`""" class MagicProxy(Base): name: str @@ -759,9 +695,7 @@ class MagicProxy(Base): def __get__(self, obj: Any, _type: Any | None = None) -> Any: ... class _ANY: - """ - A helper object that compares equal to everything. - """ + """A helper object that compares equal to everything.""" def __eq__(self, other: object) -> Literal[True]: ... def __ne__(self, other: object) -> Literal[False]: ... @@ -780,8 +714,7 @@ if sys.version_info >= (3, 10): unsafe: bool = False, **kwargs: Any, ) -> Any: - """ - Create a mock object using another object as a spec. Attributes on the + """Create a mock object using another object as a spec. Attributes on the mock will use the corresponding attribute on the `spec` object as their spec. @@ -813,8 +746,7 @@ else: _name: Any | None = None, **kwargs: Any, ) -> Any: - """ - Create a mock object using another object as a spec. Attributes on the + """Create a mock object using another object as a spec. Attributes on the mock will use the corresponding attribute on the `spec` object as their spec. @@ -851,8 +783,7 @@ class _SpecState: ) -> None: ... def mock_open(mock: Any | None = None, read_data: Any = "") -> Any: - """ - A helper function to create a mock to replace the use of `open`. It works + """A helper function to create a mock to replace the use of `open`. It works for `open` called directly or used as a context manager. The `mock` argument is the mock object to configure. If `None` (the @@ -864,8 +795,7 @@ def mock_open(mock: Any | None = None, read_data: Any = "") -> Any: """ class PropertyMock(Mock): - """ - A mock intended to be used as a property, or other descriptor, on a class. + """A mock intended to be used as a property, or other descriptor, on a class. `PropertyMock` provides `__get__` and `__set__` methods so you can specify a return value when it is fetched. @@ -883,13 +813,10 @@ if sys.version_info >= (3, 13): def __init__(self, /, *args: Any, timeout: float | None | _SentinelObject = ..., **kwargs: Any) -> None: ... # Same as `NonCallableMock.reset_mock.` def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: - """ - See :func:`.Mock.reset_mock()` - """ + """See :func:`.Mock.reset_mock()`""" def wait_until_called(self, *, timeout: float | None | _SentinelObject = ...) -> None: - """ - Wait until the mock object is called. + """Wait until the mock object is called. `timeout` - time to wait for in seconds, waits forever otherwise. Defaults to the constructor provided timeout. @@ -897,15 +824,13 @@ if sys.version_info >= (3, 13): """ def wait_until_any_call_with(self, *args: Any, **kwargs: Any) -> None: - """ - Wait until the mock object is called with given args. + """Wait until the mock object is called with given args. Waits for the timeout in seconds provided in the constructor. """ class ThreadingMock(ThreadingMixin, MagicMixin, Mock): - """ - A mock that can be used to wait until on calls happening + """A mock that can be used to wait until on calls happening in a different thread. The constructor can take a `timeout` argument which @@ -918,8 +843,7 @@ if sys.version_info >= (3, 13): """ def seal(mock: Any) -> None: - """ - Disable the automatic generation of child mocks. + """Disable the automatic generation of child mocks. Given an input Mock, seals it to ensure no further mocks will be generated when accessing an attribute that was not already defined. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/result.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/result.pyi index 4303e63e47..72fb81d963 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/result.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/result.pyi @@ -19,8 +19,7 @@ STDERR_LINE: Final[str] def failfast(method: _F) -> _F: ... class TestResult: - """ - Holder for test result information. + """Holder for test result information. Test results are automatically managed by the TestCase and TestSuite classes, and do not need to be explicitly manipulated by writers of tests. @@ -46,86 +45,62 @@ class TestResult: def __init__(self, stream: TextIO | None = None, descriptions: bool | None = None, verbosity: int | None = None) -> None: ... def printErrors(self) -> None: - """ - Called by TestRunner after test run - """ + """Called by TestRunner after test run""" def wasSuccessful(self) -> bool: - """ - Tells whether or not this result was a success. - """ + """Tells whether or not this result was a success.""" def stop(self) -> None: - """ - Indicates that the tests should be aborted. - """ + """Indicates that the tests should be aborted.""" def startTest(self, test: unittest.case.TestCase) -> None: - """ - Called when the given test is about to be run - """ + """Called when the given test is about to be run""" def stopTest(self, test: unittest.case.TestCase) -> None: - """ - Called when the given test has been run - """ + """Called when the given test has been run""" def startTestRun(self) -> None: - """ - Called once before any tests are executed. + """Called once before any tests are executed. See startTest for a method called before each test. """ def stopTestRun(self) -> None: - """ - Called once after all tests are executed. + """Called once after all tests are executed. See stopTest for a method called after each test. """ def addError(self, test: unittest.case.TestCase, err: OptExcInfo) -> None: - """ - Called when an error has occurred. 'err' is a tuple of values as + """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). """ def addFailure(self, test: unittest.case.TestCase, err: OptExcInfo) -> None: - """ - Called when an error has occurred. 'err' is a tuple of values as + """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). """ def addSuccess(self, test: unittest.case.TestCase) -> None: - """ - Called when a test has completed successfully - """ + """Called when a test has completed successfully""" def addSkip(self, test: unittest.case.TestCase, reason: str) -> None: - """ - Called when a test is skipped. - """ + """Called when a test is skipped.""" def addExpectedFailure(self, test: unittest.case.TestCase, err: OptExcInfo) -> None: - """ - Called when an expected failure/error occurred. - """ + """Called when an expected failure/error occurred.""" def addUnexpectedSuccess(self, test: unittest.case.TestCase) -> None: - """ - Called when a test was expected to fail, but succeed. - """ + """Called when a test was expected to fail, but succeed.""" def addSubTest(self, test: unittest.case.TestCase, subtest: unittest.case.TestCase, err: OptExcInfo | None) -> None: - """ - Called at the end of a subtest. + """Called at the end of a subtest. 'err' is None if the subtest ended successfully, otherwise it's a tuple of values as returned by sys.exc_info(). """ if sys.version_info >= (3, 12): def addDuration(self, test: unittest.case.TestCase, elapsed: float) -> None: - """ - Called when a test finished to run, regardless of its outcome. + """Called when a test finished to run, regardless of its outcome. *test* is the test case corresponding to the test method. *elapsed* is the time represented in seconds, and it includes the execution of cleanup functions. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/runner.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/runner.pyi index 4c16b4557a..700629bec9 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/runner.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/runner.pyi @@ -24,9 +24,7 @@ class _TextTestStream(_SupportsWriteAndFlush, Protocol): # But that's not feasible to do Generically # We can expand the attributes if requested class _WritelnDecorator: - """ - Used to decorate file-like objects with a handy 'writeln' method - """ + """Used to decorate file-like objects with a handy 'writeln' method""" def __init__(self, stream: _SupportsWriteAndFlush) -> None: ... def writeln(self, arg: str | None = None) -> None: ... @@ -41,8 +39,7 @@ class _WritelnDecorator: _StreamT = TypeVar("_StreamT", bound=_TextTestStream, default=_WritelnDecorator) class TextTestResult(unittest.result.TestResult, Generic[_StreamT]): - """ - A test result class that can print formatted text results to a stream. + """A test result class that can print formatted text results to a stream. Used by TextTestRunner. """ @@ -56,14 +53,12 @@ class TextTestResult(unittest.result.TestResult, Generic[_StreamT]): if sys.version_info >= (3, 12): durations: int | None def __init__(self, stream: _StreamT, descriptions: bool, verbosity: int, *, durations: int | None = None) -> None: - """ - Construct a TextTestResult. Subclasses should accept **kwargs + """Construct a TextTestResult. Subclasses should accept **kwargs to ensure compatibility as the interface changes. """ else: def __init__(self, stream: _StreamT, descriptions: bool, verbosity: int) -> None: - """ - Construct a TextTestResult. Subclasses should accept **kwargs + """Construct a TextTestResult. Subclasses should accept **kwargs to ensure compatibility as the interface changes. """ @@ -71,8 +66,7 @@ class TextTestResult(unittest.result.TestResult, Generic[_StreamT]): def printErrorList(self, flavour: str, errors: Iterable[tuple[unittest.case.TestCase, str]]) -> None: ... class TextTestRunner: - """ - A test runner class that displays results in textual form. + """A test runner class that displays results in textual form. It prints out the names of tests as they are run, errors as they occur, and a summary of the results at the end of the test run. @@ -102,8 +96,7 @@ class TextTestRunner: tb_locals: bool = False, durations: int | None = None, ) -> None: - """ - Construct a TextTestRunner. + """Construct a TextTestRunner. Subclasses should accept **kwargs to ensure compatibility as the interface changes. @@ -121,8 +114,7 @@ class TextTestRunner: *, tb_locals: bool = False, ) -> None: - """ - Construct a TextTestRunner. + """Construct a TextTestRunner. Subclasses should accept **kwargs to ensure compatibility as the interface changes. @@ -130,6 +122,4 @@ class TextTestRunner: def _makeResult(self) -> TextTestResult: ... def run(self, test: unittest.suite.TestSuite | unittest.case.TestCase) -> TextTestResult: - """ - Run the given test case or test suite. - """ + """Run the given test case or test suite.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/suite.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/suite.pyi index c865c896c6..8bf449bda3 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/suite.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/suite.pyi @@ -11,9 +11,7 @@ from typing_extensions import TypeAlias _TestType: TypeAlias = unittest.case.TestCase | TestSuite class BaseTestSuite: - """ - A simple test suite that doesn't provide class or module shared fixtures. - """ + """A simple test suite that doesn't provide class or module shared fixtures.""" _tests: list[unittest.case.TestCase] _removed_tests: int @@ -23,9 +21,7 @@ class BaseTestSuite: def addTests(self, tests: Iterable[_TestType]) -> None: ... def run(self, result: unittest.result.TestResult) -> unittest.result.TestResult: ... def debug(self) -> None: - """ - Run the tests without collecting errors in a TestResult - """ + """Run the tests without collecting errors in a TestResult""" def countTestCases(self) -> int: ... def __iter__(self) -> Iterator[_TestType]: ... @@ -33,8 +29,7 @@ class BaseTestSuite: __hash__: ClassVar[None] # type: ignore[assignment] class TestSuite(BaseTestSuite): - """ - A test suite is a composite test consisting of a number of TestCases. + """A test suite is a composite test consisting of a number of TestCases. For use, create an instance of TestSuite, then add test case instances. When all tests have been added, the suite can be passed to a test diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/util.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/util.pyi index e9d368f770..d61b410187 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/unittest/util.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/unittest/util.pyi @@ -21,8 +21,7 @@ def _common_shorten_repr(*args: str) -> tuple[str, ...]: ... def safe_repr(obj: object, short: bool = False) -> str: ... def strclass(cls: type) -> str: ... def sorted_list_difference(expected: Sequence[_T], actual: Sequence[_T]) -> tuple[list[_T], list[_T]]: - """ - Finds elements in only one or the other of two, sorted input lists. + """Finds elements in only one or the other of two, sorted input lists. Returns a two-element tuple of lists. The first list contains those elements in the "expected" list but not in the "actual" list, and the @@ -31,8 +30,7 @@ def sorted_list_difference(expected: Sequence[_T], actual: Sequence[_T]) -> tupl """ def unorderable_list_difference(expected: MutableSequence[_T], actual: MutableSequence[_T]) -> tuple[list[_T], list[_T]]: - """ - Same behavior as sorted_list_difference but + """Same behavior as sorted_list_difference but for lists of unorderable items (like dicts). As it does a linear search per item (remove) it @@ -40,16 +38,10 @@ def unorderable_list_difference(expected: MutableSequence[_T], actual: MutableSe """ def three_way_cmp(x: Any, y: Any) -> int: - """ - Return -1 if x < y, 0 if x == y and 1 if x > y - """ + """Return -1 if x < y, 0 if x == y and 1 if x > y""" def _count_diff_all_purpose(actual: Sequence[_T], expected: Sequence[_T]) -> list[_Mismatch[_T]]: - """ - Returns list of (cnt_act, cnt_exp, elem) triples where the counts differ - """ + """Returns list of (cnt_act, cnt_exp, elem) triples where the counts differ""" def _count_diff_hashable(actual: Sequence[_T], expected: Sequence[_T]) -> list[_Mismatch[_T]]: - """ - Returns list of (cnt_act, cnt_exp, elem) triples where the counts differ - """ + """Returns list of (cnt_act, cnt_exp, elem) triples where the counts differ""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/urllib/error.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/urllib/error.pyi index a87a3b4019..abb3b5d4d1 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/urllib/error.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/urllib/error.pyi @@ -25,9 +25,7 @@ class URLError(OSError): def __init__(self, reason: str | BaseException, filename: str | None = None) -> None: ... class HTTPError(URLError, addinfourl): - """ - Raised when HTTP error occurs, but also acts like non-error return - """ + """Raised when HTTP error occurs, but also acts like non-error return""" @property def headers(self) -> Message: ... @@ -42,9 +40,7 @@ class HTTPError(URLError, addinfourl): def __init__(self, url: str, code: int, msg: str, hdrs: Message, fp: IO[bytes] | None) -> None: ... class ContentTooShortError(URLError): - """ - Exception raised when downloaded size does not match content-length. - """ + """Exception raised when downloaded size does not match content-length.""" content: tuple[str, Message] def __init__(self, message: str, content: tuple[str, Message]) -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/urllib/parse.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/urllib/parse.pyi index 435d518ecd..9a9c2cc613 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/urllib/parse.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/urllib/parse.pyi @@ -73,23 +73,17 @@ if sys.version_info < (3, 11): MAX_CACHE_SIZE: int class _ResultMixinStr: - """ - Standard approach to encoding parsed results from str to bytes - """ + """Standard approach to encoding parsed results from str to bytes""" def encode(self, encoding: str = "ascii", errors: str = "strict") -> _ResultMixinBytes: ... class _ResultMixinBytes: - """ - Standard approach to decoding parsed results from bytes to str - """ + """Standard approach to decoding parsed results from bytes to str""" def decode(self, encoding: str = "ascii", errors: str = "strict") -> _ResultMixinStr: ... class _NetlocResultMixinBase(Generic[AnyStr]): - """ - Shared methods for the parsed result objects containing a netloc element - """ + """Shared methods for the parsed result objects containing a netloc element""" @property def username(self) -> AnyStr | None: ... @@ -100,8 +94,7 @@ class _NetlocResultMixinBase(Generic[AnyStr]): @property def port(self) -> int | None: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - Represent a PEP 585 generic type + """Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). """ @@ -110,8 +103,7 @@ class _NetlocResultMixinStr(_NetlocResultMixinBase[str], _ResultMixinStr): ... class _NetlocResultMixinBytes(_NetlocResultMixinBase[bytes], _ResultMixinBytes): ... class _DefragResultBase(NamedTuple, Generic[AnyStr]): - """ - DefragResult(url, fragment) + """DefragResult(url, fragment) A 2-tuple that contains the url without fragment identifier and the fragment identifier as a separate argument. @@ -121,8 +113,7 @@ class _DefragResultBase(NamedTuple, Generic[AnyStr]): fragment: AnyStr class _SplitResultBase(NamedTuple, Generic[AnyStr]): - """ - SplitResult(scheme, netloc, path, query, fragment) + """SplitResult(scheme, netloc, path, query, fragment) A 5-tuple that contains the different components of a URL. Similar to ParseResult, but does not split params. @@ -135,8 +126,7 @@ class _SplitResultBase(NamedTuple, Generic[AnyStr]): fragment: AnyStr class _ParseResultBase(NamedTuple, Generic[AnyStr]): - """ - ParseResult(scheme, netloc, path, params, query, fragment) + """ParseResult(scheme, netloc, path, params, query, fragment) A 6-tuple that contains components of a parsed URL. """ @@ -177,8 +167,7 @@ def parse_qs( max_num_fields: int | None = None, separator: str = "&", ) -> dict[AnyStr, list[AnyStr]]: - """ - Parse a query given as a string argument. + """Parse a query given as a string argument. Arguments: @@ -216,8 +205,7 @@ def parse_qsl( max_num_fields: int | None = None, separator: str = "&", ) -> list[tuple[AnyStr, AnyStr]]: - """ - Parse a query given as a string argument. + """Parse a query given as a string argument. Arguments: @@ -247,8 +235,7 @@ def parse_qsl( @overload def quote(string: str, safe: str | Iterable[int] = "/", encoding: str | None = None, errors: str | None = None) -> str: - """ - quote('abc def') -> 'abc%20def' + """quote('abc def') -> 'abc%20def' Each part of a URL, e.g. the path info, the query, etc., has a different set of reserved characters that must be quoted. The @@ -290,16 +277,14 @@ def quote(string: str, safe: str | Iterable[int] = "/", encoding: str | None = N @overload def quote(string: bytes | bytearray, safe: str | Iterable[int] = "/") -> str: ... def quote_from_bytes(bs: bytes | bytearray, safe: str | Iterable[int] = "/") -> str: - """ - Like quote(), but accepts a bytes object rather than a str, and does + """Like quote(), but accepts a bytes object rather than a str, and does not perform string-to-bytes encoding. It always returns an ASCII string. quote_from_bytes(b'abc def?') -> 'abc%20def%3f' """ @overload def quote_plus(string: str, safe: str | Iterable[int] = "", encoding: str | None = None, errors: str | None = None) -> str: - """ - Like quote(), but also replace ' ' with '+', as required for quoting + """Like quote(), but also replace ' ' with '+', as required for quoting HTML form values. Plus signs in the original string are escaped unless they are included in safe. It also does not have safe default to '/'. """ @@ -307,8 +292,7 @@ def quote_plus(string: str, safe: str | Iterable[int] = "", encoding: str | None @overload def quote_plus(string: bytes | bytearray, safe: str | Iterable[int] = "") -> str: ... def unquote(string: str | bytes, encoding: str = "utf-8", errors: str = "replace") -> str: - """ - Replace %xx escapes by their single-character equivalent. The optional + """Replace %xx escapes by their single-character equivalent. The optional encoding and errors parameters specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. @@ -319,13 +303,10 @@ def unquote(string: str | bytes, encoding: str = "utf-8", errors: str = "replace """ def unquote_to_bytes(string: str | bytes | bytearray) -> bytes: - """ - unquote_to_bytes('abc%20def') -> b'abc def'. - """ + """unquote_to_bytes('abc%20def') -> b'abc def'.""" def unquote_plus(string: str, encoding: str = "utf-8", errors: str = "replace") -> str: - """ - Like unquote(), but also replace plus signs by spaces, as required for + """Like unquote(), but also replace plus signs by spaces, as required for unquoting HTML form values. unquote_plus('%7e/abc+def') -> '~/abc def' @@ -333,8 +314,7 @@ def unquote_plus(string: str, encoding: str = "utf-8", errors: str = "replace") @overload def urldefrag(url: str) -> DefragResult: - """ - Removes any existing fragment from URL. + """Removes any existing fragment from URL. Returns a tuple of the defragmented URL and the fragment. If the URL contained no fragments, the second element is the @@ -371,8 +351,7 @@ def urlencode( errors: str | None = None, quote_via: _QuoteVia = ..., ) -> str: - """ - Encode a dict or sequence of two-element tuples into a URL query string. + """Encode a dict or sequence of two-element tuples into a URL query string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. @@ -388,15 +367,13 @@ def urlencode( """ def urljoin(base: AnyStr, url: AnyStr | None, allow_fragments: bool = True) -> AnyStr: - """ - Join a base URL and a possibly relative URL to form an absolute + """Join a base URL and a possibly relative URL to form an absolute interpretation of the latter. """ @overload def urlparse(url: str, scheme: str = "", allow_fragments: bool = True) -> ParseResult: - """ - Parse a URL into 6 components: + """Parse a URL into 6 components: :///;?# The result is a named 6-tuple with fields corresponding to the @@ -422,8 +399,7 @@ def urlparse( ) -> ParseResultBytes: ... @overload def urlsplit(url: str, scheme: str = "", allow_fragments: bool = True) -> SplitResult: - """ - Parse a URL into 5 components: + """Parse a URL into 5 components: :///?# The result is a named 5-tuple with fields corresponding to the @@ -458,8 +434,7 @@ else: # Requires an iterable of length 6 @overload def urlunparse(components: Iterable[None]) -> Literal[b""]: # type: ignore[overload-overlap] - """ - Put a parsed URL back together again. This may result in a + """Put a parsed URL back together again. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had redundant delimiters, e.g. a ? with an empty query (the draft states that these are equivalent). @@ -471,8 +446,7 @@ def urlunparse(components: Iterable[AnyStr | None]) -> AnyStr: ... # Requires an iterable of length 5 @overload def urlunsplit(components: Iterable[None]) -> Literal[b""]: # type: ignore[overload-overlap] - """ - Combine the elements of a tuple as returned by urlsplit() into a + """Combine the elements of a tuple as returned by urlsplit() into a complete URL as a string. The data argument can be any five-item iterable. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had unnecessary delimiters (for example, a ? with an @@ -482,8 +456,7 @@ def urlunsplit(components: Iterable[None]) -> Literal[b""]: # type: ignore[over @overload def urlunsplit(components: Iterable[AnyStr | None]) -> AnyStr: ... def unwrap(url: str) -> str: - """ - Transform a string like '' into 'scheme://host/path'. + """Transform a string like '' into 'scheme://host/path'. The string is returned unchanged if it's not a wrapped URL. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/urllib/request.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/urllib/request.pyi index f1ee7b3948..b6bbdc4d8a 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/urllib/request.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/urllib/request.pyi @@ -126,8 +126,7 @@ if sys.version_info >= (3, 13): def urlopen( url: str | Request, data: _DataType | None = None, timeout: float | None = ..., *, context: ssl.SSLContext | None = None ) -> _UrlopenRet: - """ - Open the URL url, which can be either a string or a Request object. + """Open the URL url, which can be either a string or a Request object. *data* must be an object specifying additional data to be sent to the server, or None if no such data is needed. See Request for @@ -178,8 +177,7 @@ else: cadefault: bool = False, context: ssl.SSLContext | None = None, ) -> _UrlopenRet: - """ - Open the URL url, which can be either a string or a Request object. + """Open the URL url, which can be either a string or a Request object. *data* must be an object specifying additional data to be sent to the server, or None if no such data is needed. See Request for @@ -230,8 +228,7 @@ else: def install_opener(opener: OpenerDirector) -> None: ... def build_opener(*handlers: BaseHandler | Callable[[], BaseHandler]) -> OpenerDirector: - """ - Create an opener object from a list of handlers. + """Create an opener object from a list of handlers. The opener will use several default handlers, including support for HTTP, FTP and when applicable HTTPS. @@ -242,8 +239,7 @@ def build_opener(*handlers: BaseHandler | Callable[[], BaseHandler]) -> OpenerDi if sys.version_info >= (3, 14): def url2pathname(url: str, *, require_scheme: bool = False, resolve_host: bool = False) -> str: - """ - Convert the given file URL to a local file system path. + """Convert the given file URL to a local file system path. The 'file:' scheme prefix must be omitted unless *require_scheme* is set to true. @@ -253,8 +249,7 @@ if sys.version_info >= (3, 14): """ def pathname2url(pathname: str, *, add_scheme: bool = False) -> str: - """ - Convert the given local file system path to a file URL. + """Convert the given local file system path to a file URL. The 'file:' scheme prefix is omitted unless *add_scheme* is set to true. @@ -265,36 +260,31 @@ else: from nturl2path import pathname2url as pathname2url, url2pathname as url2pathname else: def url2pathname(pathname: str) -> str: - """ - OS-specific conversion from a relative URL of the 'file' scheme + """OS-specific conversion from a relative URL of the 'file' scheme to a file system path; not recommended for general use. """ def pathname2url(pathname: str) -> str: - """ - OS-specific conversion from a file system path to a relative URL + """OS-specific conversion from a file system path to a relative URL of the 'file' scheme; not recommended for general use. """ def getproxies() -> dict[str, str]: - """ - Return a dictionary of scheme -> proxy server URL mappings. + """Return a dictionary of scheme -> proxy server URL mappings. Scan the environment for variables named _proxy; this seems to be the standard convention. """ def getproxies_environment() -> dict[str, str]: - """ - Return a dictionary of scheme -> proxy server URL mappings. + """Return a dictionary of scheme -> proxy server URL mappings. Scan the environment for variables named _proxy; this seems to be the standard convention. """ def parse_http_list(s: str) -> list[str]: - """ - Parse lists as described by RFC 2068 Section 2. + """Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could @@ -304,17 +294,19 @@ def parse_http_list(s: str) -> list[str]: """ def parse_keqv_list(l: list[str]) -> dict[str, str]: - """ - Parse list of key=value strings where keys are not duplicated. - """ + """Parse list of key=value strings where keys are not duplicated.""" if sys.platform == "win32" or sys.platform == "darwin": - def proxy_bypass(host: str) -> Any: ... # undocumented + def proxy_bypass(host: str) -> Any: # undocumented + """Return True, if host should be bypassed. + + Checks proxy settings gathered from the environment, if specified, + or the registry. + """ else: def proxy_bypass(host: str, proxies: Mapping[str, str] | None = None) -> Any: # undocumented - """ - Test if proxies should not be used for a particular host. + """Test if proxies should not be used for a particular host. Checks the proxy dict for the value of no_proxy, which should be a list of comma separated DNS suffixes, or '*' for all hosts. @@ -347,9 +339,7 @@ class Request: method: str | None = None, ) -> None: ... def get_method(self) -> str: - """ - Return a string indicating the HTTP request method. - """ + """Return a string indicating the HTTP request method.""" def add_header(self, key: str, val: str) -> None: ... def add_unredirected_header(self, key: str, val: str) -> None: ... @@ -390,8 +380,7 @@ class HTTPRedirectHandler(BaseHandler): def redirect_request( self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage, newurl: str ) -> Request | None: - """ - Return a Request or None in response to a redirect. + """Return a Request or None in response to a redirect. This is called by the http_error_30x methods when a redirection response is received. If a redirection should @@ -427,16 +416,13 @@ class HTTPPasswordMgr: def add_password(self, realm: str, uri: str | Sequence[str], user: str, passwd: str) -> None: ... def find_user_password(self, realm: str, authuri: str) -> tuple[str | None, str | None]: ... def is_suburi(self, base: str, test: str) -> bool: # undocumented - """ - Check if test is below base in a URI tree + """Check if test is below base in a URI tree Both args must be URIs in reduced form. """ def reduce_uri(self, uri: str, default_port: bool = True) -> tuple[str, str]: # undocumented - """ - Accept authority or URI and extract only the authority and path. - """ + """Accept authority or URI and extract only the authority and path.""" class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr): def add_password(self, realm: str | None, uri: str | Sequence[str], user: str, passwd: str) -> None: ... @@ -480,8 +466,7 @@ class AbstractDigestAuthHandler: def get_entity_digest(self, data: ReadableBuffer | None, chal: Mapping[str, str]) -> str | None: ... class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): - """ - An authentication protocol defined by RFC 2069 + """An authentication protocol defined by RFC 2069 Digest authentication improves on basic authentication because it does not transmit passwords in the clear. @@ -515,8 +500,7 @@ class AbstractHTTPHandler(BaseHandler): # undocumented def set_http_debuglevel(self, level: int) -> None: ... def do_request_(self, request: Request) -> Request: ... def do_open(self, http_class: _HTTPConnectionProtocol, req: Request, **http_conn_args: Any) -> HTTPResponse: - """ - Return an HTTPResponse object for the request, using http_class. + """Return an HTTPResponse object for the request, using http_class. http_class must implement the HTTPConnection API from http.client. """ @@ -548,9 +532,7 @@ class DataHandler(BaseHandler): def data_open(self, req: Request) -> addinfourl: ... class ftpwrapper: # undocumented - """ - Class used by open_ftp() for cache of open FTP connections. - """ + """Class used by open_ftp() for cache of open FTP connections.""" def __init__( self, user: str, passwd: str, host: str, port: int, dirs: str, timeout: float | None = None, persistent: bool = True @@ -578,9 +560,7 @@ class UnknownHandler(BaseHandler): def unknown_open(self, req: Request) -> NoReturn: ... class HTTPErrorProcessor(BaseHandler): - """ - Process HTTP error responses. - """ + """Process HTTP error responses.""" def http_response(self, request: Request, response: HTTPResponse) -> _UrlopenRet: ... def https_response(self, request: Request, response: HTTPResponse) -> _UrlopenRet: ... @@ -591,8 +571,7 @@ def urlretrieve( reporthook: Callable[[int, int, int], object] | None = None, data: _DataType = None, ) -> tuple[str, HTTPMessage]: - """ - Retrieve a URL into a temporary location on disk. + """Retrieve a URL into a temporary location on disk. Requires a URL argument. If a filename is passed, it is used as the temporary file location. The reporthook argument should be @@ -608,15 +587,12 @@ def urlretrieve( """ def urlcleanup() -> None: - """ - Clean up temporary files from urlretrieve calls. - """ + """Clean up temporary files from urlretrieve calls.""" if sys.version_info < (3, 14): @deprecated("Deprecated since Python 3.3; Removed in 3.14; Use newer urlopen functions and methods.") class URLopener: - """ - Class to open URLs. + """Class to open URLs. This is a class rather than just a subroutine because we may need more than one set of global protocol-specific options. Note -- this is a base class for those who don't want the @@ -627,14 +603,10 @@ if sys.version_info < (3, 14): version: ClassVar[str] def __init__(self, proxies: dict[str, str] | None = None, **x509: str) -> None: ... def open(self, fullurl: str, data: ReadableBuffer | None = None) -> _UrlopenRet: - """ - Use URLopener().open(file) instead of open(file, 'r'). - """ + """Use URLopener().open(file) instead of open(file, 'r').""" def open_unknown(self, fullurl: str, data: ReadableBuffer | None = None) -> _UrlopenRet: - """ - Overridable interface to open unknown URL type. - """ + """Overridable interface to open unknown URL type.""" def retrieve( self, @@ -643,14 +615,12 @@ if sys.version_info < (3, 14): reporthook: Callable[[int, int, int], object] | None = None, data: ReadableBuffer | None = None, ) -> tuple[str, Message | None]: - """ - retrieve(url) returns (filename, headers) for a local object + """retrieve(url) returns (filename, headers) for a local object or (tempfilename, headers) for a remote object. """ def addheader(self, *args: tuple[str, str]) -> None: # undocumented - """ - Add a header to be used by the HTTP interface only + """Add a header to be used by the HTTP interface only e.g. u.addheader('Accept', 'sound/basic') """ @@ -659,8 +629,7 @@ if sys.version_info < (3, 14): def http_error( self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: bytes | None = None ) -> _UrlopenRet: # undocumented - """ - Handle http errors. + """Handle http errors. Derived class can override this, or provide specific handlers named http_error_DDD where DDD is the 3-digit error code. @@ -669,93 +638,63 @@ if sys.version_info < (3, 14): def http_error_default( self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage ) -> _UrlopenRet: # undocumented - """ - Default error handler: close the connection and raise OSError. - """ + """Default error handler: close the connection and raise OSError.""" def open_data(self, url: str, data: ReadableBuffer | None = None) -> addinfourl: # undocumented - """ - Use "data" URL. - """ + """Use "data" URL.""" def open_file(self, url: str) -> addinfourl: # undocumented - """ - Use local file or FTP depending on form of URL. - """ + """Use local file or FTP depending on form of URL.""" def open_ftp(self, url: str) -> addinfourl: # undocumented - """ - Use FTP protocol. - """ + """Use FTP protocol.""" def open_http(self, url: str, data: ReadableBuffer | None = None) -> _UrlopenRet: # undocumented - """ - Use HTTP protocol. - """ + """Use HTTP protocol.""" def open_https(self, url: str, data: ReadableBuffer | None = None) -> _UrlopenRet: # undocumented - """ - Use HTTPS protocol. - """ + """Use HTTPS protocol.""" def open_local_file(self, url: str) -> addinfourl: # undocumented - """ - Use local file. - """ + """Use local file.""" def open_unknown_proxy(self, proxy: str, fullurl: str, data: ReadableBuffer | None = None) -> None: # undocumented - """ - Overridable interface to open unknown URL type. - """ + """Overridable interface to open unknown URL type.""" def __del__(self) -> None: ... @deprecated("Deprecated since Python 3.3; Removed in 3.14; Use newer urlopen functions and methods.") class FancyURLopener(URLopener): - """ - Derived class with handlers for errors we can handle (perhaps). - """ + """Derived class with handlers for errors we can handle (perhaps).""" def prompt_user_passwd(self, host: str, realm: str) -> tuple[str, str]: - """ - Override this in a GUI environment! - """ + """Override this in a GUI environment!""" def get_user_passwd(self, host: str, realm: str, clear_cache: int = 0) -> tuple[str, str]: ... # undocumented def http_error_301( self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None ) -> _UrlopenRet | addinfourl | None: # undocumented - """ - Error 301 -- also relocated (permanently). - """ + """Error 301 -- also relocated (permanently).""" def http_error_302( self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None ) -> _UrlopenRet | addinfourl | None: # undocumented - """ - Error 302 -- relocated (temporarily). - """ + """Error 302 -- relocated (temporarily).""" def http_error_303( self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None ) -> _UrlopenRet | addinfourl | None: # undocumented - """ - Error 303 -- also relocated (essentially identical to 302). - """ + """Error 303 -- also relocated (essentially identical to 302).""" def http_error_307( self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None ) -> _UrlopenRet | addinfourl | None: # undocumented - """ - Error 307 -- relocated, but turn POST into error. - """ + """Error 307 -- relocated, but turn POST into error.""" if sys.version_info >= (3, 11): def http_error_308( self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None ) -> _UrlopenRet | addinfourl | None: # undocumented - """ - Error 308 -- relocated, but turn POST into error. - """ + """Error 308 -- relocated, but turn POST into error.""" def http_error_401( self, @@ -767,8 +706,7 @@ if sys.version_info < (3, 14): data: ReadableBuffer | None = None, retry: bool = False, ) -> _UrlopenRet | None: # undocumented - """ - Error 401 -- authentication required. + """Error 401 -- authentication required. This function supports Basic authentication only. """ @@ -782,17 +720,14 @@ if sys.version_info < (3, 14): data: ReadableBuffer | None = None, retry: bool = False, ) -> _UrlopenRet | None: # undocumented - """ - Error 407 -- proxy authentication required. + """Error 407 -- proxy authentication required. This function supports Basic authentication only. """ def http_error_default( self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage ) -> addinfourl: # undocumented - """ - Default error handling -- don't raise an exception. - """ + """Default error handling -- don't raise an exception.""" def redirect_internal( self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/urllib/response.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/urllib/response.pyi index 1704488841..9e5bace7a9 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/urllib/response.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/urllib/response.pyi @@ -17,9 +17,7 @@ from typing import IO, Any __all__ = ["addbase", "addclosehook", "addinfo", "addinfourl"] class addbase(tempfile._TemporaryFileWrapper[bytes]): - """ - Base class for addinfo and addclosehook. Is a good idea for garbage collection. - """ + """Base class for addinfo and addclosehook. Is a good idea for garbage collection.""" fp: IO[bytes] def __init__(self, fp: IO[bytes]) -> None: ... @@ -34,27 +32,21 @@ class addbase(tempfile._TemporaryFileWrapper[bytes]): def writelines(self, lines: Iterable[ReadableBuffer]) -> None: ... class addclosehook(addbase): - """ - Class to add a close hook to an open file. - """ + """Class to add a close hook to an open file.""" closehook: Callable[..., object] hookargs: tuple[Any, ...] def __init__(self, fp: IO[bytes], closehook: Callable[..., object], *hookargs: Any) -> None: ... class addinfo(addbase): - """ - class to add an info() method to an open file. - """ + """class to add an info() method to an open file.""" headers: Message def __init__(self, fp: IO[bytes], headers: Message) -> None: ... def info(self) -> Message: ... class addinfourl(addinfo): - """ - class to add info() and geturl() methods to an open file. - """ + """class to add info() and geturl() methods to an open file.""" url: str code: int | None diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/urllib/robotparser.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/urllib/robotparser.pyi index 25443cff64..8a64bd78cc 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/urllib/robotparser.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/urllib/robotparser.pyi @@ -17,54 +17,42 @@ from typing import NamedTuple __all__ = ["RobotFileParser"] class RequestRate(NamedTuple): - """ - RequestRate(requests, seconds) - """ + """RequestRate(requests, seconds)""" requests: int seconds: int class RobotFileParser: - """ - This class provides a set of methods to read, parse and answer + """This class provides a set of methods to read, parse and answer questions about a single robots.txt file. """ def __init__(self, url: str = "") -> None: ... def set_url(self, url: str) -> None: - """ - Sets the URL referring to a robots.txt file. - """ + """Sets the URL referring to a robots.txt file.""" def read(self) -> None: - """ - Reads the robots.txt URL and feeds it to the parser. - """ + """Reads the robots.txt URL and feeds it to the parser.""" def parse(self, lines: Iterable[str]) -> None: - """ - Parse the input lines from a robots.txt file. + """Parse the input lines from a robots.txt file. We allow that a user-agent: line is not preceded by one or more blank lines. """ def can_fetch(self, useragent: str, url: str) -> bool: - """ - using the parsed robots.txt decide if useragent can fetch url - """ + """using the parsed robots.txt decide if useragent can fetch url""" def mtime(self) -> int: - """ - Returns the time the robots.txt file was last fetched. + """Returns the time the robots.txt file was last fetched. This is useful for long-running web spiders that need to check for new robots.txt files periodically. """ def modified(self) -> None: - """ - Sets the time the robots.txt file was last fetched to the + """Sets the time the robots.txt file was last fetched to the current time. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/uu.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/uu.pyi index a4ecfeb9d2..5484712ab5 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/uu.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/uu.pyi @@ -15,11 +15,7 @@ _File: TypeAlias = str | BinaryIO class Error(Exception): ... def encode(in_file: _File, out_file: _File, name: str | None = None, mode: int | None = None, *, backtick: bool = False) -> None: - """ - Uuencode file - """ + """Uuencode file""" def decode(in_file: _File, out_file: _File | None = None, mode: int | None = None, quiet: bool = False) -> None: - """ - Decode uuencoded file - """ + """Decode uuencoded file""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/uuid.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/uuid.pyi index 1e7795ac4e..2f58bfc1a2 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/uuid.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/uuid.pyi @@ -66,17 +66,14 @@ from typing_extensions import LiteralString, TypeAlias _FieldsType: TypeAlias = tuple[int, int, int, int, int, int] class SafeUUID(Enum): - """ - An enumeration. - """ + """An enumeration.""" safe = 0 unsafe = -1 unknown = None class UUID: - """ - Instances of the UUID class represent UUIDs as specified in RFC 4122. + """Instances of the UUID class represent UUIDs as specified in RFC 4122. UUID objects are immutable, hashable, and usable as dictionary keys. Converting a UUID to a string with str() yields something in the form '12345678-1234-1234-1234-123456789abc'. The UUID constructor accepts @@ -148,8 +145,7 @@ class UUID: *, is_safe: SafeUUID = ..., ) -> None: - """ - Create a UUID from either a string of 32 hexadecimal digits, + """Create a UUID from either a string of 32 hexadecimal digits, a string of 16 bytes as the 'bytes' argument, a string of 16 bytes in little-endian order as the 'bytes_le' argument, a tuple of six integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, @@ -221,8 +217,7 @@ class UUID: def __hash__(self) -> builtins.int: ... def getnode() -> int: - """ - Get the hardware address as a 48-bit positive integer. + """Get the hardware address as a 48-bit positive integer. The first time this runs, it may launch a separate program, which could be quite slow. If all attempts to obtain the hardware address fail, we @@ -231,8 +226,7 @@ def getnode() -> int: """ def uuid1(node: int | None = None, clock_seq: int | None = None) -> UUID: - """ - Generate a UUID from a host ID, sequence number, and the current time. + """Generate a UUID from a host ID, sequence number, and the current time. If 'node' is not given, getnode() is used to obtain the hardware address. If 'clock_seq' is given, it is used as the sequence number; otherwise a random 14-bit sequence number is chosen. @@ -240,8 +234,7 @@ def uuid1(node: int | None = None, clock_seq: int | None = None) -> UUID: if sys.version_info >= (3, 14): def uuid6(node: int | None = None, clock_seq: int | None = None) -> UUID: - """ - Similar to :func:`uuid1` but where fields are ordered differently + """Similar to :func:`uuid1` but where fields are ordered differently for improved DB locality. More precisely, given a 60-bit timestamp value as specified for UUIDv1, @@ -251,15 +244,13 @@ if sys.version_info >= (3, 14): """ def uuid7() -> UUID: - """ - Generate a UUID from a Unix timestamp in milliseconds and random bits. + """Generate a UUID from a Unix timestamp in milliseconds and random bits. UUIDv7 objects feature monotonicity within a millisecond. """ def uuid8(a: int | None = None, b: int | None = None, c: int | None = None) -> UUID: - """ - Generate a UUID from three custom blocks. + """Generate a UUID from three custom blocks. * 'a' is the first 48-bit chunk of the UUID (octets 0-5); * 'b' is the mid 12-bit chunk (octets 6-7); @@ -270,32 +261,22 @@ if sys.version_info >= (3, 14): if sys.version_info >= (3, 12): def uuid3(namespace: UUID, name: str | bytes) -> UUID: - """ - Generate a UUID from the MD5 hash of a namespace UUID and a name. - """ + """Generate a UUID from the MD5 hash of a namespace UUID and a name.""" else: def uuid3(namespace: UUID, name: str) -> UUID: - """ - Generate a UUID from the MD5 hash of a namespace UUID and a name. - """ + """Generate a UUID from the MD5 hash of a namespace UUID and a name.""" def uuid4() -> UUID: - """ - Generate a random UUID. - """ + """Generate a random UUID.""" if sys.version_info >= (3, 12): def uuid5(namespace: UUID, name: str | bytes) -> UUID: - """ - Generate a UUID from the SHA-1 hash of a namespace UUID and a name. - """ + """Generate a UUID from the SHA-1 hash of a namespace UUID and a name.""" else: def uuid5(namespace: UUID, name: str) -> UUID: - """ - Generate a UUID from the SHA-1 hash of a namespace UUID and a name. - """ + """Generate a UUID from the SHA-1 hash of a namespace UUID and a name.""" if sys.version_info >= (3, 14): NIL: Final[UUID] @@ -312,6 +293,4 @@ RESERVED_FUTURE: Final[LiteralString] if sys.version_info >= (3, 12): def main() -> None: - """ - Run the uuid command line interface. - """ + """Run the uuid command line interface.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/venv/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/venv/__init__.pyi index bfc3e45299..5ee02fa498 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/venv/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/venv/__init__.pyi @@ -1,4 +1,5 @@ """ + Virtual environment (venv) package for Python. Based on PEP 405. Copyright (C) 2011-2014 Vinay Sajip. @@ -16,8 +17,7 @@ logger: logging.Logger CORE_VENV_DEPS: tuple[str, ...] class EnvBuilder: - """ - This class exists to allow virtual environment creation to be + """This class exists to allow virtual environment creation to be customized. The constructor parameters determine the builder's behaviour when called upon to create a virtual environment. @@ -42,7 +42,6 @@ class EnvBuilder: :param scm_ignore_files: Create ignore files for the SCMs specified by the iterable. """ - system_site_packages: bool clear: bool symlinks: bool @@ -76,56 +75,43 @@ class EnvBuilder: ) -> None: ... def create(self, env_dir: StrOrBytesPath) -> None: - """ - Create a virtual environment in a directory. + """Create a virtual environment in a directory. :param env_dir: The target directory to create an environment in. """ - def clear_directory(self, path: StrOrBytesPath) -> None: ... # undocumented def ensure_directories(self, env_dir: StrOrBytesPath) -> SimpleNamespace: - """ - Create the directories for the environment. + """Create the directories for the environment. Returns a context object which holds paths in the environment, for use by subsequent logic. """ - def create_configuration(self, context: SimpleNamespace) -> None: - """ - Create a configuration file indicating where the environment's Python + """Create a configuration file indicating where the environment's Python was copied from, and whether the system site-packages should be made available in the environment. :param context: The information for the environment creation request being processed. """ - def symlink_or_copy( self, src: StrOrBytesPath, dst: StrOrBytesPath, relative_symlinks_ok: bool = False ) -> None: # undocumented - """ - Try symlinking a file, and if that fails, fall back to copying. + """Try symlinking a file, and if that fails, fall back to copying. (Unused on Windows, because we can't just copy a failed symlink file: we switch to a different set of files instead.) """ - def setup_python(self, context: SimpleNamespace) -> None: - """ - Set up a Python executable in the environment. + """Set up a Python executable in the environment. :param context: The information for the environment creation request being processed. """ - def _setup_pip(self, context: SimpleNamespace) -> None: # undocumented + """Installs or upgrades pip in a virtual environment """ - Installs or upgrades pip in a virtual environment - """ - def setup_scripts(self, context: SimpleNamespace) -> None: - """ - Set up scripts into the created environment from a directory. + """Set up scripts into the created environment from a directory. This method installs the default scripts into the environment being created. You can prevent the default installation by overriding @@ -134,19 +120,15 @@ class EnvBuilder: 'scripts' directory in the venv package is used as the source of scripts to install. """ - def post_setup(self, context: SimpleNamespace) -> None: - """ - Hook for post-setup modification of the venv. Subclasses may install + """Hook for post-setup modification of the venv. Subclasses may install additional packages or scripts here, add activation shell scripts, etc. :param context: The information for the environment creation request being processed. """ - def replace_variables(self, text: str, context: SimpleNamespace) -> str: # undocumented - """ - Replace variable placeholders in script text with context-specific + """Replace variable placeholders in script text with context-specific variables. Return the text passed in , but with variables replaced. @@ -155,10 +137,8 @@ class EnvBuilder: :param context: The information for the environment creation request being processed. """ - def install_scripts(self, context: SimpleNamespace, path: str) -> None: - """ - Install scripts into the created environment from a directory. + """Install scripts into the created environment from a directory. :param context: The information for the environment creation request being processed. @@ -169,12 +149,10 @@ class EnvBuilder: Placeholder variables are replaced with environment- specific values. """ - def upgrade_dependencies(self, context: SimpleNamespace) -> None: ... if sys.version_info >= (3, 13): def create_git_ignore_file(self, context: SimpleNamespace) -> None: - """ - Create a .gitignore file in the environment directory. + """Create a .gitignore file in the environment directory. The contents of the file cause the entire environment directory to be ignored by git. @@ -192,8 +170,7 @@ if sys.version_info >= (3, 13): *, scm_ignore_files: Iterable[str] = ..., ) -> None: - """ - Create a virtual environment in a directory. + """Create a virtual environment in a directory. """ else: @@ -206,8 +183,7 @@ else: prompt: str | None = None, upgrade_deps: bool = False, ) -> None: - """ - Create a virtual environment in a directory. + """Create a virtual environment in a directory. """ def main(args: Sequence[str] | None = None) -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/warnings.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/warnings.pyi index 370ee85cbe..1f0a32e880 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/warnings.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/warnings.pyi @@ -41,20 +41,15 @@ def showwarning( file: TextIO | None = None, line: str | None = None, ) -> None: - """ - Hook to write a warning to a file; replace if you like. - """ + """Hook to write a warning to a file; replace if you like.""" def formatwarning(message: Warning | str, category: type[Warning], filename: str, lineno: int, line: str | None = None) -> str: - """ - Function to format a warning the standard way. - """ + """Function to format a warning the standard way.""" def filterwarnings( action: _ActionKind, message: str = "", category: type[Warning] = ..., module: str = "", lineno: int = 0, append: bool = False ) -> None: - """ - Insert an entry into the list of warnings filters (at the front). + """Insert an entry into the list of warnings filters (at the front). 'action' -- one of "error", "ignore", "always", "all", "default", "module", or "once" @@ -66,8 +61,7 @@ def filterwarnings( """ def simplefilter(action: _ActionKind, category: type[Warning] = ..., lineno: int = 0, append: bool = False) -> None: - """ - Insert a simple entry into the list of warnings filters (at the front). + """Insert a simple entry into the list of warnings filters (at the front). A simple filter matches all modules and messages. 'action' -- one of "error", "ignore", "always", "all", "default", "module", @@ -78,14 +72,10 @@ def simplefilter(action: _ActionKind, category: type[Warning] = ..., lineno: int """ def resetwarnings() -> None: - """ - Clear the list of warning filters, so that no filters are active. - """ + """Clear the list of warning filters, so that no filters are active.""" class _OptionError(Exception): - """ - Exception used by option processing helpers. - """ + """Exception used by option processing helpers.""" class WarningMessage: message: Warning | str @@ -107,8 +97,7 @@ class WarningMessage: ) -> None: ... class catch_warnings(Generic[_W_co]): - """ - A context manager that copies and restores the warnings filter upon + """A context manager that copies and restores the warnings filter upon exiting the context. The 'record' argument specifies whether warnings should be captured by a @@ -138,8 +127,7 @@ class catch_warnings(Generic[_W_co]): lineno: int = 0, append: bool = False, ) -> None: - """ - Specify whether to record warnings and if an alternative module + """Specify whether to record warnings and if an alternative module should be used other than sys.modules['warnings']. """ @@ -168,8 +156,7 @@ class catch_warnings(Generic[_W_co]): else: @overload def __init__(self: catch_warnings[None], *, record: Literal[False] = False, module: ModuleType | None = None) -> None: - """ - Specify whether to record warnings and if an alternative module + """Specify whether to record warnings and if an alternative module should be used other than sys.modules['warnings']. """ @@ -187,8 +174,7 @@ class catch_warnings(Generic[_W_co]): if sys.version_info >= (3, 13): class deprecated: - """ - Indicate that a class, function or overload is deprecated. + """Indicate that a class, function or overload is deprecated. When this decorator is applied to an object, the type checker will generate a diagnostic on usage of the deprecated object. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/wave.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/wave.pyi index d1bb8bc86c..5ba98cf5a4 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/wave.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/wave.pyi @@ -85,9 +85,7 @@ class Error(Exception): ... WAVE_FORMAT_PCM: Final = 1 class _wave_params(NamedTuple): - """ - _wave_params(nchannels, sampwidth, framerate, nframes, comptype, compname) - """ + """_wave_params(nchannels, sampwidth, framerate, nframes, comptype, compname)""" nchannels: int sampwidth: int @@ -97,8 +95,7 @@ class _wave_params(NamedTuple): compname: str class Wave_read: - """ - Variables used in this class: + """Variables used in this class: These variables are available to the user though appropriate methods of this class: @@ -151,8 +148,7 @@ class Wave_read: def readframes(self, nframes: int) -> bytes: ... class Wave_write: - """ - Variables used in this class: + """Variables used in this class: These variables are user settable through appropriate methods of this class: diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/weakref.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/weakref.pyi index a4a52d3673..0aedfdef6a 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/weakref.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/weakref.pyi @@ -64,24 +64,19 @@ class ReferenceType(Generic[_T]): # "weakref" __callback__: Callable[[Self], Any] def __new__(cls, o: _T, callback: Callable[[Self], Any] | None = ..., /) -> Self: ... def __call__(self) -> _T | None: - """ - Call self as a function. - """ + """Call self as a function.""" def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: - """ - See PEP 585 - """ + """See PEP 585""" ref = ReferenceType # everything below here is implemented in weakref.py class WeakMethod(ref[_CallableT]): - """ - A custom `weakref.ref` subclass which simulates a weak reference to + """A custom `weakref.ref` subclass which simulates a weak reference to a bound method, working around the lifetime problem of bound methods. """ @@ -92,8 +87,7 @@ class WeakMethod(ref[_CallableT]): def __hash__(self) -> int: ... class WeakValueDictionary(MutableMapping[_KT, _VT]): - """ - Mapping class that references values weakly. + """Mapping class that references values weakly. Entries in the dictionary will be discarded when no strong reference to the value exists anymore @@ -134,8 +128,7 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): def values(self) -> Iterator[_VT]: ... # type: ignore[override] def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore[override] def itervaluerefs(self) -> Iterator[KeyedRef[_KT, _VT]]: - """ - Return an iterator that yields the weak references to the values. + """Return an iterator that yields the weak references to the values. The references are not guaranteed to be 'live' at the time they are used, so the result of calling the references needs @@ -145,8 +138,7 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): """ def valuerefs(self) -> list[KeyedRef[_KT, _VT]]: - """ - Return a list of weak references to the values. + """Return a list of weak references to the values. The references are not guaranteed to be 'live' at the time they are used, so the result of calling the references needs @@ -177,8 +169,7 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... class KeyedRef(ref[_T], Generic[_KT, _T]): - """ - Specialized reference that includes a key corresponding to the value. + """Specialized reference that includes a key corresponding to the value. This is used in the WeakValueDictionary to avoid having to create a function object for each key stored in the mapping. A shared @@ -191,8 +182,7 @@ class KeyedRef(ref[_T], Generic[_KT, _T]): def __init__(self, ob: _T, callback: Callable[[Self], Any], key: _KT) -> None: ... class WeakKeyDictionary(MutableMapping[_KT, _VT]): - """ - Mapping class that references keys weakly. + """Mapping class that references keys weakly. Entries in the dictionary will be discarded when there is no longer a strong reference to the key. This can be used to @@ -226,8 +216,7 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): def values(self) -> Iterator[_VT]: ... # type: ignore[override] def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore[override] def keyrefs(self) -> list[ref[_KT]]: - """ - Return a list of weak references to the keys. + """Return a list of weak references to the keys. The references are not guaranteed to be 'live' at the time they are used, so the result of calling the references needs @@ -261,8 +250,7 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... class finalize(Generic[_P, _T]): - """ - Class for finalization of weakrefable objects + """Class for finalization of weakrefable objects finalize(obj, func, *args, **kwargs) returns a callable finalizer object which will be called when obj is garbage collected. The @@ -277,26 +265,21 @@ class finalize(Generic[_P, _T]): def __init__(self, obj: _T, func: Callable[_P, Any], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... def __call__(self, _: Any = None) -> Any | None: - """ - If alive then mark as dead and return func(*args, **kwargs); + """If alive then mark as dead and return func(*args, **kwargs); otherwise return None """ def detach(self) -> tuple[_T, Callable[_P, Any], tuple[Any, ...], dict[str, Any]] | None: - """ - If alive then mark as dead and return (obj, func, args, kwargs); + """If alive then mark as dead and return (obj, func, args, kwargs); otherwise return None """ def peek(self) -> tuple[_T, Callable[_P, Any], tuple[Any, ...], dict[str, Any]] | None: - """ - If alive then return (obj, func, args, kwargs); + """If alive then return (obj, func, args, kwargs); otherwise return None """ @property def alive(self) -> bool: - """ - Whether finalizer is alive - """ + """Whether finalizer is alive""" atexit: bool diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/webbrowser.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/webbrowser.pyi index 6ab2e6f844..f35cc7cdd7 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/webbrowser.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/webbrowser.pyi @@ -15,18 +15,13 @@ class Error(Exception): ... def register( name: str, klass: Callable[[], BaseBrowser] | None, instance: BaseBrowser | None = None, *, preferred: bool = False ) -> None: - """ - Register a browser connector. - """ + """Register a browser connector.""" def get(using: str | None = None) -> BaseBrowser: - """ - Return a browser launcher instance appropriate for the environment. - """ + """Return a browser launcher instance appropriate for the environment.""" def open(url: str, new: int = 0, autoraise: bool = True) -> bool: - """ - Display url using the default browser. + """Display url using the default browser. If possible, open url in a location determined by new. - 0: the same browser window (the default). @@ -39,23 +34,19 @@ def open(url: str, new: int = 0, autoraise: bool = True) -> bool: """ def open_new(url: str) -> bool: - """ - Open url in a new window of the default browser. + """Open url in a new window of the default browser. If not possible, then open url in the only browser window. """ def open_new_tab(url: str) -> bool: - """ - Open url in a new page ("tab") of the default browser. + """Open url in a new page ("tab") of the default browser. If not possible, then the behavior becomes equivalent to open_new(). """ class BaseBrowser: - """ - Parent class for all browsers. Do not use directly. - """ + """Parent class for all browsers. Do not use directly.""" args: list[str] name: str @@ -67,8 +58,7 @@ class BaseBrowser: def open_new_tab(self, url: str) -> bool: ... class GenericBrowser(BaseBrowser): - """ - Class for all browsers started with a command + """Class for all browsers started with a command and without remote functionality. """ @@ -76,15 +66,12 @@ class GenericBrowser(BaseBrowser): def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... class BackgroundBrowser(GenericBrowser): - """ - Class for all browsers which are to be started in the + """Class for all browsers which are to be started in the background. """ class UnixBrowser(BaseBrowser): - """ - Parent class for all Unix browsers with remote functionality. - """ + """Parent class for all Unix browsers with remote functionality.""" def open(self, url: str, new: Literal[0, 1, 2] = 0, autoraise: bool = True) -> bool: ... # type: ignore[override] raise_opts: list[str] | None @@ -96,15 +83,11 @@ class UnixBrowser(BaseBrowser): remote_action_newtab: str class Mozilla(UnixBrowser): - """ - Launcher class for Mozilla browsers. - """ + """Launcher class for Mozilla browsers.""" if sys.version_info < (3, 12): class Galeon(UnixBrowser): - """ - Launcher class for Galeon/Epiphany browsers. - """ + """Launcher class for Galeon/Epiphany browsers.""" raise_opts: list[str] @@ -112,23 +95,16 @@ if sys.version_info < (3, 12): def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... class Chrome(UnixBrowser): - """ - Launcher class for Google Chrome browser. - """ + """Launcher class for Google Chrome browser.""" class Opera(UnixBrowser): - """ - Launcher class for Opera browser. - """ + """Launcher class for Opera browser.""" class Elinks(UnixBrowser): - """ - Launcher class for Elinks browsers. - """ + """Launcher class for Elinks browsers.""" class Konqueror(BaseBrowser): - """ - Controller for the KDE File Manager (kfm, or Konqueror). + """Controller for the KDE File Manager (kfm, or Konqueror). See the output of ``kfmclient --commands`` for more information on the Konqueror remote-control interface. @@ -144,6 +120,16 @@ if sys.platform == "darwin": if sys.version_info < (3, 13): @deprecated("Deprecated in 3.11, to be removed in 3.13.") class MacOSX(BaseBrowser): + """Launcher class for Aqua browsers on Mac OS X + + Optionally specify a browser name on instantiation. Note that this + will not work for Aqua browsers if the user has moved the application + package after installation. + + If no browser is specified, the default browser, as specified in the + Internet System Preferences panel, will be used. + """ + def __init__(self, name: str) -> None: ... def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/winreg.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/winreg.pyi index d4d04817d7..a717fe3f3f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/winreg.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/winreg.pyi @@ -1,3 +1,43 @@ +""" +This module provides access to the Windows registry API. + +Functions: + +CloseKey() - Closes a registry key. +ConnectRegistry() - Establishes a connection to a predefined registry handle + on another computer. +CreateKey() - Creates the specified key, or opens it if it already exists. +DeleteKey() - Deletes the specified key. +DeleteValue() - Removes a named value from the specified registry key. +EnumKey() - Enumerates subkeys of the specified open registry key. +EnumValue() - Enumerates values of the specified open registry key. +ExpandEnvironmentStrings() - Expand the env strings in a REG_EXPAND_SZ + string. +FlushKey() - Writes all the attributes of the specified key to the registry. +LoadKey() - Creates a subkey under HKEY_USER or HKEY_LOCAL_MACHINE and + stores registration information from a specified file into that + subkey. +OpenKey() - Opens the specified key. +OpenKeyEx() - Alias of OpenKey(). +QueryValue() - Retrieves the value associated with the unnamed value for a + specified key in the registry. +QueryValueEx() - Retrieves the type and data for a specified value name + associated with an open registry key. +QueryInfoKey() - Returns information about the specified key. +SaveKey() - Saves the specified key, and all its subkeys a file. +SetValue() - Associates a value with a specified key. +SetValueEx() - Stores data in the value field of an open registry key. + +Special objects: + +HKEYType -- type object for HKEY objects +error -- exception raised for Win32 errors + +Integer constants: +Many constants are defined - see the documentation for each function +to see what constants are used, and where. +""" + import sys from _typeshed import ReadableBuffer, Unused from types import TracebackType @@ -6,29 +46,363 @@ from typing_extensions import Self, TypeAlias if sys.platform == "win32": _KeyType: TypeAlias = HKEYType | int - def CloseKey(hkey: _KeyType, /) -> None: ... - def ConnectRegistry(computer_name: str | None, key: _KeyType, /) -> HKEYType: ... - def CreateKey(key: _KeyType, sub_key: str | None, /) -> HKEYType: ... - def CreateKeyEx(key: _KeyType, sub_key: str | None, reserved: int = 0, access: int = 131078) -> HKEYType: ... - def DeleteKey(key: _KeyType, sub_key: str, /) -> None: ... - def DeleteKeyEx(key: _KeyType, sub_key: str, access: int = 256, reserved: int = 0) -> None: ... - def DeleteValue(key: _KeyType, value: str, /) -> None: ... - def EnumKey(key: _KeyType, index: int, /) -> str: ... - def EnumValue(key: _KeyType, index: int, /) -> tuple[str, Any, int]: ... - def ExpandEnvironmentStrings(string: str, /) -> str: ... - def FlushKey(key: _KeyType, /) -> None: ... - def LoadKey(key: _KeyType, sub_key: str, file_name: str, /) -> None: ... - def OpenKey(key: _KeyType, sub_key: str, reserved: int = 0, access: int = 131097) -> HKEYType: ... - def OpenKeyEx(key: _KeyType, sub_key: str, reserved: int = 0, access: int = 131097) -> HKEYType: ... - def QueryInfoKey(key: _KeyType, /) -> tuple[int, int, int]: ... - def QueryValue(key: _KeyType, sub_key: str | None, /) -> str: ... - def QueryValueEx(key: _KeyType, name: str, /) -> tuple[Any, int]: ... - def SaveKey(key: _KeyType, file_name: str, /) -> None: ... - def SetValue(key: _KeyType, sub_key: str, type: int, value: str, /) -> None: ... + def CloseKey(hkey: _KeyType, /) -> None: + """Closes a previously opened registry key. + + hkey + A previously opened key. + + Note that if the key is not closed using this method, it will be + closed when the hkey object is destroyed by Python. + """ + + def ConnectRegistry(computer_name: str | None, key: _KeyType, /) -> HKEYType: + """Establishes a connection to the registry on another computer. + + computer_name + The name of the remote computer, of the form r"\\\\computername". If + None, the local computer is used. + key + The predefined key to connect to. + + The return value is the handle of the opened key. + If the function fails, an OSError exception is raised. + """ + + def CreateKey(key: _KeyType, sub_key: str | None, /) -> HKEYType: + """Creates or opens the specified key. + + key + An already open key, or one of the predefined HKEY_* constants. + sub_key + The name of the key this method opens or creates. + + If key is one of the predefined keys, sub_key may be None. In that case, + the handle returned is the same key handle passed in to the function. + + If the key already exists, this function opens the existing key. + + The return value is the handle of the opened key. + If the function fails, an OSError exception is raised. + """ + + def CreateKeyEx(key: _KeyType, sub_key: str | None, reserved: int = 0, access: int = 131078) -> HKEYType: + """Creates or opens the specified key. + + key + An already open key, or one of the predefined HKEY_* constants. + sub_key + The name of the key this method opens or creates. + reserved + A reserved integer, and must be zero. Default is zero. + access + An integer that specifies an access mask that describes the + desired security access for the key. Default is KEY_WRITE. + + If key is one of the predefined keys, sub_key may be None. In that case, + the handle returned is the same key handle passed in to the function. + + If the key already exists, this function opens the existing key + + The return value is the handle of the opened key. + If the function fails, an OSError exception is raised. + """ + + def DeleteKey(key: _KeyType, sub_key: str, /) -> None: + """Deletes the specified key. + + key + An already open key, or any one of the predefined HKEY_* constants. + sub_key + A string that must be the name of a subkey of the key identified by + the key parameter. This value must not be None, and the key may not + have subkeys. + + This method can not delete keys with subkeys. + + If the function succeeds, the entire key, including all of its values, + is removed. If the function fails, an OSError exception is raised. + """ + + def DeleteKeyEx(key: _KeyType, sub_key: str, access: int = 256, reserved: int = 0) -> None: + """Deletes the specified key (intended for 64-bit OS). + + key + An already open key, or any one of the predefined HKEY_* constants. + sub_key + A string that must be the name of a subkey of the key identified by + the key parameter. This value must not be None, and the key may not + have subkeys. + access + An integer that specifies an access mask that describes the + desired security access for the key. Default is KEY_WOW64_64KEY. + reserved + A reserved integer, and must be zero. Default is zero. + + While this function is intended to be used for 64-bit OS, it is also + available on 32-bit systems. + + This method can not delete keys with subkeys. + + If the function succeeds, the entire key, including all of its values, + is removed. If the function fails, an OSError exception is raised. + On unsupported Windows versions, NotImplementedError is raised. + """ + + def DeleteValue(key: _KeyType, value: str, /) -> None: + """Removes a named value from a registry key. + + key + An already open key, or any one of the predefined HKEY_* constants. + value + A string that identifies the value to remove. + """ + + def EnumKey(key: _KeyType, index: int, /) -> str: + """Enumerates subkeys of an open registry key. + + key + An already open key, or any one of the predefined HKEY_* constants. + index + An integer that identifies the index of the key to retrieve. + + The function retrieves the name of one subkey each time it is called. + It is typically called repeatedly until an OSError exception is + raised, indicating no more values are available. + """ + + def EnumValue(key: _KeyType, index: int, /) -> tuple[str, Any, int]: + """Enumerates values of an open registry key. + + key + An already open key, or any one of the predefined HKEY_* constants. + index + An integer that identifies the index of the value to retrieve. + + The function retrieves the name of one subkey each time it is called. + It is typically called repeatedly, until an OSError exception + is raised, indicating no more values. + + The result is a tuple of 3 items: + value_name + A string that identifies the value. + value_data + An object that holds the value data, and whose type depends + on the underlying registry type. + data_type + An integer that identifies the type of the value data. + """ + + def ExpandEnvironmentStrings(string: str, /) -> str: + """Expand environment vars.""" + + def FlushKey(key: _KeyType, /) -> None: + """Writes all the attributes of a key to the registry. + + key + An already open key, or any one of the predefined HKEY_* constants. + + It is not necessary to call FlushKey to change a key. Registry changes + are flushed to disk by the registry using its lazy flusher. Registry + changes are also flushed to disk at system shutdown. Unlike + CloseKey(), the FlushKey() method returns only when all the data has + been written to the registry. + + An application should only call FlushKey() if it requires absolute + certainty that registry changes are on disk. If you don't know whether + a FlushKey() call is required, it probably isn't. + """ + + def LoadKey(key: _KeyType, sub_key: str, file_name: str, /) -> None: + """Insert data into the registry from a file. + + key + An already open key, or any one of the predefined HKEY_* constants. + sub_key + A string that identifies the sub-key to load. + file_name + The name of the file to load registry data from. This file must + have been created with the SaveKey() function. Under the file + allocation table (FAT) file system, the filename may not have an + extension. + + Creates a subkey under the specified key and stores registration + information from a specified file into that subkey. + + A call to LoadKey() fails if the calling process does not have the + SE_RESTORE_PRIVILEGE privilege. + + If key is a handle returned by ConnectRegistry(), then the path + specified in fileName is relative to the remote computer. + + The MSDN docs imply key must be in the HKEY_USER or HKEY_LOCAL_MACHINE + tree. + """ + + def OpenKey(key: _KeyType, sub_key: str, reserved: int = 0, access: int = 131097) -> HKEYType: + """Opens the specified key. + + key + An already open key, or any one of the predefined HKEY_* constants. + sub_key + A string that identifies the sub_key to open. + reserved + A reserved integer that must be zero. Default is zero. + access + An integer that specifies an access mask that describes the desired + security access for the key. Default is KEY_READ. + + The result is a new handle to the specified key. + If the function fails, an OSError exception is raised. + """ + + def OpenKeyEx(key: _KeyType, sub_key: str, reserved: int = 0, access: int = 131097) -> HKEYType: + """Opens the specified key. + + key + An already open key, or any one of the predefined HKEY_* constants. + sub_key + A string that identifies the sub_key to open. + reserved + A reserved integer that must be zero. Default is zero. + access + An integer that specifies an access mask that describes the desired + security access for the key. Default is KEY_READ. + + The result is a new handle to the specified key. + If the function fails, an OSError exception is raised. + """ + + def QueryInfoKey(key: _KeyType, /) -> tuple[int, int, int]: + """Returns information about a key. + + key + An already open key, or any one of the predefined HKEY_* constants. + + The result is a tuple of 3 items: + An integer that identifies the number of sub keys this key has. + An integer that identifies the number of values this key has. + An integer that identifies when the key was last modified (if available) + as 100's of nanoseconds since Jan 1, 1600. + """ + + def QueryValue(key: _KeyType, sub_key: str | None, /) -> str: + """Retrieves the unnamed value for a key. + + key + An already open key, or any one of the predefined HKEY_* constants. + sub_key + A string that holds the name of the subkey with which the value + is associated. If this parameter is None or empty, the function + retrieves the value set by the SetValue() method for the key + identified by key. + + Values in the registry have name, type, and data components. This method + retrieves the data for a key's first value that has a NULL name. + But since the underlying API call doesn't return the type, you'll + probably be happier using QueryValueEx; this function is just here for + completeness. + """ + + def QueryValueEx(key: _KeyType, name: str, /) -> tuple[Any, int]: + """Retrieves the type and value of a specified sub-key. + + key + An already open key, or any one of the predefined HKEY_* constants. + name + A string indicating the value to query. + + Behaves mostly like QueryValue(), but also returns the type of the + specified value name associated with the given open registry key. + + The return value is a tuple of the value and the type_id. + """ + + def SaveKey(key: _KeyType, file_name: str, /) -> None: + """Saves the specified key, and all its subkeys to the specified file. + + key + An already open key, or any one of the predefined HKEY_* constants. + file_name + The name of the file to save registry data to. This file cannot + already exist. If this filename includes an extension, it cannot be + used on file allocation table (FAT) file systems by the LoadKey(), + ReplaceKey() or RestoreKey() methods. + + If key represents a key on a remote computer, the path described by + file_name is relative to the remote computer. + + The caller of this method must possess the SeBackupPrivilege + security privilege. This function passes NULL for security_attributes + to the API. + """ + + def SetValue(key: _KeyType, sub_key: str, type: int, value: str, /) -> None: + """Associates a value with a specified key. + + key + An already open key, or any one of the predefined HKEY_* constants. + sub_key + A string that names the subkey with which the value is associated. + type + An integer that specifies the type of the data. Currently this must + be REG_SZ, meaning only strings are supported. + value + A string that specifies the new value. + + If the key specified by the sub_key parameter does not exist, the + SetValue function creates it. + + Value lengths are limited by available memory. Long values (more than + 2048 bytes) should be stored as files with the filenames stored in + the configuration registry to help the registry perform efficiently. + + The key identified by the key parameter must have been opened with + KEY_SET_VALUE access. + """ + @overload # type=REG_DWORD|REG_QWORD - def SetValueEx( - key: _KeyType, value_name: str | None, reserved: Unused, type: Literal[4, 5], value: int | None, / - ) -> None: ... + def SetValueEx(key: _KeyType, value_name: str | None, reserved: Unused, type: Literal[4, 5], value: int | None, /) -> None: + """Stores data in the value field of an open registry key. + + key + An already open key, or any one of the predefined HKEY_* constants. + value_name + A string containing the name of the value to set, or None. + reserved + Can be anything - zero is always passed to the API. + type + An integer that specifies the type of the data, one of: + REG_BINARY -- Binary data in any form. + REG_DWORD -- A 32-bit number. + REG_DWORD_LITTLE_ENDIAN -- A 32-bit number in little-endian format. Equivalent to REG_DWORD + REG_DWORD_BIG_ENDIAN -- A 32-bit number in big-endian format. + REG_EXPAND_SZ -- A null-terminated string that contains unexpanded + references to environment variables (for example, + %PATH%). + REG_LINK -- A Unicode symbolic link. + REG_MULTI_SZ -- A sequence of null-terminated strings, terminated + by two null characters. Note that Python handles + this termination automatically. + REG_NONE -- No defined value type. + REG_QWORD -- A 64-bit number. + REG_QWORD_LITTLE_ENDIAN -- A 64-bit number in little-endian format. Equivalent to REG_QWORD. + REG_RESOURCE_LIST -- A device-driver resource list. + REG_SZ -- A null-terminated string. + value + A string that specifies the new value. + + This method can also set additional value and type information for the + specified key. The key identified by the key parameter must have been + opened with KEY_SET_VALUE access. + + To open the key, use the CreateKeyEx() or OpenKeyEx() methods. + + Value lengths are limited by available memory. Long values (more than + 2048 bytes) should be stored as files with the filenames stored in + the configuration registry to help the registry perform efficiently. + """ + @overload # type=REG_SZ|REG_EXPAND_SZ def SetValueEx( key: _KeyType, value_name: str | None, reserved: Unused, type: Literal[1, 2], value: str | None, / @@ -55,10 +429,38 @@ if sys.platform == "win32": value: int | str | list[str] | ReadableBuffer | None, /, ) -> None: ... - def DisableReflectionKey(key: _KeyType, /) -> None: ... - def EnableReflectionKey(key: _KeyType, /) -> None: ... - def QueryReflectionKey(key: _KeyType, /) -> bool: ... + def DisableReflectionKey(key: _KeyType, /) -> None: + """Disables registry reflection for 32bit processes running on a 64bit OS. + key + An already open key, or any one of the predefined HKEY_* constants. + + Will generally raise NotImplementedError if executed on a 32bit OS. + + If the key is not on the reflection list, the function succeeds but has + no effect. Disabling reflection for a key does not affect reflection + of any subkeys. + """ + + def EnableReflectionKey(key: _KeyType, /) -> None: + """Restores registry reflection for the specified disabled key. + + key + An already open key, or any one of the predefined HKEY_* constants. + + Will generally raise NotImplementedError if executed on a 32bit OS. + Restoring reflection for a key does not affect reflection of any + subkeys. + """ + + def QueryReflectionKey(key: _KeyType, /) -> bool: + """Returns the reflection state for the specified key as a bool. + + key + An already open key, or any one of the predefined HKEY_* constants. + + Will generally raise NotImplementedError if executed on a 32bit OS. + """ HKEY_CLASSES_ROOT: int HKEY_CURRENT_USER: int HKEY_LOCAL_MACHINE: int @@ -119,14 +521,56 @@ if sys.platform == "win32": # Though this class has a __name__ of PyHKEY, it's exposed as HKEYType for some reason @final class HKEYType: - def __bool__(self) -> bool: ... - def __int__(self) -> int: ... + """PyHKEY Object - A Python object, representing a win32 registry key. + + This object wraps a Windows HKEY object, automatically closing it when + the object is destroyed. To guarantee cleanup, you can call either + the Close() method on the PyHKEY, or the CloseKey() method. + + All functions which accept a handle object also accept an integer -- + however, use of the handle object is encouraged. + + Functions: + Close() - Closes the underlying handle. + Detach() - Returns the integer Win32 handle, detaching it from the object + + Properties: + handle - The integer Win32 handle. + + Operations: + __bool__ - Handles with an open object return true, otherwise false. + __int__ - Converting a handle to an integer returns the Win32 handle. + rich comparison - Handle objects are compared using the handle value. + """ + + def __bool__(self) -> bool: + """True if self else False""" + + def __int__(self) -> int: + """int(self)""" + def __enter__(self) -> Self: ... def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None ) -> bool | None: ... - def Close(self) -> None: ... - def Detach(self) -> int: ... + def Close(self) -> None: + """Closes the underlying Windows handle. + + If the handle is already closed, no error is raised. + """ + + def Detach(self) -> int: + """Detaches the Windows handle from the handle object. + + The result is the value of the handle before it is detached. If the + handle is already detached, this will return zero. + + After calling this function, the handle is effectively invalidated, + but the handle is not closed. You would call this function when you + need the underlying win32 handle to exist beyond the lifetime of the + handle object. + """ + def __hash__(self) -> int: ... @property def handle(self) -> int: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/winsound.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/winsound.pyi index 39dfa7b8b9..99ed1cc450 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/winsound.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/winsound.pyi @@ -1,3 +1,23 @@ +""" +PlaySound(sound, flags) - play a sound +SND_FILENAME - sound is a wav file name +SND_ALIAS - sound is a registry sound association name +SND_LOOP - Play the sound repeatedly; must also specify SND_ASYNC +SND_MEMORY - sound is a memory image of a wav file +SND_PURGE - stop all instances of the specified sound +SND_ASYNC - PlaySound returns immediately +SND_NODEFAULT - Do not play a default beep if the sound can not be found +SND_NOSTOP - Do not interrupt any sounds currently playing +SND_NOWAIT - Return immediately if the sound driver is busy +SND_APPLICATION - sound is an application-specific alias in the registry. +SND_SENTRY - Triggers a SoundSentry event when the sound is played. +SND_SYNC - Play the sound synchronously, default behavior. +SND_SYSTEM - Assign sound to the audio session for system notification sounds. + +Beep(frequency, duration) - Make a beep through the PC speaker. +MessageBeep(type) - Call Windows MessageBeep. +""" + import sys from _typeshed import ReadableBuffer from typing import Final, Literal, overload @@ -29,10 +49,30 @@ if sys.platform == "win32": MB_ICONSTOP: Final = 16 MB_ICONWARNING: Final = 48 - def Beep(frequency: int, duration: int) -> None: ... + def Beep(frequency: int, duration: int) -> None: + """A wrapper around the Windows Beep API. + + frequency + Frequency of the sound in hertz. + Must be in the range 37 through 32,767. + duration + How long the sound should play, in milliseconds. + """ # Can actually accept anything ORed with 4, and if not it's definitely str, but that's inexpressible @overload - def PlaySound(sound: ReadableBuffer | None, flags: Literal[4]) -> None: ... + def PlaySound(sound: ReadableBuffer | None, flags: Literal[4]) -> None: + """A wrapper around the Windows PlaySound API. + + sound + The sound to play; a filename, data, or None. + flags + Flag values, ored together. See module documentation. + """ + @overload def PlaySound(sound: str | ReadableBuffer | None, flags: int) -> None: ... - def MessageBeep(type: int = 0) -> None: ... + def MessageBeep(type: int = 0) -> None: + """Call Windows MessageBeep(x). + + x defaults to MB_OK. + """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/handlers.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/handlers.pyi index ddb5ee4d02..35b3b8756d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/handlers.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/handlers.pyi @@ -15,14 +15,10 @@ __all__ = ["BaseHandler", "SimpleHandler", "BaseCGIHandler", "CGIHandler", "IISC def format_date_time(timestamp: float | None) -> str: ... # undocumented def read_environ() -> dict[str, str]: - """ - Read environment, fixing HTTP variables - """ + """Read environment, fixing HTTP variables""" class BaseHandler: - """ - Manage the invocation of a WSGI application - """ + """Manage the invocation of a WSGI application""" wsgi_version: tuple[int, int] # undocumented wsgi_multithread: bool @@ -43,18 +39,13 @@ class BaseHandler: error_headers: list[tuple[str, str]] error_body: bytes def run(self, application: WSGIApplication) -> None: - """ - Invoke the application - """ + """Invoke the application""" def setup_environ(self) -> None: - """ - Set up the environment for one request - """ + """Set up the environment for one request""" def finish_response(self) -> None: - """ - Send any iterable data, then close self and the iterable + """Send any iterable data, then close self and the iterable Subclasses intended for use in asynchronous servers will want to redefine this method, such that it sets up callbacks @@ -63,18 +54,13 @@ class BaseHandler: """ def get_scheme(self) -> str: - """ - Return the URL scheme being used - """ + """Return the URL scheme being used""" def set_content_length(self) -> None: - """ - Compute Content-Length or switch to chunked encoding if possible - """ + """Compute Content-Length or switch to chunked encoding if possible""" def cleanup_headers(self) -> None: - """ - Make any necessary header changes or defaults + """Make any necessary header changes or defaults Subclasses can extend this to add other defaults. """ @@ -82,23 +68,16 @@ class BaseHandler: def start_response( self, status: str, headers: list[tuple[str, str]], exc_info: OptExcInfo | None = None ) -> Callable[[bytes], None]: - """ - 'start_response()' callable as specified by PEP 3333 - """ + """'start_response()' callable as specified by PEP 3333""" def send_preamble(self) -> None: - """ - Transmit version/status/date/server, via self._write() - """ + """Transmit version/status/date/server, via self._write()""" def write(self, data: bytes) -> None: - """ - 'write()' callable as specified by PEP 3333 - """ + """'write()' callable as specified by PEP 3333""" def sendfile(self) -> bool: - """ - Platform-specific file transmission + """Platform-specific file transmission Override this method in subclasses to support platform-specific file transmission. It is only called if the application's @@ -117,47 +96,34 @@ class BaseHandler: """ def finish_content(self) -> None: - """ - Ensure headers and content have both been sent - """ + """Ensure headers and content have both been sent""" def close(self) -> None: - """ - Close the iterable (if needed) and reset all instance vars + """Close the iterable (if needed) and reset all instance vars Subclasses may want to also drop the client connection. """ def send_headers(self) -> None: - """ - Transmit headers to the client, via self._write() - """ + """Transmit headers to the client, via self._write()""" def result_is_file(self) -> bool: - """ - True if 'self.result' is an instance of 'self.wsgi_file_wrapper' - """ + """True if 'self.result' is an instance of 'self.wsgi_file_wrapper'""" def client_is_modern(self) -> bool: - """ - True if client can accept status and headers - """ + """True if client can accept status and headers""" def log_exception(self, exc_info: OptExcInfo) -> None: - """ - Log the 'exc_info' tuple in the server log + """Log the 'exc_info' tuple in the server log Subclasses may override to retarget the output or change its format. """ def handle_error(self) -> None: - """ - Log current error, and send error output to client if possible - """ + """Log current error, and send error output to client if possible""" def error_output(self, environ: WSGIEnvironment, start_response: StartResponse) -> list[bytes]: - """ - WSGI mini-app to create error output + """WSGI mini-app to create error output By default, this just uses the 'error_status', 'error_headers', and 'error_body' attributes to generate an output page. It can @@ -172,8 +138,7 @@ class BaseHandler: @abstractmethod def _write(self, data: bytes) -> None: - """ - Override in subclass to buffer data for send to client + """Override in subclass to buffer data for send to client It's okay if this method actually transmits the data; BaseHandler just separates write and flush operations for greater efficiency @@ -182,8 +147,7 @@ class BaseHandler: @abstractmethod def _flush(self) -> None: - """ - Override in subclass to force sending of recent '_write()' calls + """Override in subclass to force sending of recent '_write()' calls It's okay if this method is a no-op (i.e., if '_write()' actually sends the data. @@ -191,25 +155,18 @@ class BaseHandler: @abstractmethod def get_stdin(self) -> InputStream: - """ - Override in subclass to return suitable 'wsgi.input' - """ + """Override in subclass to return suitable 'wsgi.input'""" @abstractmethod def get_stderr(self) -> ErrorStream: - """ - Override in subclass to return suitable 'wsgi.errors' - """ + """Override in subclass to return suitable 'wsgi.errors'""" @abstractmethod def add_cgi_vars(self) -> None: - """ - Override in subclass to insert CGI variables in 'self.environ' - """ + """Override in subclass to insert CGI variables in 'self.environ'""" class SimpleHandler(BaseHandler): - """ - Handler that's just initialized with streams, environment, etc. + """Handler that's just initialized with streams, environment, etc. This handler subclass is intended for synchronous HTTP/1.0 origin servers, and handles sending the entire response output, given the correct inputs. @@ -242,8 +199,7 @@ class SimpleHandler(BaseHandler): def _flush(self) -> None: ... class BaseCGIHandler(SimpleHandler): - """ - CGI-like systems using input/output/error streams and environ mapping + """CGI-like systems using input/output/error streams and environ mapping Usage:: @@ -263,8 +219,7 @@ class BaseCGIHandler(SimpleHandler): """ class CGIHandler(BaseCGIHandler): - """ - CGI-based invocation via sys.stdin/stdout/stderr and os.environ + """CGI-based invocation via sys.stdin/stdout/stderr and os.environ Usage:: @@ -282,8 +237,7 @@ class CGIHandler(BaseCGIHandler): def __init__(self) -> None: ... class IISCGIHandler(BaseCGIHandler): - """ - CGI-based invocation with workaround for IIS path bug + """CGI-based invocation with workaround for IIS path bug This handler should be used in preference to CGIHandler when deploying on Microsoft IIS without having set the config allowPathInfo option (IIS>=7) diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/headers.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/headers.pyi index f3a5eeb609..ee1d7c2094 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/headers.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/headers.pyi @@ -15,31 +15,23 @@ _HeaderList: TypeAlias = list[tuple[str, str]] tspecials: Pattern[str] # undocumented class Headers: - """ - Manage a collection of HTTP response headers - """ + """Manage a collection of HTTP response headers""" def __init__(self, headers: _HeaderList | None = None) -> None: ... def __len__(self) -> int: - """ - Return the total number of headers, including duplicates. - """ + """Return the total number of headers, including duplicates.""" def __setitem__(self, name: str, val: str) -> None: - """ - Set the value of a header. - """ + """Set the value of a header.""" def __delitem__(self, name: str) -> None: - """ - Delete all occurrences of a header, if present. + """Delete all occurrences of a header, if present. Does *not* raise an exception if the header is missing. """ def __getitem__(self, name: str) -> str | None: - """ - Get the first header value for 'name' + """Get the first header value for 'name' Return None if the header is missing instead of raising an exception. @@ -49,13 +41,10 @@ class Headers: """ def __contains__(self, name: str) -> bool: - """ - Return true if the message contains the header. - """ + """Return true if the message contains the header.""" def get_all(self, name: str) -> list[str]: - """ - Return a list of all the values for the named field. + """Return a list of all the values for the named field. These will be sorted in the order they appeared in the original header list or were added to this instance, and may contain duplicates. Any @@ -65,15 +54,12 @@ class Headers: @overload def get(self, name: str, default: str) -> str: - """ - Get the first header value for 'name', or return 'default' - """ + """Get the first header value for 'name', or return 'default'""" @overload def get(self, name: str, default: str | None = None) -> str | None: ... def keys(self) -> list[str]: - """ - Return a list of all the header field names. + """Return a list of all the header field names. These will be sorted in the order they appeared in the original header list, or were added to this instance, and may contain duplicates. @@ -82,8 +68,7 @@ class Headers: """ def values(self) -> list[str]: - """ - Return a list of all header values. + """Return a list of all header values. These will be sorted in the order they appeared in the original header list, or were added to this instance, and may contain duplicates. @@ -92,8 +77,7 @@ class Headers: """ def items(self) -> _HeaderList: - """ - Get all the header fields and values. + """Get all the header fields and values. These will be sorted in the order they were in the original header list, or were added to this instance, and may contain duplicates. @@ -103,16 +87,14 @@ class Headers: def __bytes__(self) -> bytes: ... def setdefault(self, name: str, value: str) -> str: - """ - Return first matching header value for 'name', or 'value' + """Return first matching header value for 'name', or 'value' If there is no header named 'name', add a new header with name 'name' and value 'value'. """ def add_header(self, _name: str, _value: str | None, **_params: str | None) -> None: - """ - Extended header setting. + """Extended header setting. _name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/simple_server.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/simple_server.pyi index f8f67c4055..3a5032fbc9 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/simple_server.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/simple_server.pyi @@ -27,9 +27,7 @@ class ServerHandler(SimpleHandler): # undocumented server_software: str class WSGIServer(HTTPServer): - """ - BaseHTTPServer that implements the Python WSGI protocol - """ + """BaseHTTPServer that implements the Python WSGI protocol""" application: WSGIApplication | None base_environ: WSGIEnvironment # only available after call to setup_environ() @@ -48,9 +46,7 @@ _S = TypeVar("_S", bound=WSGIServer) @overload def make_server(host: str, port: int, app: WSGIApplication, *, handler_class: type[WSGIRequestHandler] = ...) -> WSGIServer: - """ - Create a new WSGI server listening on `host` and `port` for `app` - """ + """Create a new WSGI server listening on `host` and `port` for `app`""" @overload def make_server( diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/types.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/types.pyi index 998976c7d6..3ee4da7362 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/types.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/types.pyi @@ -10,9 +10,7 @@ from typing_extensions import TypeAlias __all__ = ["StartResponse", "WSGIEnvironment", "WSGIApplication", "InputStream", "ErrorStream", "FileWrapper"] class StartResponse(Protocol): - """ - start_response() callable as defined in PEP 3333 - """ + """start_response() callable as defined in PEP 3333""" def __call__( self, status: str, headers: list[tuple[str, str]], exc_info: OptExcInfo | None = ..., / @@ -22,9 +20,7 @@ WSGIEnvironment: TypeAlias = dict[str, Any] WSGIApplication: TypeAlias = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] class InputStream(Protocol): - """ - WSGI input stream as defined in PEP 3333 - """ + """WSGI input stream as defined in PEP 3333""" def read(self, size: int = ..., /) -> bytes: ... def readline(self, size: int = ..., /) -> bytes: ... @@ -32,9 +28,7 @@ class InputStream(Protocol): def __iter__(self) -> Iterator[bytes]: ... class ErrorStream(Protocol): - """ - WSGI error stream as defined in PEP 3333 - """ + """WSGI error stream as defined in PEP 3333""" def flush(self) -> object: ... def write(self, s: str, /) -> object: ... @@ -45,8 +39,6 @@ class _Readable(Protocol): # Optional: def close(self) -> object: ... class FileWrapper(Protocol): - """ - WSGI file wrapper as defined in PEP 3333 - """ + """WSGI file wrapper as defined in PEP 3333""" def __call__(self, file: _Readable, block_size: int = ..., /) -> Iterable[bytes]: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/util.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/util.pyi index bbf8db695c..4005e3b8bc 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/util.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/util.pyi @@ -12,9 +12,7 @@ if sys.version_info >= (3, 13): __all__ += ["is_hop_by_hop"] class FileWrapper: - """ - Wrapper to convert file-like objects to iterables - """ + """Wrapper to convert file-like objects to iterables""" filelike: IO[bytes] blksize: int @@ -27,23 +25,16 @@ class FileWrapper: def __next__(self) -> bytes: ... def guess_scheme(environ: WSGIEnvironment) -> str: - """ - Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https' - """ + """Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https'""" def application_uri(environ: WSGIEnvironment) -> str: - """ - Return the application's base URI (no PATH_INFO or QUERY_STRING) - """ + """Return the application's base URI (no PATH_INFO or QUERY_STRING)""" def request_uri(environ: WSGIEnvironment, include_query: bool = True) -> str: - """ - Return the full request URI, optionally including the query string - """ + """Return the full request URI, optionally including the query string""" def shift_path_info(environ: WSGIEnvironment) -> str | None: - """ - Shift a name from PATH_INFO to SCRIPT_NAME, returning it + """Shift a name from PATH_INFO to SCRIPT_NAME, returning it If there are no remaining path segments in PATH_INFO, return None. Note: 'environ' is modified in-place; use a copy if you need to keep @@ -57,8 +48,7 @@ def shift_path_info(environ: WSGIEnvironment) -> str | None: """ def setup_testing_defaults(environ: WSGIEnvironment) -> None: - """ - Update 'environ' with trivial defaults for testing purposes + """Update 'environ' with trivial defaults for testing purposes This adds various parameters required for WSGI, including HTTP_HOST, SERVER_NAME, SERVER_PORT, REQUEST_METHOD, SCRIPT_NAME, PATH_INFO, @@ -71,6 +61,4 @@ def setup_testing_defaults(environ: WSGIEnvironment) -> None: """ def is_hop_by_hop(header_name: str) -> bool: - """ - Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header - """ + """Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/validate.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/validate.pyi index b537918d43..ad2d25da22 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/validate.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/wsgiref/validate.pyi @@ -1,4 +1,5 @@ """ + Middleware to check for obedience to the WSGI specification. Some of the things this checks: @@ -113,13 +114,10 @@ from typing_extensions import TypeAlias __all__ = ["validator"] class WSGIWarning(Warning): - """ - Raised in response to WSGI-spec-related warnings - """ + """Raised in response to WSGI-spec-related warnings""" def validator(application: WSGIApplication) -> WSGIApplication: - """ - When applied between a WSGI server and a WSGI application, this + """When applied between a WSGI server and a WSGI application, this middleware will check for WSGI compliance on a number of levels. This middleware does not modify the request or response in any way, but will raise an AssertionError if anything seems off diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xdrlib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xdrlib.pyi index 3d89d11458..9a2ed92bea 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xdrlib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xdrlib.pyi @@ -12,8 +12,7 @@ __all__ = ["Error", "Packer", "Unpacker", "ConversionError"] _T = TypeVar("_T") class Error(Exception): - """ - Exception class for this module. Use: + """Exception class for this module. Use: except xdrlib.Error as var: # var has the Error instance for the exception @@ -28,9 +27,7 @@ class Error(Exception): class ConversionError(Error): ... class Packer: - """ - Pack various data representations into a buffer. - """ + """Pack various data representations into a buffer.""" def reset(self) -> None: ... def get_buffer(self) -> bytes: ... @@ -53,9 +50,7 @@ class Packer: def pack_array(self, list: Sequence[_T], pack_item: Callable[[_T], object]) -> None: ... class Unpacker: - """ - Unpacks various data representations from the given buffer. - """ + """Unpacks various data representations from the given buffer.""" def __init__(self, data: bytes) -> None: ... def reset(self, data: bytes) -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/NodeFilter.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/NodeFilter.pyi index b1c7d2059a..5634d118a3 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/NodeFilter.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/NodeFilter.pyi @@ -2,9 +2,7 @@ from typing import Literal from xml.dom.minidom import Node class NodeFilter: - """ - This is the DOM2 NodeFilter interface. It contains only constants. - """ + """This is the DOM2 NodeFilter interface. It contains only constants.""" FILTER_ACCEPT: Literal[1] FILTER_REJECT: Literal[2] diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/__init__.pyi index 0d8ede6419..a29f7d06ab 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/__init__.pyi @@ -19,9 +19,7 @@ from typing import Any, Final, Literal from .domreg import getDOMImplementation as getDOMImplementation, registerDOMImplementation as registerDOMImplementation class Node: - """ - Class giving the NodeType constants. - """ + """Class giving the NodeType constants.""" ELEMENT_NODE: Literal[1] ATTRIBUTE_NODE: Literal[2] @@ -55,8 +53,7 @@ INVALID_ACCESS_ERR: Final = 15 VALIDATION_ERR: Final = 16 class DOMException(Exception): - """ - Abstract base class for DOM exceptions. + """Abstract base class for DOM exceptions. Exceptions with specific codes are specializations of this class. """ @@ -113,9 +110,7 @@ class ValidationErr(DOMException): code: Literal[16] class UserDataHandler: - """ - Class giving the operation constants for UserDataHandler.handle(). - """ + """Class giving the operation constants for UserDataHandler.handle().""" NODE_CLONED: Literal[1] NODE_IMPORTED: Literal[2] diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/domreg.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/domreg.pyi index 760f75e7e2..05cbbaf72d 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/domreg.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/domreg.pyi @@ -11,8 +11,7 @@ well_known_implementations: dict[str, str] registered: dict[str, Callable[[], DOMImplementation]] def registerDOMImplementation(name: str, factory: Callable[[], DOMImplementation]) -> None: - """ - registerDOMImplementation(name, factory) + """registerDOMImplementation(name, factory) Register the factory function with the name. The factory function should return an object which implements the DOMImplementation @@ -22,8 +21,7 @@ def registerDOMImplementation(name: str, factory: Callable[[], DOMImplementation """ def getDOMImplementation(name: str | None = None, features: str | Iterable[tuple[str, str | None]] = ()) -> DOMImplementation: - """ - getDOMImplementation(name = None, features = ()) -> DOM implementation. + """getDOMImplementation(name = None, features = ()) -> DOM implementation. Return a suitable DOM implementation. The name is either well-known, the module name of a DOM implementation, or None. If diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/expatbuilder.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/expatbuilder.pyi index 66f6538faa..cdb0ce4047 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/expatbuilder.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/expatbuilder.pyi @@ -34,8 +34,7 @@ class ElementInfo: def isIdNS(self, euri: str, ename: str, auri: str, aname: str) -> bool: ... class ExpatBuilder: - """ - Document builder that uses Expat to build a ParsedXML.DOM document + """Document builder that uses Expat to build a ParsedXML.DOM document instance. """ @@ -43,35 +42,24 @@ class ExpatBuilder: curNode: DocumentFragment | Element | Document # Created in self.reset() def __init__(self, options: Options | None = None) -> None: ... def createParser(self) -> XMLParserType: - """ - Create a new parser object. - """ + """Create a new parser object.""" def getParser(self) -> XMLParserType: - """ - Return the parser object, creating a new one if needed. - """ + """Return the parser object, creating a new one if needed.""" def reset(self) -> None: - """ - Free all data structures used during DOM construction. - """ + """Free all data structures used during DOM construction.""" def install(self, parser: XMLParserType) -> None: - """ - Install the callbacks needed to build the DOM into the parser. - """ + """Install the callbacks needed to build the DOM into the parser.""" def parseFile(self, file: SupportsRead[ReadableBuffer | str]) -> Document: - """ - Parse a document from a file object, returning the document + """Parse a document from a file object, returning the document node. """ def parseString(self, string: str | ReadableBuffer) -> Document: - """ - Parse a document from a string, returning the document node. - """ + """Parse a document from a string, returning the document node.""" def start_doctype_decl_handler( self, doctypeName: str, systemId: str | None, publicId: str | None, has_internal_subset: bool @@ -103,8 +91,7 @@ class ExpatBuilder: def xml_decl_handler(self, version: str, encoding: str | None, standalone: int) -> None: ... class FilterVisibilityController: - """ - Wrapper around a DOMBuilderFilter which implements the checks + """Wrapper around a DOMBuilderFilter which implements the checks to make the whatToShow filter attribute work. """ @@ -125,8 +112,7 @@ class Skipper(FilterCrutch): def end_element_handler(self, *args: Any) -> None: ... class FragmentBuilder(ExpatBuilder): - """ - Builder which constructs document fragments given XML source + """Builder which constructs document fragments given XML source text and a context node. The context node is expected to provide information about the @@ -140,67 +126,47 @@ class FragmentBuilder(ExpatBuilder): def __init__(self, context: Node, options: Options | None = None) -> None: ... def reset(self) -> None: ... def parseFile(self, file: SupportsRead[ReadableBuffer | str]) -> DocumentFragment: # type: ignore[override] - """ - Parse a document fragment from a file object, returning the + """Parse a document fragment from a file object, returning the fragment node. """ def parseString(self, string: ReadableBuffer | str) -> DocumentFragment: # type: ignore[override] - """ - Parse a document fragment from a string, returning the + """Parse a document fragment from a string, returning the fragment node. """ def external_entity_ref_handler(self, context: str, base: str | None, systemId: str | None, publicId: str | None) -> int: ... class Namespaces: - """ - Mix-in class for builders; adds support for namespaces. - """ + """Mix-in class for builders; adds support for namespaces.""" def createParser(self) -> XMLParserType: - """ - Create a new namespace-handling parser. - """ + """Create a new namespace-handling parser.""" def install(self, parser: XMLParserType) -> None: - """ - Insert the namespace-handlers onto the parser. - """ + """Insert the namespace-handlers onto the parser.""" def start_namespace_decl_handler(self, prefix: str | None, uri: str) -> None: - """ - Push this namespace declaration on our storage. - """ + """Push this namespace declaration on our storage.""" def start_element_handler(self, name: str, attributes: list[str]) -> None: ... def end_element_handler(self, name: str) -> None: ... # only exists if __debug__ class ExpatBuilderNS(Namespaces, ExpatBuilder): - """ - Document builder that supports namespaces. - """ + """Document builder that supports namespaces.""" class FragmentBuilderNS(Namespaces, FragmentBuilder): - """ - Fragment builder that supports namespaces. - """ + """Fragment builder that supports namespaces.""" class ParseEscape(Exception): - """ - Exception raised to short-circuit parsing in InternalSubsetExtractor. - """ + """Exception raised to short-circuit parsing in InternalSubsetExtractor.""" class InternalSubsetExtractor(ExpatBuilder): - """ - XML processor which can rip out the internal document type subset. - """ + """XML processor which can rip out the internal document type subset.""" subset: str | list[str] | None = None def getSubset(self) -> str: - """ - Return the internal subset as a string. - """ + """Return the internal subset as a string.""" def parseFile(self, file: SupportsRead[ReadableBuffer | str]) -> None: ... # type: ignore[override] def parseString(self, string: str | ReadableBuffer) -> None: ... # type: ignore[override] @@ -211,21 +177,18 @@ class InternalSubsetExtractor(ExpatBuilder): def start_element_handler(self, name: str, attrs: list[str]) -> NoReturn: ... def parse(file: str | SupportsRead[ReadableBuffer | str], namespaces: bool = True) -> Document: - """ - Parse a document, returning the resulting Document node. + """Parse a document, returning the resulting Document node. 'file' may be either a file name or an open file object. """ def parseString(string: str | ReadableBuffer, namespaces: bool = True) -> Document: - """ - Parse a document from a string, returning the resulting + """Parse a document from a string, returning the resulting Document node. """ def parseFragment(file: str | SupportsRead[ReadableBuffer | str], context: Node, namespaces: bool = True) -> DocumentFragment: - """ - Parse a fragment of a document, given the context from which it + """Parse a fragment of a document, given the context from which it was originally extracted. context should be the parent of the node(s) which are in the fragment. @@ -233,13 +196,10 @@ def parseFragment(file: str | SupportsRead[ReadableBuffer | str], context: Node, """ def parseFragmentString(string: str | ReadableBuffer, context: Node, namespaces: bool = True) -> DocumentFragment: - """ - Parse a fragment of a document from a string, given the context + """Parse a fragment of a document from a string, given the context from which it was originally extracted. context should be the parent of the node(s) which are in the fragment. """ def makeBuilder(options: Options) -> ExpatBuilderNS | ExpatBuilder: - """ - Create a builder based on an Options object. - """ + """Create a builder based on an Options object.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/minicompat.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/minicompat.pyi index 8a1ae008c5..026e1db05f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/minicompat.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/minicompat.pyi @@ -17,18 +17,14 @@ StringTypes: tuple[type[str]] class NodeList(list[_T]): @property def length(self) -> int: - """ - The number of nodes in the NodeList. - """ + """The number of nodes in the NodeList.""" def item(self, index: int) -> _T | None: ... class EmptyNodeList(tuple[()]): @property def length(self) -> Literal[0]: - """ - The number of nodes in the NodeList. - """ + """The number of nodes in the NodeList.""" def item(self, index: int) -> None: ... def __add__(self, other: Iterable[_T]) -> NodeList[_T]: ... # type: ignore[override] diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/minidom.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/minidom.pyi index ce485dff96..bac8efb041 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/minidom.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/minidom.pyi @@ -67,14 +67,10 @@ class _UserDataHandler(Protocol): def parse( file: str | SupportsRead[ReadableBuffer | str], parser: XMLReader | None = None, bufsize: int | None = None ) -> Document: - """ - Parse a file into a DOM by filename or file object. - """ + """Parse a file into a DOM by filename or file object.""" def parseString(string: str | ReadableBuffer, parser: XMLReader | None = None) -> Document: - """ - Parse a file into a DOM from a string. - """ + """Parse a file into a DOM from a string.""" @overload def getDOMImplementation(features: None = None) -> DOMImplementation: ... @@ -108,21 +104,15 @@ class Node(xml.dom.Node): @property def firstChild(self) -> _NodesThatAreChildren | None: - """ - First child node, or None. - """ + """First child node, or None.""" @property def lastChild(self) -> _NodesThatAreChildren | None: - """ - Last child node, or None. - """ + """Last child node, or None.""" @property def localName(self) -> str | None: # non-null only for Element and Attr - """ - Namespace-local name of this node. - """ + """Namespace-local name of this node.""" def __bool__(self) -> Literal[True]: ... @overload @@ -202,22 +192,16 @@ class DocumentFragment(Node): childNodes: NodeList[_DocumentFragmentChildren] @property def firstChild(self) -> _DocumentFragmentChildren | None: - """ - First child node, or None. - """ + """First child node, or None.""" @property def lastChild(self) -> _DocumentFragmentChildren | None: - """ - Last child node, or None. - """ + """Last child node, or None.""" namespaceURI: None prefix: None @property def localName(self) -> None: - """ - Namespace-local name of this node. - """ + """Namespace-local name of this node.""" def __init__(self) -> None: ... def insertBefore( # type: ignore[override] @@ -245,22 +229,16 @@ class Attr(Node): childNodes: NodeList[_AttrChildren] @property def firstChild(self) -> _AttrChildren | None: - """ - First child node, or None. - """ + """First child node, or None.""" @property def lastChild(self) -> _AttrChildren | None: - """ - Last child node, or None. - """ + """Last child node, or None.""" namespaceURI: str | None prefix: str | None @property def localName(self) -> str: - """ - Namespace-local name of this attribute. - """ + """Namespace-local name of this attribute.""" name: str value: str specified: bool @@ -272,15 +250,11 @@ class Attr(Node): def unlink(self) -> None: ... @property def isId(self) -> bool: - """ - True if this attribute is an ID. - """ + """True if this attribute is an ID.""" @property def schemaType(self) -> TypeInfo: - """ - Schema type for this attribute. - """ + """Schema type for this attribute.""" def insertBefore(self, newChild: _AttrChildrenPlusFragment, refChild: _AttrChildren | None) -> _AttrChildrenPlusFragment: ... # type: ignore[override] def appendChild(self, node: _AttrChildrenPlusFragment) -> _AttrChildrenPlusFragment: ... # type: ignore[override] @@ -293,8 +267,7 @@ class Attr(Node): # In the DOM, this interface isn't specific to Attr, but our implementation is # because that's the only place we use it. class NamedNodeMap: - """ - The attribute list is a transient interface to the underlying + """The attribute list is a transient interface to the underlying dictionaries. Mutations here will change the underlying element's dictionary. @@ -305,9 +278,7 @@ class NamedNodeMap: def __init__(self, attrs: dict[str, Attr], attrsNS: dict[_NSName, Attr], ownerElement: Element) -> None: ... @property def length(self) -> int: - """ - Number of nodes in the NamedNodeMap. - """ + """Number of nodes in the NamedNodeMap.""" def item(self, index: int) -> Node | None: ... def items(self) -> list[tuple[str, str]]: ... @@ -350,31 +321,23 @@ class Element(Node): nodeValue: None @property def attributes(self) -> NamedNodeMap: # type: ignore[override] - """ - NamedNodeMap of attributes on the element. - """ + """NamedNodeMap of attributes on the element.""" parentNode: Document | Element | DocumentFragment | None nextSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None previousSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None childNodes: NodeList[_ElementChildren] @property def firstChild(self) -> _ElementChildren | None: - """ - First child node, or None. - """ + """First child node, or None.""" @property def lastChild(self) -> _ElementChildren | None: - """ - Last child node, or None. - """ + """Last child node, or None.""" namespaceURI: str | None prefix: str | None @property def localName(self) -> str: - """ - Namespace-local name of this element. - """ + """Namespace-local name of this element.""" schemaType: TypeInfo tagName: str @@ -383,8 +346,7 @@ class Element(Node): ) -> None: ... def unlink(self) -> None: ... def getAttribute(self, attname: str) -> str: - """ - Returns the value of the specified attribute. + """Returns the value of the specified attribute. Returns the value of the element's attribute named attname as a string. An empty string is returned if the element does not @@ -405,8 +367,7 @@ class Element(Node): def removeAttributeNode(self, node: Attr) -> Attr: ... removeAttributeNodeNS = removeAttributeNode def hasAttribute(self, name: str) -> bool: - """ - Checks whether the element has an attribute with the specified name. + """Checks whether the element has an attribute with the specified name. Returns True if the element has an attribute with the specified name. Otherwise, returns False. @@ -414,8 +375,7 @@ class Element(Node): def hasAttributeNS(self, namespaceURI: str | None, localName: str) -> bool: ... def getElementsByTagName(self, name: str) -> NodeList[Element]: - """ - Returns all descendant elements with the given tag name. + """Returns all descendant elements with the given tag name. Returns the list of all descendant elements (not direct children only) with the specified tag name. @@ -423,8 +383,7 @@ class Element(Node): def getElementsByTagNameNS(self, namespaceURI: str | None, localName: str) -> NodeList[Element]: ... def writexml(self, writer: SupportsWrite[str], indent: str = "", addindent: str = "", newl: str = "") -> None: - """ - Write an XML element to a file-like object + """Write an XML element to a file-like object Write the element to the writer object that must provide a write method (e.g. a file or StringIO object). @@ -447,8 +406,7 @@ class Element(Node): def removeChild(self, oldChild: _ElementChildrenVar) -> _ElementChildrenVar: ... # type: ignore[override] class Childless: - """ - Mixin that makes childless-ness easy to implement and avoids + """Mixin that makes childless-ness easy to implement and avoids the complexity of the Node methods that deal with children. """ @@ -456,15 +414,11 @@ class Childless: childNodes: EmptyNodeList @property def firstChild(self) -> None: - """ - The type of the None singleton. - """ + """The type of the None singleton.""" @property def lastChild(self) -> None: - """ - The type of the None singleton. - """ + """The type of the None singleton.""" def appendChild(self, node: _NodesThatAreChildren | DocumentFragment) -> NoReturn: ... def hasChildNodes(self) -> Literal[False]: ... @@ -487,22 +441,16 @@ class ProcessingInstruction(Childless, Node): childNodes: EmptyNodeList @property def firstChild(self) -> None: - """ - The type of the None singleton. - """ + """The type of the None singleton.""" @property def lastChild(self) -> None: - """ - The type of the None singleton. - """ + """The type of the None singleton.""" namespaceURI: None prefix: None @property def localName(self) -> None: - """ - Namespace-local name of this node. - """ + """Namespace-local name of this node.""" target: str data: str @@ -519,18 +467,14 @@ class CharacterData(Childless, Node): @property def localName(self) -> None: - """ - Namespace-local name of this node. - """ + """Namespace-local name of this node.""" ownerDocument: Document | None data: str def __init__(self) -> None: ... @property def length(self) -> int: - """ - Length of the string data. - """ + """Length of the string data.""" def __len__(self) -> int: ... def substringData(self, offset: int, count: int) -> str: ... @@ -551,37 +495,27 @@ class Text(CharacterData): childNodes: EmptyNodeList @property def firstChild(self) -> None: - """ - The type of the None singleton. - """ + """The type of the None singleton.""" @property def lastChild(self) -> None: - """ - The type of the None singleton. - """ + """The type of the None singleton.""" namespaceURI: None prefix: None @property def localName(self) -> None: - """ - Namespace-local name of this node. - """ + """Namespace-local name of this node.""" data: str def splitText(self, offset: int) -> Self: ... def writexml(self, writer: SupportsWrite[str], indent: str = "", addindent: str = "", newl: str = "") -> None: ... def replaceWholeText(self, content: str) -> Self | None: ... @property def isWhitespaceInElementContent(self) -> bool: - """ - True iff this text node contains only whitespace and is in element content. - """ + """True iff this text node contains only whitespace and is in element content.""" @property def wholeText(self) -> str: - """ - The text of all logically-adjacent text nodes. - """ + """The text of all logically-adjacent text nodes.""" class Comment(CharacterData): nodeType: ClassVar[Literal[8]] @@ -595,22 +529,16 @@ class Comment(CharacterData): childNodes: EmptyNodeList @property def firstChild(self) -> None: - """ - The type of the None singleton. - """ + """The type of the None singleton.""" @property def lastChild(self) -> None: - """ - The type of the None singleton. - """ + """The type of the None singleton.""" namespaceURI: None prefix: None @property def localName(self) -> None: - """ - Namespace-local name of this node. - """ + """Namespace-local name of this node.""" def __init__(self, data: str) -> None: ... def writexml(self, writer: SupportsWrite[str], indent: str = "", addindent: str = "", newl: str = "") -> None: ... @@ -640,14 +568,10 @@ class ReadOnlySequentialNamedNodeMap(Generic[_N]): def setNamedItemNS(self, node: Node) -> NoReturn: ... @property def length(self) -> int: - """ - Number of entries in the NamedNodeMap. - """ + """Number of entries in the NamedNodeMap.""" class Identified: - """ - Mix-in class that supports the publicId and systemId attributes. - """ + """Mix-in class that supports the publicId and systemId attributes.""" publicId: str | None systemId: str | None @@ -664,22 +588,16 @@ class DocumentType(Identified, Childless, Node): childNodes: EmptyNodeList @property def firstChild(self) -> None: - """ - The type of the None singleton. - """ + """The type of the None singleton.""" @property def lastChild(self) -> None: - """ - The type of the None singleton. - """ + """The type of the None singleton.""" namespaceURI: None prefix: None @property def localName(self) -> None: - """ - Namespace-local name of this node. - """ + """Namespace-local name of this node.""" name: str | None internalSubset: str | None entities: ReadOnlySequentialNamedNodeMap[Entity] @@ -701,22 +619,16 @@ class Entity(Identified, Node): childNodes: NodeList[_EntityChildren] @property def firstChild(self) -> _EntityChildren | None: - """ - First child node, or None. - """ + """First child node, or None.""" @property def lastChild(self) -> _EntityChildren | None: - """ - Last child node, or None. - """ + """Last child node, or None.""" namespaceURI: None prefix: None @property def localName(self) -> None: - """ - Namespace-local name of this node. - """ + """Namespace-local name of this node.""" actualEncoding: str | None encoding: str | None version: str | None @@ -740,22 +652,16 @@ class Notation(Identified, Childless, Node): childNodes: EmptyNodeList @property def firstChild(self) -> None: - """ - The type of the None singleton. - """ + """The type of the None singleton.""" @property def lastChild(self) -> None: - """ - The type of the None singleton. - """ + """The type of the None singleton.""" namespaceURI: None prefix: None @property def localName(self) -> None: - """ - Namespace-local name of this node. - """ + """Namespace-local name of this node.""" def __init__(self, name: str, publicId: str | None, systemId: str | None) -> None: ... @@ -766,8 +672,7 @@ class DOMImplementation(DOMImplementationLS): def getInterface(self, feature: str) -> Self | None: ... class ElementInfo: - """ - Object that represents content-model information for an element. + """Object that represents content-model information for an element. This implementation is not expected to be used in practice; DOM builders should provide implementations which do the right thing @@ -780,20 +685,15 @@ class ElementInfo: def getAttributeTypeNS(self, namespaceURI: str | None, localName: str) -> TypeInfo: ... def isElementContent(self) -> bool: ... def isEmpty(self) -> bool: - """ - Returns true iff this element is declared to have an EMPTY + """Returns true iff this element is declared to have an EMPTY content model. """ def isId(self, aname: str) -> bool: - """ - Returns true iff the named attribute is a DTD-style ID. - """ + """Returns true iff the named attribute is a DTD-style ID.""" def isIdNS(self, namespaceURI: str | None, localName: str) -> bool: - """ - Returns true iff the identified attribute is a DTD-style ID. - """ + """Returns true iff the identified attribute is a DTD-style ID.""" _DocumentChildrenPlusFragment = TypeVar("_DocumentChildrenPlusFragment", bound=_DocumentChildren | DocumentFragment) @@ -809,22 +709,16 @@ class Document(Node, DocumentLS): childNodes: NodeList[_DocumentChildren] @property def firstChild(self) -> _DocumentChildren | None: - """ - First child node, or None. - """ + """First child node, or None.""" @property def lastChild(self) -> _DocumentChildren | None: - """ - Last child node, or None. - """ + """Last child node, or None.""" namespaceURI: None prefix: None @property def localName(self) -> None: - """ - Namespace-local name of this node. - """ + """Namespace-local name of this node.""" implementation: DOMImplementation actualEncoding: str | None encoding: str | None diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/pulldom.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/pulldom.pyi index ee8a70ef22..aef911a90f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/pulldom.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/pulldom.pyi @@ -70,9 +70,7 @@ class PullDOM(ContentHandler): def buildDocument(self, uri: str | None, tagname: str | None) -> Element: ... def endDocument(self) -> None: ... def clear(self) -> None: - """ - clear(): Explicitly release parsing structures - """ + """clear(): Explicitly release parsing structures""" class ErrorHandler: def warning(self, exception: BaseException) -> None: ... @@ -94,9 +92,7 @@ class DOMEventStream: def expandNode(self, node: Document) -> None: ... def reset(self) -> None: ... def clear(self) -> None: - """ - clear(): Explicitly release parsing objects - """ + """clear(): Explicitly release parsing objects""" class SAX2DOM(PullDOM): def startElementNS(self, name: _NSName, tagName: str | None, attrs: AttributesNSImpl) -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/xmlbuilder.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/xmlbuilder.pyi index d36d9b0cdd..8fa87d80d9 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/xmlbuilder.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xml/dom/xmlbuilder.pyi @@ -9,8 +9,7 @@ from xml.dom.minidom import Document, Node, _DOMErrorHandler __all__ = ["DOMBuilder", "DOMEntityResolver", "DOMInputSource"] class Options: - """ - Features object that has variables set for each DOMBuilder feature. + """Features object that has variables set for each DOMBuilder feature. The DOMBuilder class uses an instance of this class to pass settings to the ExpatBuilder class. @@ -67,8 +66,7 @@ class DOMInputSource: baseURI: str | None class DOMBuilderFilter: - """ - Element filter which can be used to tailor construction of + """Element filter which can be used to tailor construction of a DOM instance. """ @@ -81,9 +79,7 @@ class DOMBuilderFilter: def startContainer(self, element: Node) -> Literal[1, 2, 3, 4]: ... class DocumentLS: - """ - Mixin to create documents that conform to the load/save spec. - """ + """Mixin to create documents that conform to the load/save spec.""" async_: bool def abort(self) -> NoReturn: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xml/etree/ElementTree.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xml/etree/ElementTree.pyi index 3a1a9ad9f1..19138824c3 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xml/etree/ElementTree.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xml/etree/ElementTree.pyi @@ -83,9 +83,7 @@ class ParseError(SyntaxError): # In reality it works based on `.tag` attribute duck typing. def iselement(element: object) -> TypeGuard[Element]: - """ - Return True if *element* appears to be an Element. - """ + """Return True if *element* appears to be an Element.""" @overload def canonicalize( @@ -101,8 +99,7 @@ def canonicalize( exclude_attrs: Iterable[str] | None = None, exclude_tags: Iterable[str] | None = None, ) -> str: - """ - Convert XML to its C14N 2.0 serialised form. + """Convert XML to its C14N 2.0 serialised form. If *out* is provided, it must be a file or file-like object that receives the serialised canonical XML output (text, not bytes) through its ``.write()`` @@ -174,29 +171,21 @@ class Element(Generic[_Tag]): def __copy__(self) -> Element[_Tag]: ... # returns the type of self in Python impl, but not in C impl def __deepcopy__(self, memo: Any, /) -> Element: ... # Only exists in C impl def __delitem__(self, key: SupportsIndex | slice, /) -> None: - """ - Delete self[key]. - """ + """Delete self[key].""" @overload def __getitem__(self, key: SupportsIndex, /) -> Element: - """ - Return self[key]. - """ + """Return self[key].""" @overload def __getitem__(self, key: slice, /) -> list[Element]: ... def __len__(self) -> int: - """ - Return len(self). - """ + """Return len(self).""" # Doesn't actually exist at runtime, but instance of the class are indeed iterable due to __getitem__. def __iter__(self) -> Iterator[Element]: ... @overload def __setitem__(self, key: SupportsIndex, value: Element, /) -> None: - """ - Set self[key] to value. - """ + """Set self[key] to value.""" @overload def __setitem__(self, key: slice, value: Iterable[Element], /) -> None: ... @@ -204,14 +193,11 @@ class Element(Generic[_Tag]): # Doesn't really exist in earlier versions, where __len__ is called implicitly instead @deprecated("Testing an element's truth value is deprecated.") def __bool__(self) -> bool: - """ - True if self else False - """ + """True if self else False""" def SubElement(parent: Element, tag: str, attrib: dict[str, str] = ..., **extra: str) -> Element: ... def Comment(text: str | None = None) -> _CallableElement: - """ - Comment element factory. + """Comment element factory. This function creates a special element which the standard serializer serializes as an XML comment. @@ -220,8 +206,7 @@ def Comment(text: str | None = None) -> _CallableElement: """ def ProcessingInstruction(target: str, text: str | None = None) -> _CallableElement: - """ - Processing Instruction element factory. + """Processing Instruction element factory. This function creates a special element which the standard serializer serializes as an XML comment. @@ -233,8 +218,7 @@ def ProcessingInstruction(target: str, text: str | None = None) -> _CallableElem PI = ProcessingInstruction class QName: - """ - Qualified name wrapper. + """Qualified name wrapper. This class can be used to wrap a QName attribute value in order to get proper namespace handing on output. @@ -259,8 +243,7 @@ class QName: _Root = TypeVar("_Root", Element, Element | None, default=Element | None) class ElementTree(Generic[_Root]): - """ - An XML element hierarchy. + """An XML element hierarchy. This class also provides support for serialization to and from standard XML. @@ -272,13 +255,10 @@ class ElementTree(Generic[_Root]): def __init__(self, element: Element | None = None, file: _FileRead | None = None) -> None: ... def getroot(self) -> _Root: - """ - Return root element of this tree. - """ + """Return root element of this tree.""" def parse(self, source: _FileRead, parser: XMLParser | None = None) -> Element: - """ - Load external XML document into element tree. + """Load external XML document into element tree. *source* is a file name or file object, *parser* is an optional parser instance that defaults to XMLParser. @@ -289,8 +269,7 @@ class ElementTree(Generic[_Root]): """ def iter(self, tag: str | None = None) -> Generator[Element, None, None]: - """ - Create and return tree iterator for the root element. + """Create and return tree iterator for the root element. The iterator loops over all elements in this tree, in document order. @@ -299,8 +278,7 @@ class ElementTree(Generic[_Root]): """ def find(self, path: str, namespaces: dict[str, str] | None = None) -> Element | None: - """ - Find first matching element by tag name or path. + """Find first matching element by tag name or path. Same as getroot().find(path), which is Element.find() @@ -312,8 +290,7 @@ class ElementTree(Generic[_Root]): @overload def findtext(self, path: str, default: None = None, namespaces: dict[str, str] | None = None) -> str | None: - """ - Find first matching element by tag name or path. + """Find first matching element by tag name or path. Same as getroot().findtext(path), which is Element.findtext() @@ -326,8 +303,7 @@ class ElementTree(Generic[_Root]): @overload def findtext(self, path: str, default: _T, namespaces: dict[str, str] | None = None) -> _T | str: ... def findall(self, path: str, namespaces: dict[str, str] | None = None) -> list[Element]: - """ - Find all matching subelements by tag name or path. + """Find all matching subelements by tag name or path. Same as getroot().findall(path), which is Element.findall(). @@ -339,8 +315,7 @@ class ElementTree(Generic[_Root]): @overload def iterfind(self, path: Literal[""], namespaces: dict[str, str] | None = None) -> None: # type: ignore[overload-overlap] - """ - Find all matching subelements by tag name or path. + """Find all matching subelements by tag name or path. Same as getroot().iterfind(path), which is element.iterfind() @@ -362,8 +337,7 @@ class ElementTree(Generic[_Root]): *, short_empty_elements: bool = True, ) -> None: - """ - Write element tree to a file as XML. + """Write element tree to a file as XML. Arguments: *file_or_filename* -- file name or a file object opened for writing @@ -391,8 +365,7 @@ class ElementTree(Generic[_Root]): HTML_EMPTY: set[str] def register_namespace(prefix: str, uri: str) -> None: - """ - Register a namespace prefix. + """Register a namespace prefix. The registry is global, and any existing mapping for either the given prefix or the namespace URI will be removed. @@ -413,8 +386,7 @@ def tostring( default_namespace: str | None = None, short_empty_elements: bool = True, ) -> bytes: - """ - Generate string representation of XML element. + """Generate string representation of XML element. All subelements are included. If encoding is "unicode", a string is returned. Otherwise a bytestring is returned. @@ -478,8 +450,7 @@ def tostringlist( short_empty_elements: bool = True, ) -> list[Any]: ... def dump(elem: Element | ElementTree[Any]) -> None: - """ - Write element tree or element structure to sys.stdout. + """Write element tree or element structure to sys.stdout. This function should be used for debugging only. @@ -489,8 +460,7 @@ def dump(elem: Element | ElementTree[Any]) -> None: """ def indent(tree: Element | ElementTree[Any], space: str = " ", level: int = 0) -> None: - """ - Indent an XML document by inserting newlines and indentation space + """Indent an XML document by inserting newlines and indentation space after elements. *tree* is the ElementTree or Element to modify. The (root) element @@ -506,8 +476,7 @@ def indent(tree: Element | ElementTree[Any], space: str = " ", level: int = 0) """ def parse(source: _FileRead, parser: XMLParser[Any] | None = None) -> ElementTree[Element]: - """ - Parse XML document into element tree. + """Parse XML document into element tree. *source* is a filename or file object containing XML data, *parser* is an optional parser instance defaulting to XMLParser. @@ -525,8 +494,7 @@ class _IterParseIterator(Iterator[tuple[str, Element]], Protocol): def __del__(self) -> None: ... def iterparse(source: _FileRead, events: Sequence[str] | None = None, parser: XMLParser | None = None) -> _IterParseIterator: - """ - Incrementally parse XML document into ElementTree. + """Incrementally parse XML document into ElementTree. This class also reports what's going on to the user based on the *events* it is initialized with. The supported events are the strings @@ -545,21 +513,17 @@ _EventQueue: TypeAlias = tuple[str] | tuple[str, tuple[str, str]] | tuple[str, N class XMLPullParser(Generic[_E]): def __init__(self, events: Sequence[str] | None = None, *, _parser: XMLParser[_E] | None = None) -> None: ... def feed(self, data: str | ReadableBuffer) -> None: - """ - Feed encoded data to parser. - """ + """Feed encoded data to parser.""" def close(self) -> None: - """ - Finish feeding data to parser. + """Finish feeding data to parser. Unlike XMLParser, does not return the root element. Use read_events() to consume elements from XMLPullParser. """ def read_events(self) -> Iterator[_EventQueue | tuple[str, _E]]: - """ - Return an iterator over currently available (event, elem) pairs. + """Return an iterator over currently available (event, elem) pairs. Events are consumed from the internal event queue as they are retrieved from the iterator. @@ -568,8 +532,7 @@ class XMLPullParser(Generic[_E]): def flush(self) -> None: ... def XML(text: str | ReadableBuffer, parser: XMLParser | None = None) -> Element: - """ - Parse XML document from string constant. + """Parse XML document from string constant. This function can be used to embed "XML Literals" in Python code. @@ -580,8 +543,7 @@ def XML(text: str | ReadableBuffer, parser: XMLParser | None = None) -> Element: """ def XMLID(text: str | ReadableBuffer, parser: XMLParser | None = None) -> tuple[Element, dict[str, Element]]: - """ - Parse XML document from string constant for its IDs. + """Parse XML document from string constant for its IDs. *text* is a string containing XML data, *parser* is an optional parser instance, defaulting to the standard XMLParser. @@ -594,8 +556,7 @@ def XMLID(text: str | ReadableBuffer, parser: XMLParser | None = None) -> tuple[ fromstring = XML def fromstringlist(sequence: Sequence[str | ReadableBuffer], parser: XMLParser | None = None) -> Element: - """ - Parse XML document from sequence of string fragments. + """Parse XML document from sequence of string fragments. *sequence* is a list of other sequence, *parser* is an optional parser instance, defaulting to the standard XMLParser. @@ -639,8 +600,7 @@ class TreeBuilder: def pi(self, target: str, text: str | None = None, /) -> Element[Any]: ... class C14NWriterTarget: - """ - Canonicalization writer target for the XMLParser. + """Canonicalization writer target for the XMLParser. Serialises parse events to XML C14N 2.0. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/__init__.pyi index b6bbdd5517..e29ad16a3c 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/__init__.pyi @@ -43,8 +43,7 @@ _Source: TypeAlias = StrPath | _SupportsReadClose[bytes] | _SupportsReadClose[st default_parser_list: list[str] def make_parser(parser_list: Iterable[str] = ()) -> XMLReader: - """ - Creates and returns a SAX parser. + """Creates and returns a SAX parser. Creates the first parser it is able to instantiate of the ones given in the iterable created by chaining parser_list and diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/_exceptions.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/_exceptions.pyi index 8117e571d1..96f8bf7cb9 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/_exceptions.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/_exceptions.pyi @@ -6,8 +6,7 @@ from typing import NoReturn from xml.sax.xmlreader import Locator class SAXException(Exception): - """ - Encapsulate an XML error or warning. This class can contain + """Encapsulate an XML error or warning. This class can contain basic error or warning information from either the XML parser or the application: you can subclass it to provide additional functionality, or to add localization. Note that although you will @@ -18,30 +17,23 @@ class SAXException(Exception): """ def __init__(self, msg: str, exception: Exception | None = None) -> None: - """ - Creates an exception. The message is required, but the exception + """Creates an exception. The message is required, but the exception is optional. """ def getMessage(self) -> str: - """ - Return a message for this exception. - """ + """Return a message for this exception.""" def getException(self) -> Exception | None: - """ - Return the embedded exception, or None if there was none. - """ + """Return the embedded exception, or None if there was none.""" def __getitem__(self, ix: object) -> NoReturn: - """ - Avoids weird error messages if someone does exception[ix] by + """Avoids weird error messages if someone does exception[ix] by mistake, since Exception has __getitem__ defined. """ class SAXParseException(SAXException): - """ - Encapsulate an XML parse error or warning. + """Encapsulate an XML parse error or warning. This exception will include information for locating the error in the original XML document. Note that although the application will @@ -55,34 +47,24 @@ class SAXParseException(SAXException): """ def __init__(self, msg: str, exception: Exception | None, locator: Locator) -> None: - """ - Creates the exception. The exception parameter is allowed to be None. - """ + """Creates the exception. The exception parameter is allowed to be None.""" def getColumnNumber(self) -> int | None: - """ - The column number of the end of the text where the exception + """The column number of the end of the text where the exception occurred. """ def getLineNumber(self) -> int | None: - """ - The line number of the end of the text where the exception occurred. - """ + """The line number of the end of the text where the exception occurred.""" def getPublicId(self) -> str | None: - """ - Get the public identifier of the entity where the exception occurred. - """ + """Get the public identifier of the entity where the exception occurred.""" def getSystemId(self) -> str | None: - """ - Get the system identifier of the entity where the exception occurred. - """ + """Get the system identifier of the entity where the exception occurred.""" class SAXNotRecognizedException(SAXException): - """ - Exception class for an unrecognized identifier. + """Exception class for an unrecognized identifier. An XMLReader will raise this exception when it is confronted with an unrecognized feature or property. SAX applications and extensions may @@ -90,8 +72,7 @@ class SAXNotRecognizedException(SAXException): """ class SAXNotSupportedException(SAXException): - """ - Exception class for an unsupported operation. + """Exception class for an unsupported operation. An XMLReader will raise this exception when a service it cannot perform is requested (specifically setting a state or value). SAX @@ -100,8 +81,7 @@ class SAXNotSupportedException(SAXException): """ class SAXReaderNotAvailable(SAXNotSupportedException): - """ - Exception class for a missing driver. + """Exception class for a missing driver. An XMLReader module (driver) should raise this exception when it is first imported, e.g. when a support module cannot be imported. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/expatreader.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/expatreader.pyi index 3ca70f6c78..37cd77e100 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/expatreader.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/expatreader.pyi @@ -1,4 +1,5 @@ """ + SAX driver for the pyexpat C module. This driver works with pyexpat.__version__ == '2.22'. """ @@ -25,8 +26,7 @@ class _ClosedParser: ErrorLineNumber: int class ExpatLocator(xmlreader.Locator): - """ - Locator for use with the ExpatParser class. + """Locator for use with the ExpatParser class. This uses a weak reference to the parser object to avoid creating a circular reference between the parser and the content handler. @@ -39,15 +39,11 @@ class ExpatLocator(xmlreader.Locator): def getSystemId(self) -> str | None: ... class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator): - """ - SAX driver for the pyexpat C module. - """ + """SAX driver for the pyexpat C module.""" def __init__(self, namespaceHandling: _BoolType = 0, bufsize: int = 65516) -> None: ... def parse(self, source: xmlreader.InputSource | _Source) -> None: - """ - Parse an XML document from a URL or an InputSource. - """ + """Parse an XML document from a URL or an InputSource.""" def prepareParser(self, source: xmlreader.InputSource) -> None: ... def setContentHandler(self, handler: _ContentHandlerProtocol) -> None: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/handler.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/handler.pyi index ba00e1a87a..77e0970532 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/handler.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/handler.pyi @@ -1,4 +1,5 @@ """ + This module contains the core classes of version 2.0 of SAX for Python. This file provides only default classes with absolutely minimum functionality, from which drivers and applications can be subclassed. @@ -22,8 +23,7 @@ class _ErrorHandlerProtocol(Protocol): # noqa: Y046 # Protocol is not used def warning(self, exception: BaseException) -> None: ... class ErrorHandler: - """ - Basic interface for SAX error handlers. + """Basic interface for SAX error handlers. If you create an object that implements this interface, then register the object with your XMLReader, the parser will call the @@ -34,19 +34,13 @@ class ErrorHandler: """ def error(self, exception: BaseException) -> NoReturn: - """ - Handle a recoverable error. - """ + """Handle a recoverable error.""" def fatalError(self, exception: BaseException) -> NoReturn: - """ - Handle a non-recoverable error. - """ + """Handle a non-recoverable error.""" def warning(self, exception: BaseException) -> None: - """ - Handle a warning. - """ + """Handle a warning.""" @type_check_only class _ContentHandlerProtocol(Protocol): # noqa: Y046 # Protocol is not used @@ -65,8 +59,7 @@ class _ContentHandlerProtocol(Protocol): # noqa: Y046 # Protocol is not used def skippedEntity(self, name: str) -> None: ... class ContentHandler: - """ - Interface for receiving logical document content events. + """Interface for receiving logical document content events. This is the main callback interface in SAX, and the one most important to applications. The order of events in this interface @@ -74,8 +67,7 @@ class ContentHandler: """ def setDocumentLocator(self, locator: xmlreader.Locator) -> None: - """ - Called by the parser to give the application a locator for + """Called by the parser to give the application a locator for locating the origin of document events. SAX parsers are strongly encouraged (though not absolutely @@ -98,8 +90,7 @@ class ContentHandler: """ def startDocument(self) -> None: - """ - Receive notification of the beginning of a document. + """Receive notification of the beginning of a document. The SAX parser will invoke this method only once, before any other methods in this interface or in DTDHandler (except for @@ -107,8 +98,7 @@ class ContentHandler: """ def endDocument(self) -> None: - """ - Receive notification of the end of a document. + """Receive notification of the end of a document. The SAX parser will invoke this method only once, and it will be the last method invoked during the parse. The parser shall @@ -118,8 +108,7 @@ class ContentHandler: """ def startPrefixMapping(self, prefix: str | None, uri: str) -> None: - """ - Begin the scope of a prefix-URI Namespace mapping. + """Begin the scope of a prefix-URI Namespace mapping. The information from this event is not necessary for normal Namespace processing: the SAX XML reader will automatically @@ -143,8 +132,7 @@ class ContentHandler: """ def endPrefixMapping(self, prefix: str | None) -> None: - """ - End the scope of a prefix-URI mapping. + """End the scope of a prefix-URI mapping. See startPrefixMapping for details. This event will always occur after the corresponding endElement event, but the order @@ -152,8 +140,7 @@ class ContentHandler: """ def startElement(self, name: str, attrs: xmlreader.AttributesImpl) -> None: - """ - Signals the start of an element in non-namespace mode. + """Signals the start of an element in non-namespace mode. The name parameter contains the raw XML 1.0 name of the element type as a string and the attrs parameter holds an @@ -162,16 +149,14 @@ class ContentHandler: """ def endElement(self, name: str) -> None: - """ - Signals the end of an element in non-namespace mode. + """Signals the end of an element in non-namespace mode. The name parameter contains the name of the element type, just as with the startElement event. """ def startElementNS(self, name: tuple[str | None, str], qname: str | None, attrs: xmlreader.AttributesNSImpl) -> None: - """ - Signals the start of an element in namespace mode. + """Signals the start of an element in namespace mode. The name parameter contains the name of the element type as a (uri, localname) tuple, the qname parameter the raw XML 1.0 @@ -184,16 +169,14 @@ class ContentHandler: """ def endElementNS(self, name: tuple[str | None, str], qname: str | None) -> None: - """ - Signals the end of an element in namespace mode. + """Signals the end of an element in namespace mode. The name parameter contains the name of the element type, just as with the startElementNS event. """ def characters(self, content: str) -> None: - """ - Receive notification of character data. + """Receive notification of character data. The Parser will call this method to report each chunk of character data. SAX parsers may return all contiguous @@ -204,8 +187,7 @@ class ContentHandler: """ def ignorableWhitespace(self, whitespace: str) -> None: - """ - Receive notification of ignorable whitespace in element content. + """Receive notification of ignorable whitespace in element content. Validating Parsers must use this method to report each chunk of ignorable whitespace (see the W3C XML 1.0 recommendation, @@ -220,8 +202,7 @@ class ContentHandler: """ def processingInstruction(self, target: str, data: str) -> None: - """ - Receive notification of a processing instruction. + """Receive notification of a processing instruction. The Parser will invoke this method once for each processing instruction found: note that processing instructions may occur @@ -233,8 +214,7 @@ class ContentHandler: """ def skippedEntity(self, name: str) -> None: - """ - Receive notification of a skipped entity. + """Receive notification of a skipped entity. The Parser will invoke this method once for each entity skipped. Non-validating processors may skip entities if they @@ -252,30 +232,24 @@ class _DTDHandlerProtocol(Protocol): # noqa: Y046 # Protocol is not used def unparsedEntityDecl(self, name: str, publicId: str | None, systemId: str, ndata: str) -> None: ... class DTDHandler: - """ - Handle DTD events. + """Handle DTD events. This interface specifies only those DTD events required for basic parsing (unparsed entities and attributes). """ def notationDecl(self, name: str, publicId: str | None, systemId: str) -> None: - """ - Handle a notation declaration event. - """ + """Handle a notation declaration event.""" def unparsedEntityDecl(self, name: str, publicId: str | None, systemId: str, ndata: str) -> None: - """ - Handle an unparsed entity declaration event. - """ + """Handle an unparsed entity declaration event.""" @type_check_only class _EntityResolverProtocol(Protocol): # noqa: Y046 # Protocol is not used def resolveEntity(self, publicId: str | None, systemId: str) -> str: ... class EntityResolver: - """ - Basic interface for resolving entities. If you create an object + """Basic interface for resolving entities. If you create an object implementing this interface, then register the object with your Parser, the parser will call the method in your object to resolve all external entities. Note that DefaultHandler implements @@ -283,8 +257,7 @@ class EntityResolver: """ def resolveEntity(self, publicId: str | None, systemId: str) -> str: - """ - Resolve the system identifier of an entity and return either + """Resolve the system identifier of an entity and return either the system identifier to read from as a string, or an InputSource to read from. """ @@ -306,8 +279,7 @@ all_properties: list[str] if sys.version_info >= (3, 10): class LexicalHandler: - """ - Optional SAX2 handler for lexical events. + """Optional SAX2 handler for lexical events. This handler is used to obtain lexical information about an XML document, that is, information about how the document was encoded @@ -321,16 +293,14 @@ if sys.version_info >= (3, 10): """ def comment(self, content: str) -> None: - """ - Reports a comment anywhere in the document (including the + """Reports a comment anywhere in the document (including the DTD and outside the document element). content is a string that holds the contents of the comment. """ def startDTD(self, name: str, public_id: str | None, system_id: str | None) -> None: - """ - Report the start of the DTD declarations, if the document + """Report the start of the DTD declarations, if the document has an associated DTD. A startEntity event will be reported before declaration events @@ -344,19 +314,14 @@ if sys.version_info >= (3, 10): """ def endDTD(self) -> None: - """ - Signals the end of DTD declarations. - """ + """Signals the end of DTD declarations.""" def startCDATA(self) -> None: - """ - Reports the beginning of a CDATA marked section. + """Reports the beginning of a CDATA marked section. The contents of the CDATA marked section will be reported through the characters event. """ def endCDATA(self) -> None: - """ - Reports the end of a CDATA marked section. - """ + """Reports the end of a CDATA marked section.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/saxutils.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/saxutils.pyi index e2462c2a36..88ae28c3b9 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/saxutils.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/saxutils.pyi @@ -11,8 +11,7 @@ from typing import Literal, NoReturn from xml.sax import _Source, handler, xmlreader def escape(data: str, entities: Mapping[str, str] = {}) -> str: - """ - Escape &, <, and > in a string of data. + """Escape &, <, and > in a string of data. You can escape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be @@ -20,8 +19,7 @@ def escape(data: str, entities: Mapping[str, str] = {}) -> str: """ def unescape(data: str, entities: Mapping[str, str] = {}) -> str: - """ - Unescape &, <, and > in a string of data. + """Unescape &, <, and > in a string of data. You can unescape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be @@ -29,8 +27,7 @@ def unescape(data: str, entities: Mapping[str, str] = {}) -> str: """ def quoteattr(data: str, entities: Mapping[str, str] = {}) -> str: - """ - Escape and quote an attribute value. + """Escape and quote an attribute value. Escape &, <, and > in a string of data, then quote it for use as an attribute value. The " character will be escaped as well, if @@ -49,9 +46,7 @@ class XMLGenerator(handler.ContentHandler): short_empty_elements: bool = False, ) -> None: ... def _qname(self, name: tuple[str | None, str]) -> str: - """ - Builds a qualified name from a (ns_url, localname) pair - """ + """Builds a qualified name from a (ns_url, localname) pair""" def startDocument(self) -> None: ... def endDocument(self) -> None: ... @@ -66,8 +61,7 @@ class XMLGenerator(handler.ContentHandler): def processingInstruction(self, target: str, data: str) -> None: ... class XMLFilterBase(xmlreader.XMLReader): - """ - This class is designed to sit between an XMLReader and the + """This class is designed to sit between an XMLReader and the client application's event handlers. By default, it does nothing but pass requests up to the reader and events on to the handlers unmodified, but subclasses can override specific methods to modify @@ -111,7 +105,6 @@ class XMLFilterBase(xmlreader.XMLReader): def setParent(self, parent: xmlreader.XMLReader) -> None: ... def prepare_input_source(source: xmlreader.InputSource | _Source, base: str = "") -> xmlreader.InputSource: - """ - This function takes an InputSource and an optional base URL and + """This function takes an InputSource and an optional base URL and returns a fully resolved InputSource object ready for reading. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/xmlreader.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/xmlreader.pyi index 04af644b28..f6285d61de 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/xmlreader.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xml/sax/xmlreader.pyi @@ -11,8 +11,7 @@ from xml.sax import _Source, _SupportsReadClose from xml.sax.handler import _ContentHandlerProtocol, _DTDHandlerProtocol, _EntityResolverProtocol, _ErrorHandlerProtocol class XMLReader: - """ - Interface for reading an XML document using callbacks. + """Interface for reading an XML document using callbacks. XMLReader is the interface that an XML parser's SAX2 driver must implement. This interface allows an application to set and query @@ -26,53 +25,34 @@ class XMLReader: """ def parse(self, source: InputSource | _Source) -> None: - """ - Parse an XML document from a system identifier or an InputSource. - """ + """Parse an XML document from a system identifier or an InputSource.""" def getContentHandler(self) -> _ContentHandlerProtocol: - """ - Returns the current ContentHandler. - """ + """Returns the current ContentHandler.""" def setContentHandler(self, handler: _ContentHandlerProtocol) -> None: - """ - Registers a new object to receive document content events. - """ + """Registers a new object to receive document content events.""" def getDTDHandler(self) -> _DTDHandlerProtocol: - """ - Returns the current DTD handler. - """ + """Returns the current DTD handler.""" def setDTDHandler(self, handler: _DTDHandlerProtocol) -> None: - """ - Register an object to receive basic DTD-related events. - """ + """Register an object to receive basic DTD-related events.""" def getEntityResolver(self) -> _EntityResolverProtocol: - """ - Returns the current EntityResolver. - """ + """Returns the current EntityResolver.""" def setEntityResolver(self, resolver: _EntityResolverProtocol) -> None: - """ - Register an object to resolve external entities. - """ + """Register an object to resolve external entities.""" def getErrorHandler(self) -> _ErrorHandlerProtocol: - """ - Returns the current ErrorHandler. - """ + """Returns the current ErrorHandler.""" def setErrorHandler(self, handler: _ErrorHandlerProtocol) -> None: - """ - Register an object to receive error-message events. - """ + """Register an object to receive error-message events.""" def setLocale(self, locale: str) -> None: - """ - Allow an application to set the locale for errors and warnings. + """Allow an application to set the locale for errors and warnings. SAX parsers are not required to provide localization for errors and warnings; if they cannot support the requested locale, @@ -81,28 +61,19 @@ class XMLReader: """ def getFeature(self, name: str) -> Literal[0, 1] | bool: - """ - Looks up and returns the state of a SAX2 feature. - """ + """Looks up and returns the state of a SAX2 feature.""" def setFeature(self, name: str, state: Literal[0, 1] | bool) -> None: - """ - Sets the state of a SAX2 feature. - """ + """Sets the state of a SAX2 feature.""" def getProperty(self, name: str) -> object: - """ - Looks up and returns the value of a SAX2 property. - """ + """Looks up and returns the value of a SAX2 property.""" def setProperty(self, name: str, value: object) -> None: - """ - Sets the value of a SAX2 property. - """ + """Sets the value of a SAX2 property.""" class IncrementalParser(XMLReader): - """ - This interface adds three extra methods to the XMLReader + """This interface adds three extra methods to the XMLReader interface that allow XML parsers to support incremental parsing. Support for this interface is optional, since not all underlying XML parsers support this functionality. @@ -125,8 +96,7 @@ class IncrementalParser(XMLReader): def __init__(self, bufsize: int = 65536) -> None: ... def parse(self, source: InputSource | _Source) -> None: ... def feed(self, data: str | ReadableBuffer) -> None: - """ - This method gives the raw XML data in the data parameter to + """This method gives the raw XML data in the data parameter to the parser and makes it parse the data, emitting the corresponding events. It is allowed for XML constructs to be split across several calls to feed. @@ -135,14 +105,12 @@ class IncrementalParser(XMLReader): """ def prepareParser(self, source: InputSource) -> None: - """ - This method is called by the parse implementation to allow + """This method is called by the parse implementation to allow the SAX 2.0 driver to prepare itself for parsing. """ def close(self) -> None: - """ - This method is called when the entire XML document has been + """This method is called when the entire XML document has been passed to the parser through the feed method, to notify the parser that there are no more data. This allows the parser to do the final checks on the document and empty the internal @@ -155,44 +123,33 @@ class IncrementalParser(XMLReader): """ def reset(self) -> None: - """ - This method is called after close has been called to reset + """This method is called after close has been called to reset the parser so that it is ready to parse new documents. The results of calling parse or feed after close without calling reset are undefined. """ class Locator: - """ - Interface for associating a SAX event with a document + """Interface for associating a SAX event with a document location. A locator object will return valid results only during calls to DocumentHandler methods; at any other time, the results are unpredictable. """ def getColumnNumber(self) -> int | None: - """ - Return the column number where the current event ends. - """ + """Return the column number where the current event ends.""" def getLineNumber(self) -> int | None: - """ - Return the line number where the current event ends. - """ + """Return the line number where the current event ends.""" def getPublicId(self) -> str | None: - """ - Return the public identifier for the current event. - """ + """Return the public identifier for the current event.""" def getSystemId(self) -> str | None: - """ - Return the system identifier for the current event. - """ + """Return the system identifier for the current event.""" class InputSource: - """ - Encapsulation of the information needed by the XMLReader to + """Encapsulation of the information needed by the XMLReader to read entities. This class may include information about the public identifier, @@ -210,28 +167,19 @@ class InputSource: def __init__(self, system_id: str | None = None) -> None: ... def setPublicId(self, public_id: str | None) -> None: - """ - Sets the public identifier of this InputSource. - """ + """Sets the public identifier of this InputSource.""" def getPublicId(self) -> str | None: - """ - Returns the public identifier of this InputSource. - """ + """Returns the public identifier of this InputSource.""" def setSystemId(self, system_id: str | None) -> None: - """ - Sets the system identifier of this InputSource. - """ + """Sets the system identifier of this InputSource.""" def getSystemId(self) -> str | None: - """ - Returns the system identifier of this InputSource. - """ + """Returns the system identifier of this InputSource.""" def setEncoding(self, encoding: str | None) -> None: - """ - Sets the character encoding of this InputSource. + """Sets the character encoding of this InputSource. The encoding must be a string acceptable for an XML encoding declaration (see section 4.3.3 of the XML recommendation). @@ -241,13 +189,10 @@ class InputSource: """ def getEncoding(self) -> str | None: - """ - Get the character encoding of this InputSource. - """ + """Get the character encoding of this InputSource.""" def setByteStream(self, bytefile: _SupportsReadClose[bytes] | None) -> None: - """ - Set the byte stream (a Python file-like object which does + """Set the byte stream (a Python file-like object which does not perform byte-to-character conversion) for this input source. @@ -260,16 +205,14 @@ class InputSource: """ def getByteStream(self) -> _SupportsReadClose[bytes] | None: - """ - Get the byte stream for this input source. + """Get the byte stream for this input source. The getEncoding method will return the character encoding for this byte stream, or None if unknown. """ def setCharacterStream(self, charfile: _SupportsReadClose[str] | None) -> None: - """ - Set the character stream for this input source. (The stream + """Set the character stream for this input source. (The stream must be a Python 2.0 Unicode-wrapped file-like that performs conversion to Unicode strings.) @@ -279,16 +222,13 @@ class InputSource: """ def getCharacterStream(self) -> _SupportsReadClose[str] | None: - """ - Get the character stream for this input source. - """ + """Get the character stream for this input source.""" _AttrKey = TypeVar("_AttrKey", default=str) class AttributesImpl(Generic[_AttrKey]): def __init__(self, attrs: Mapping[_AttrKey, str]) -> None: - """ - Non-NS-aware implementation. + """Non-NS-aware implementation. attrs should be of the form {name : value}. """ @@ -317,8 +257,7 @@ _NSName: TypeAlias = tuple[str | None, str] class AttributesNSImpl(AttributesImpl[_NSName]): def __init__(self, attrs: Mapping[_NSName, str], qnames: Mapping[_NSName, str]) -> None: - """ - NS-aware implementation. + """NS-aware implementation. attrs should be of the form {(ns_uri, lname): value, ...}. qnames of the form {(ns_uri, lname): qname, ...}. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xmlrpc/client.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xmlrpc/client.pyi index 59792c0efe..b0758e5007 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xmlrpc/client.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xmlrpc/client.pyi @@ -1,4 +1,5 @@ """ + An XML-RPC client interface for Python. The marshalling and response parser code can also be used to @@ -94,14 +95,10 @@ INVALID_METHOD_PARAMS: Final[int] # undocumented INTERNAL_ERROR: Final[int] # undocumented class Error(Exception): - """ - Base class for client errors. - """ + """Base class for client errors.""" class ProtocolError(Error): - """ - Indicates an HTTP protocol error. - """ + """Indicates an HTTP protocol error.""" url: str errcode: int @@ -110,14 +107,10 @@ class ProtocolError(Error): def __init__(self, url: str, errcode: int, errmsg: str, headers: dict[str, str]) -> None: ... class ResponseError(Error): - """ - Indicates a broken response package. - """ + """Indicates a broken response package.""" class Fault(Error): - """ - Indicates an XML-RPC fault package. - """ + """Indicates an XML-RPC fault package.""" faultCode: int faultString: str @@ -130,8 +123,7 @@ def _iso8601_format(value: datetime) -> str: ... # undocumented def _strftime(value: _XMLDate) -> str: ... # undocumented class DateTime: - """ - DateTime wrapper for an ISO 8601 string or time tuple or + """DateTime wrapper for an ISO 8601 string or time tuple or localtime integer value to generate 'dateTime.iso8601' XML-RPC value. """ @@ -153,9 +145,7 @@ def _datetime(data: Any) -> DateTime: ... # undocumented def _datetime_type(data: str) -> datetime: ... # undocumented class Binary: - """ - Wrapper for binary data. - """ + """Wrapper for binary data.""" data: bytes def __init__(self, data: bytes | bytearray | None = None) -> None: ... @@ -176,8 +166,7 @@ class ExpatParser: # undocumented _WriteCallback: TypeAlias = Callable[[str], object] class Marshaller: - """ - Generate an XML-RPC params chunk from a Python data structure. + """Generate an XML-RPC params chunk from a Python data structure. Create a Marshaller instance for each set of parameters, and use the "dumps" method to convert your data (represented as a tuple) @@ -209,8 +198,7 @@ class Marshaller: def dump_instance(self, value: object, write: _WriteCallback) -> None: ... class Unmarshaller: - """ - Unmarshal an XML-RPC response, based on incoming XML event + """Unmarshal an XML-RPC response, based on incoming XML event messages (start, data, end). Call close() to get the resulting data structure. @@ -261,8 +249,7 @@ class _MultiCallMethod: # undocumented def __call__(self, *args: _Marshallable) -> None: ... class MultiCallIterator: # undocumented - """ - Iterates over the results of a multicall. Exceptions are + """Iterates over the results of a multicall. Exceptions are raised in response to xmlrpc faults. """ @@ -271,8 +258,7 @@ class MultiCallIterator: # undocumented def __getitem__(self, i: int) -> _Marshallable: ... class MultiCall: - """ - server -> an object used to boxcar method calls + """server -> an object used to boxcar method calls server should be a ServerProxy object. @@ -300,8 +286,7 @@ FastParser: ExpatParser | None FastUnmarshaller: Unmarshaller | None def getparser(use_datetime: bool = False, use_builtin_types: bool = False) -> tuple[ExpatParser, Unmarshaller]: - """ - getparser() -> parser, unmarshaller + """getparser() -> parser, unmarshaller Create an instance of the fastest available parser, and attach it to an unmarshalling object. Return both objects. @@ -314,8 +299,7 @@ def dumps( encoding: str | None = None, allow_none: bool = False, ) -> str: - """ - data [,options] -> marshalled data + """data [,options] -> marshalled data Convert an argument tuple or a Fault instance to an XML-RPC request (or response, if the methodresponse option is used). @@ -339,8 +323,7 @@ def dumps( def loads( data: str | ReadableBuffer, use_datetime: bool = False, use_builtin_types: bool = False ) -> tuple[tuple[_Marshallable, ...], str | None]: - """ - data -> unmarshalled data, method name + """data -> unmarshalled data, method name Convert an XML-RPC packet to unmarshalled data plus a method name (None if not present). @@ -350,22 +333,19 @@ def loads( """ def gzip_encode(data: ReadableBuffer) -> bytes: # undocumented - """ - data -> gzip encoded data + """data -> gzip encoded data Encode data using the gzip content encoding as described in RFC 1952 """ def gzip_decode(data: ReadableBuffer, max_decode: int = 20971520) -> bytes: # undocumented - """ - gzip encoded data -> unencoded data + """gzip encoded data -> unencoded data Decode data using the gzip content encoding as described in RFC 1952 """ class GzipDecodedResponse(gzip.GzipFile): # undocumented - """ - a file-like object to decode a response encoded with the gzip + """a file-like object to decode a response encoded with the gzip method, as described in RFC 1952. """ @@ -380,9 +360,7 @@ class _Method: # undocumented def __call__(self, *args: _Marshallable) -> _Marshallable: ... class Transport: - """ - Handles an HTTP transaction to an XML-RPC server. - """ + """Handles an HTTP transaction to an XML-RPC server.""" user_agent: str accept_gzip_encoding: bool @@ -415,9 +393,7 @@ class Transport: def parse_response(self, response: http.client.HTTPResponse) -> tuple[_Marshallable, ...]: ... class SafeTransport(Transport): - """ - Handles an HTTPS transaction to an XML-RPC server. - """ + """Handles an HTTPS transaction to an XML-RPC server.""" def __init__( self, @@ -430,8 +406,7 @@ class SafeTransport(Transport): def make_connection(self, host: _HostType) -> http.client.HTTPSConnection: ... class ServerProxy: - """ - uri [,options] -> a logical connection to an XML-RPC server + """uri [,options] -> a logical connection to an XML-RPC server uri is the connection point on the server, given as scheme://host/target. @@ -475,8 +450,7 @@ class ServerProxy: def __getattr__(self, name: str) -> _Method: ... @overload def __call__(self, attr: Literal["close"]) -> Callable[[], None]: - """ - A workaround to get special attributes on the ServerProxy + """A workaround to get special attributes on the ServerProxy without interfering with the magic __getattr__ """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xmlrpc/server.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xmlrpc/server.pyi index 3d770019ea..cec2524fbc 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xmlrpc/server.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xmlrpc/server.pyi @@ -138,8 +138,7 @@ _DispatchProtocol: TypeAlias = ( ) def resolve_dotted_attribute(obj: Any, attr: str, allow_dotted_names: bool = True) -> Any: # undocumented - """ - resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d + """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. @@ -149,14 +148,12 @@ def resolve_dotted_attribute(obj: Any, attr: str, allow_dotted_names: bool = Tru """ def list_public_methods(obj: Any) -> list[str]: # undocumented - """ - Returns a list of attribute strings, found in the specified + """Returns a list of attribute strings, found in the specified object, which represent callable attributes """ class SimpleXMLRPCDispatcher: # undocumented - """ - Mix-in class that dispatches XML-RPC requests. + """Mix-in class that dispatches XML-RPC requests. This class is used to register XML-RPC method handlers and then to dispatch them. This class doesn't need to be @@ -171,8 +168,7 @@ class SimpleXMLRPCDispatcher: # undocumented use_builtin_types: bool def __init__(self, allow_none: bool = False, encoding: str | None = None, use_builtin_types: bool = False) -> None: ... def register_instance(self, instance: Any, allow_dotted_names: bool = False) -> None: - """ - Registers an instance to respond to XML-RPC requests. + """Registers an instance to respond to XML-RPC requests. Only one instance can be installed at a time. @@ -204,24 +200,21 @@ class SimpleXMLRPCDispatcher: # undocumented """ def register_function(self, function: _DispatchProtocol | None = None, name: str | None = None) -> Callable[..., Any]: - """ - Registers a function to respond to XML-RPC requests. + """Registers a function to respond to XML-RPC requests. The optional name argument can be used to set a Unicode name for the function. """ def register_introspection_functions(self) -> None: - """ - Registers the XML-RPC introspection methods in the system + """Registers the XML-RPC introspection methods in the system namespace. see http://xmlrpc.usefulinc.com/doc/reserved.html """ def register_multicall_functions(self) -> None: - """ - Registers the XML-RPC multicall method in the system + """Registers the XML-RPC multicall method in the system namespace. see http://www.xmlrpc.com/discuss/msgReader$1208 @@ -233,8 +226,7 @@ class SimpleXMLRPCDispatcher: # undocumented dispatch_method: Callable[[str, tuple[_Marshallable, ...]], Fault | tuple[_Marshallable, ...]] | None = None, path: Any | None = None, ) -> str: # undocumented - """ - Dispatches an XML-RPC method from marshalled (XML) data. + """Dispatches an XML-RPC method from marshalled (XML) data. XML-RPC methods are dispatched from the marshalled (XML) data using the _dispatch method and the result is returned as @@ -246,15 +238,13 @@ class SimpleXMLRPCDispatcher: # undocumented """ def system_listMethods(self) -> list[str]: # undocumented - """ - system.listMethods() => ['add', 'subtract', 'multiple'] + """system.listMethods() => ['add', 'subtract', 'multiple'] Returns a list of the methods supported by the server. """ def system_methodSignature(self, method_name: str) -> str: # undocumented - """ - system.methodSignature('add') => [double, int, int] + """system.methodSignature('add') => [double, int, int] Returns a list describing the signature of the method. In the above example, the add method takes two integers as arguments @@ -264,15 +254,13 @@ class SimpleXMLRPCDispatcher: # undocumented """ def system_methodHelp(self, method_name: str) -> str: # undocumented - """ - system.methodHelp('add') => "Adds two integers together" + """system.methodHelp('add') => "Adds two integers together" Returns a string containing documentation for the specified method. """ def system_multicall(self, call_list: list[dict[str, _Marshallable]]) -> list[_Marshallable]: # undocumented - """ - system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => [[4], ...] + """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => [[4], ...] Allows the caller to package multiple XML-RPC calls into a single request. @@ -281,8 +269,7 @@ class SimpleXMLRPCDispatcher: # undocumented """ def _dispatch(self, method: str, params: Iterable[_Marshallable]) -> _Marshallable: # undocumented - """ - Dispatches the XML-RPC method. + """Dispatches the XML-RPC method. XML-RPC calls are forwarded to a registered function that matches the called XML-RPC method name. If no such function @@ -303,8 +290,7 @@ class SimpleXMLRPCDispatcher: # undocumented """ class SimpleXMLRPCRequestHandler(http.server.BaseHTTPRequestHandler): - """ - Simple XML-RPC request handler class. + """Simple XML-RPC request handler class. Handles all HTTP POST requests and attempts to decode them as XML-RPC requests. @@ -316,8 +302,7 @@ class SimpleXMLRPCRequestHandler(http.server.BaseHTTPRequestHandler): def accept_encodings(self) -> dict[str, float]: ... def is_rpc_path_valid(self) -> bool: ... def do_POST(self) -> None: - """ - Handles the HTTP POST request. + """Handles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server's _dispatch method for handling. @@ -327,8 +312,7 @@ class SimpleXMLRPCRequestHandler(http.server.BaseHTTPRequestHandler): def report_404(self) -> None: ... class SimpleXMLRPCServer(socketserver.TCPServer, SimpleXMLRPCDispatcher): - """ - Simple XML-RPC server. + """Simple XML-RPC server. Simple XML-RPC server that allows functions and a single instance to be installed to handle requests. The default implementation @@ -350,8 +334,7 @@ class SimpleXMLRPCServer(socketserver.TCPServer, SimpleXMLRPCDispatcher): ) -> None: ... class MultiPathXMLRPCServer(SimpleXMLRPCServer): # undocumented - """ - Multipath XML-RPC Server + """Multipath XML-RPC Server This specialization of SimpleXMLRPCServer allows the user to create multiple Dispatcher instances and assign them to different HTTP request paths. This makes it possible to run two or more @@ -374,27 +357,21 @@ class MultiPathXMLRPCServer(SimpleXMLRPCServer): # undocumented def get_dispatcher(self, path: str) -> SimpleXMLRPCDispatcher: ... class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher): - """ - Simple handler for XML-RPC data passed through CGI. - """ + """Simple handler for XML-RPC data passed through CGI.""" def __init__(self, allow_none: bool = False, encoding: str | None = None, use_builtin_types: bool = False) -> None: ... def handle_xmlrpc(self, request_text: str) -> None: - """ - Handle a single XML-RPC request - """ + """Handle a single XML-RPC request""" def handle_get(self) -> None: - """ - Handle a single HTTP GET request. + """Handle a single HTTP GET request. Default implementation indicates an error because XML-RPC uses the POST method. """ def handle_request(self, request_text: str | None = None) -> None: - """ - Handle a single XML-RPC request passed through a CGI post method. + """Handle a single XML-RPC request passed through a CGI post method. If no XML data is given then it is read from stdin. The resulting XML-RPC response is printed to stdout along with the correct HTTP @@ -402,9 +379,7 @@ class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher): """ class ServerHTMLDoc(pydoc.HTMLDoc): # undocumented - """ - Class used to generate pydoc HTML document for a server - """ + """Class used to generate pydoc HTML document for a server""" def docroutine( # type: ignore[override] self, @@ -416,18 +391,13 @@ class ServerHTMLDoc(pydoc.HTMLDoc): # undocumented methods: Mapping[str, str] = {}, cl: type | None = None, ) -> str: - """ - Produce HTML documentation for a function or method object. - """ + """Produce HTML documentation for a function or method object.""" def docserver(self, server_name: str, package_documentation: str, methods: dict[str, str]) -> str: - """ - Produce HTML documentation for an XML-RPC server. - """ + """Produce HTML documentation for an XML-RPC server.""" class XMLRPCDocGenerator: # undocumented - """ - Generates documentation for an XML-RPC server. + """Generates documentation for an XML-RPC server. This class is designed as mix-in and should not be constructed directly. @@ -437,23 +407,16 @@ class XMLRPCDocGenerator: # undocumented server_documentation: str server_title: str def set_server_title(self, server_title: str) -> None: - """ - Set the HTML title of the generated server documentation - """ + """Set the HTML title of the generated server documentation""" def set_server_name(self, server_name: str) -> None: - """ - Set the name of the generated HTML server documentation - """ + """Set the name of the generated HTML server documentation""" def set_server_documentation(self, server_documentation: str) -> None: - """ - Set the documentation string for the entire server. - """ + """Set the documentation string for the entire server.""" def generate_html_documentation(self) -> str: - """ - generate_html_documentation() => html documentation for the server + """generate_html_documentation() => html documentation for the server Generates HTML documentation for the server using introspection for installed functions and instances that do not implement the @@ -465,8 +428,7 @@ class XMLRPCDocGenerator: # undocumented """ class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): - """ - XML-RPC and documentation request handler class. + """XML-RPC and documentation request handler class. Handles all HTTP POST requests and attempts to decode them as XML-RPC requests. @@ -476,16 +438,14 @@ class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): """ def do_GET(self) -> None: - """ - Handles the HTTP GET request. + """Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation. """ class DocXMLRPCServer(SimpleXMLRPCServer, XMLRPCDocGenerator): - """ - XML-RPC and HTML documentation server. + """XML-RPC and HTML documentation server. Adds the ability to serve server documentation to the capabilities of SimpleXMLRPCServer. @@ -503,8 +463,7 @@ class DocXMLRPCServer(SimpleXMLRPCServer, XMLRPCDocGenerator): ) -> None: ... class DocCGIXMLRPCRequestHandler(CGIXMLRPCRequestHandler, XMLRPCDocGenerator): - """ - Handler for XML-RPC data and documentation requests passed through + """Handler for XML-RPC data and documentation requests passed through CGI """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/xxlimited.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/xxlimited.pyi index 589d13dea7..d63d49a6eb 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/xxlimited.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/xxlimited.pyi @@ -9,28 +9,21 @@ class Str(str): ... @final class Xxo: - """ - A class that explicitly stores attributes in an internal dict - """ + """A class that explicitly stores attributes in an internal dict""" def demo(self) -> None: - """ - demo(o) -> o - """ + """demo(o) -> o""" if sys.version_info >= (3, 11) and sys.platform != "win32": x_exports: int def foo(i: int, j: int, /) -> Any: - """ - foo(i,j) + """foo(i,j) Return the sum of i and j. """ def new() -> Xxo: - """ - new() -> new Xx object - """ + """new() -> new Xx object""" if sys.version_info >= (3, 10): class Error(Exception): ... @@ -41,4 +34,5 @@ else: class Null: __hash__: ClassVar[None] # type: ignore[assignment] - def roj(b: Any, /) -> None: ... + def roj(b: Any, /) -> None: + """roj(a,b) -> None""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/zipapp.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/zipapp.pyi index 31ece867e8..354ecc600e 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/zipapp.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/zipapp.pyi @@ -17,8 +17,7 @@ def create_archive( filter: Callable[[Path], bool] | None = None, compressed: bool = False, ) -> None: - """ - Create an application archive from SOURCE. + """Create an application archive from SOURCE. The SOURCE can be the name of a directory, or a filename or a file-like object referring to an existing archive. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/zipfile/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/zipfile/__init__.pyi index 3bd0e3d4a9..1a8ca7b1f3 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/zipfile/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/zipfile/__init__.pyi @@ -1,4 +1,5 @@ """ + Read and write ZIP files. XXX references to utf-8 need further investigation. @@ -46,8 +47,7 @@ BadZipfile = BadZipFile error = BadZipfile class LargeZipFile(Exception): - """ - Raised when writing a zipfile, the zipfile requires ZIP64 extensions + """Raised when writing a zipfile, the zipfile requires ZIP64 extensions and those extensions are disabled. """ @@ -68,8 +68,7 @@ class _ClosableZipStream(_ZipStream, Protocol): def close(self) -> object: ... class ZipExtFile(io.BufferedIOBase): - """ - File-like object for reading an archive member. + """File-like object for reading an archive member. Is returned by ZipFile.open(). """ @@ -103,27 +102,21 @@ class ZipExtFile(io.BufferedIOBase): close_fileobj: Literal[False] = False, ) -> None: ... def read(self, n: int | None = -1) -> bytes: - """ - Read and return up to n bytes. + """Read and return up to n bytes. If the argument is omitted, None, or negative, data is read and returned until EOF is reached. """ def readline(self, limit: int = -1) -> bytes: # type: ignore[override] - """ - Read and return a line from the stream. + """Read and return a line from the stream. If limit is specified, at most limit bytes will be read. """ def peek(self, n: int = 1) -> bytes: - """ - Returns buffered bytes without advancing the position. - """ + """Returns buffered bytes without advancing the position.""" def read1(self, n: int | None) -> bytes: # type: ignore[override] - """ - Read up to n bytes with at most one read() system call. - """ + """Read up to n bytes with at most one read() system call.""" def seek(self, offset: int, whence: int = 0) -> int: ... @@ -145,8 +138,7 @@ class _ZipWritable(Protocol): def write(self, b: bytes, /) -> int: ... class ZipFile: - """ - Class with methods to open, read, write, close, list zip files. + """Class with methods to open, read, write, close, list zip files. z = ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=True, compresslevel=None) @@ -196,8 +188,7 @@ class ZipFile: strict_timestamps: bool = True, metadata_encoding: str | None = None, ) -> None: - """ - Open the ZIP file with mode read 'r', write 'w', exclusive create 'x', + """Open the ZIP file with mode read 'r', write 'w', exclusive create 'x', or append 'a'. """ # metadata_encoding is only allowed for read mode @@ -249,8 +240,7 @@ class ZipFile: *, strict_timestamps: bool = True, ) -> None: - """ - Open the ZIP file with mode read 'r', write 'w', exclusive create 'x', + """Open the ZIP file with mode read 'r', write 'w', exclusive create 'x', or append 'a'. """ @@ -293,32 +283,25 @@ class ZipFile: self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... def close(self) -> None: - """ - Close the file, and for mode 'w', 'x' and 'a' write the ending + """Close the file, and for mode 'w', 'x' and 'a' write the ending records. """ def getinfo(self, name: str) -> ZipInfo: - """ - Return the instance of ZipInfo given 'name'. - """ + """Return the instance of ZipInfo given 'name'.""" def infolist(self) -> list[ZipInfo]: - """ - Return a list of class ZipInfo instances for files in the + """Return a list of class ZipInfo instances for files in the archive. """ def namelist(self) -> list[str]: - """ - Return a list of file names in the archive. - """ + """Return a list of file names in the archive.""" def open( self, name: str | ZipInfo, mode: _ReadWriteMode = "r", pwd: bytes | None = None, *, force_zip64: bool = False ) -> IO[bytes]: - """ - Return file-like object for 'name'. + """Return file-like object for 'name'. name is a string for the file name within the ZIP file, or a ZipInfo object. @@ -335,8 +318,7 @@ class ZipFile: """ def extract(self, member: str | ZipInfo, path: StrPath | None = None, pwd: bytes | None = None) -> str: - """ - Extract a member from the archive to the current working directory, + """Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. 'member' may be a filename or a ZipInfo object. You can specify a different directory using 'path'. You can specify the @@ -346,8 +328,7 @@ class ZipFile: def extractall( self, path: StrPath | None = None, members: Iterable[str | ZipInfo] | None = None, pwd: bytes | None = None ) -> None: - """ - Extract all members from the archive to the current working + """Extract all members from the archive to the current working directory. 'path' specifies a different directory to extract to. 'members' is optional and must be a subset of the list returned by namelist(). You can specify the password to decrypt all files @@ -355,24 +336,18 @@ class ZipFile: """ def printdir(self, file: _Writer | None = None) -> None: - """ - Print a table of contents for the zip file. - """ + """Print a table of contents for the zip file.""" def setpassword(self, pwd: bytes) -> None: - """ - Set default password for encrypted files. - """ + """Set default password for encrypted files.""" def read(self, name: str | ZipInfo, pwd: bytes | None = None) -> bytes: - """ - Return file bytes for name. 'pwd' is the password to decrypt + """Return file bytes for name. 'pwd' is the password to decrypt encrypted files. """ def testzip(self) -> str | None: - """ - Read all the files and check the CRC. + """Read all the files and check the CRC. Return None if all files could be read successfully, or the name of the offending file otherwise. @@ -385,8 +360,7 @@ class ZipFile: compress_type: int | None = None, compresslevel: int | None = None, ) -> None: - """ - Put the bytes from filename into the archive under the name + """Put the bytes from filename into the archive under the name arcname. """ @@ -397,8 +371,7 @@ class ZipFile: compress_type: int | None = None, compresslevel: int | None = None, ) -> None: - """ - Write a file into the archive. The contents is 'data', which + """Write a file into the archive. The contents is 'data', which may be either a 'str' or a 'bytes' instance; if it is a 'str', it is encoded as UTF-8 first. 'zinfo_or_arcname' is either a ZipInfo instance or @@ -406,33 +379,25 @@ class ZipFile: """ if sys.version_info >= (3, 11): def mkdir(self, zinfo_or_directory_name: str | ZipInfo, mode: int = 0o777) -> None: - """ - Creates a directory inside the zip archive. - """ + """Creates a directory inside the zip archive.""" if sys.version_info >= (3, 14): @property def data_offset(self) -> int | None: - """ - The offset to the start of zip data in the file or None if + """The offset to the start of zip data in the file or None if unavailable. """ def __del__(self) -> None: - """ - Call the "close()" method in case the user forgot. - """ + """Call the "close()" method in case the user forgot.""" class PyZipFile(ZipFile): - """ - Class to create ZIP archives with Python library files and packages. - """ + """Class to create ZIP archives with Python library files and packages.""" def __init__( self, file: str | IO[bytes], mode: _ZipFileMode = "r", compression: int = 0, allowZip64: bool = True, optimize: int = -1 ) -> None: ... def writepy(self, pathname: str, basename: str = "", filterfunc: Callable[[str], bool] | None = None) -> None: - """ - Add all files from "pathname" to the ZIP archive. + """Add all files from "pathname" to the ZIP archive. If pathname is a package directory, search the directory and all package subdirectories recursively for all *.py and enter @@ -447,9 +412,7 @@ class PyZipFile(ZipFile): """ class ZipInfo: - """ - Class with attributes describing each file in the ZIP archive. - """ + """Class with attributes describing each file in the ZIP archive.""" filename: str date_time: _DateTuple @@ -475,8 +438,7 @@ class ZipInfo: def __init__(self, filename: str = "NoName", date_time: _DateTuple = (1980, 1, 1, 0, 0, 0)) -> None: ... @classmethod def from_file(cls, filename: StrPath, arcname: StrPath | None = None, *, strict_timestamps: bool = True) -> Self: - """ - Construct an appropriate ZipInfo for a file on the filesystem. + """Construct an appropriate ZipInfo for a file on the filesystem. filename should be the path to a file or directory on the filesystem. @@ -486,13 +448,10 @@ class ZipInfo: """ def is_dir(self) -> bool: - """ - Return True if this archive member is a directory. - """ + """Return True if this archive member is a directory.""" def FileHeader(self, zip64: bool | None = None) -> bytes: - """ - Return the per-file header as a bytes object. + """Return the per-file header as a bytes object. When the optional zip64 arg is None rather than a bool, we will decide based upon the file_size and compress_size, if known, @@ -504,22 +463,19 @@ if sys.version_info >= (3, 12): else: class CompleteDirs(ZipFile): - """ - A ZipFile subclass that ensures that implied directories + """A ZipFile subclass that ensures that implied directories are always included in the namelist. """ def resolve_dir(self, name: str) -> str: - """ - If the name represents a directory, return that name + """If the name represents a directory, return that name as a directory (with the trailing slash). """ @overload @classmethod def make(cls, source: ZipFile) -> CompleteDirs: - """ - Given a source (filename or zipfile), return an + """Given a source (filename or zipfile), return an appropriate CompleteDirs subclass. """ @@ -528,8 +484,7 @@ else: def make(cls, source: StrPath | IO[bytes]) -> Self: ... class Path: - """ - A pathlib-compatible interface for zip files. + """A pathlib-compatible interface for zip files. Consider a zip file with this structure:: @@ -608,8 +563,7 @@ else: root: CompleteDirs at: str def __init__(self, root: ZipFile | StrPath | IO[bytes], at: str = "") -> None: - """ - Construct a Path from a ZipFile or filename. + """Construct a Path from a ZipFile or filename. Note: When the source is an existing ZipFile object, its type (__class__) will be mutated to a @@ -645,8 +599,7 @@ else: *, pwd: bytes | None = None, ) -> TextIOWrapper: - """ - Open this entry as text or binary following the semantics + """Open this entry as text or binary following the semantics of ``pathlib.Path.open()`` by passing arguments through to io.TextIOWrapper(). """ @@ -679,8 +632,7 @@ else: def __truediv__(self, add: StrPath) -> Path: ... def is_zipfile(filename: StrOrBytesPath | _SupportsReadSeekTell) -> bool: - """ - Quickly see if a file is a ZIP file by checking the magic number. + """Quickly see if a file is a ZIP file by checking the magic number. The filename argument may be a file or file-like object too. """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/zipfile/_path/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/zipfile/_path/__init__.pyi index 4b6743b707..05fddc05ad 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/zipfile/_path/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/zipfile/_path/__init__.pyi @@ -1,4 +1,5 @@ """ + A Path-like interface for zipfiles. This codebase is shared between zipfile.Path in the stdlib @@ -22,17 +23,14 @@ if sys.version_info >= (3, 12): __all__ = ["Path"] class InitializedState: - """ - Mix-in to save the initialization state for pickling. - """ + """Mix-in to save the initialization state for pickling.""" def __init__(self, *args: object, **kwargs: object) -> None: ... def __getstate__(self) -> tuple[list[object], dict[object, object]]: ... def __setstate__(self, state: Sequence[tuple[list[object], dict[object, object]]]) -> None: ... class CompleteDirs(InitializedState, ZipFile): - """ - A ZipFile subclass that ensures that implied directories + """A ZipFile subclass that ensures that implied directories are always included in the namelist. >>> list(CompleteDirs._implied_dirs(['foo/bar.txt', 'foo/bar/baz.txt'])) @@ -42,16 +40,14 @@ if sys.version_info >= (3, 12): """ def resolve_dir(self, name: str) -> str: - """ - If the name represents a directory, return that name + """If the name represents a directory, return that name as a directory (with the trailing slash). """ @overload @classmethod def make(cls, source: ZipFile) -> CompleteDirs: - """ - Given a source (filename or zipfile), return an + """Given a source (filename or zipfile), return an appropriate CompleteDirs subclass. """ @@ -61,14 +57,12 @@ if sys.version_info >= (3, 12): if sys.version_info >= (3, 13): @classmethod def inject(cls, zf: _ZF) -> _ZF: - """ - Given a writable zip file zf, inject directory entries for + """Given a writable zip file zf, inject directory entries for any directories implied by the presence of children. """ class Path: - """ - A :class:`importlib.resources.abc.Traversable` interface for zip files. + """A :class:`importlib.resources.abc.Traversable` interface for zip files. Implements many of the features users enjoy from :class:`pathlib.Path`. @@ -172,8 +166,7 @@ if sys.version_info >= (3, 12): root: CompleteDirs at: str def __init__(self, root: ZipFile | StrPath | IO[bytes], at: str = "") -> None: - """ - Construct a Path from a ZipFile or filename. + """Construct a Path from a ZipFile or filename. Note: When the source is an existing ZipFile object, its type (__class__) will be mutated to a @@ -206,8 +199,7 @@ if sys.version_info >= (3, 12): *, pwd: bytes | None = None, ) -> TextIOWrapper: - """ - Open this entry as text or binary following the semantics + """Open this entry as text or binary following the semantics of ``pathlib.Path.open()`` by passing arguments through to io.TextIOWrapper(). """ @@ -231,15 +223,12 @@ if sys.version_info >= (3, 12): def glob(self, pattern: str) -> Iterator[Self]: ... def rglob(self, pattern: str) -> Iterator[Self]: ... def is_symlink(self) -> Literal[False]: - """ - Return whether this path is a symlink. - """ + """Return whether this path is a symlink.""" def relative_to(self, other: Path, *extra: StrPath) -> str: ... def match(self, path_pattern: str) -> bool: ... def __eq__(self, other: object) -> bool: - """ - >>> Path(zipfile.ZipFile(io.BytesIO(), 'w')) == 'foo' + """>>> Path(zipfile.ZipFile(io.BytesIO(), 'w')) == 'foo' False """ diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/zipfile/_path/glob.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/zipfile/_path/glob.pyi index aa5bc08214..f7c0e01897 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/zipfile/_path/glob.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/zipfile/_path/glob.pyi @@ -4,8 +4,7 @@ from re import Match if sys.version_info >= (3, 13): class Translator: - """ - >>> Translator('xyz') + """>>> Translator('xyz') Traceback (most recent call last): ... AssertionError: Invalid separators @@ -18,13 +17,10 @@ if sys.version_info >= (3, 13): def __init__(self, seps: str = ...) -> None: ... def translate(self, pattern: str) -> str: - """ - Given a glob pattern, produce a regex that matches it. - """ + """Given a glob pattern, produce a regex that matches it.""" def extend(self, pattern: str) -> str: - """ - Extend regex for pattern-wide concerns. + """Extend regex for pattern-wide concerns. Apply '(?s:)' to create a non-matching group that matches newlines (valid on Unix). @@ -33,15 +29,13 @@ if sys.version_info >= (3, 13): """ def match_dirs(self, pattern: str) -> str: - """ - Ensure that zipfile.Path directory names are matched. + """Ensure that zipfile.Path directory names are matched. zipfile.Path directory names always end in a slash. """ def translate_core(self, pattern: str) -> str: - """ - Given a glob pattern, produce a regex that matches it. + """Given a glob pattern, produce a regex that matches it. >>> t = Translator() >>> t.translate_core('*.txt').replace('\\\\\\\\', '') @@ -53,13 +47,10 @@ if sys.version_info >= (3, 13): """ def replace(self, match: Match[str]) -> str: - """ - Perform the replacements for a match from :func:`separate`. - """ + """Perform the replacements for a match from :func:`separate`.""" def restrict_rglob(self, pattern: str) -> None: - """ - Raise ValueError if ** appears in anything but a full path segment. + """Raise ValueError if ** appears in anything but a full path segment. >>> Translator().translate('**foo') Traceback (most recent call last): @@ -68,14 +59,11 @@ if sys.version_info >= (3, 13): """ def star_not_empty(self, pattern: str) -> str: - """ - Ensure that * will not match an empty segment. - """ + """Ensure that * will not match an empty segment.""" else: def translate(pattern: str) -> str: - """ - Given a glob pattern, produce a regex that matches it. + """Given a glob pattern, produce a regex that matches it. >>> translate('*.txt') '[^/]*\\\\.txt' @@ -85,16 +73,28 @@ else: '.*/[^/]*' """ - def match_dirs(pattern: str) -> str: ... - def translate_core(pattern: str) -> str: ... - def replace(match: Match[str]) -> str: - """ - Perform the replacements for a match from :func:`separate`. + def match_dirs(pattern: str) -> str: + """Ensure that zipfile.Path directory names are matched. + + zipfile.Path directory names always end in a slash. """ + def translate_core(pattern: str) -> str: + """Given a glob pattern, produce a regex that matches it. + + >>> translate('*.txt') + '[^/]*\\\\.txt' + >>> translate('a?txt') + 'a.txt' + >>> translate('**/*') + '.*/[^/]*' + """ + + def replace(match: Match[str]) -> str: + """Perform the replacements for a match from :func:`separate`.""" + def separate(pattern: str) -> Iterator[Match[str]]: - """ - Separate out character sets to avoid translating their contents. + """Separate out character sets to avoid translating their contents. >>> [m.group(0) for m in separate('*.txt')] ['*.txt'] diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/zipimport.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/zipimport.pyi index 4deeaa2ee9..0e56e78be3 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/zipimport.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/zipimport.pyi @@ -32,8 +32,7 @@ __all__ = ["ZipImportError", "zipimporter"] class ZipImportError(ImportError): ... class zipimporter(_LoaderBasics): - """ - zipimporter(archivepath) -> zipimporter object + """zipimporter(archivepath) -> zipimporter object Create a new zipimporter instance. 'archivepath' must be a path to a zipfile, or to a specific path inside a zipfile. For example, it can be @@ -59,47 +58,37 @@ class zipimporter(_LoaderBasics): def find_module(self, fullname: str, path: str | None = None) -> zipimporter | None: ... def get_code(self, fullname: str) -> CodeType: - """ - get_code(fullname) -> code object. + """get_code(fullname) -> code object. Return the code object for the specified module. Raise ZipImportError if the module couldn't be imported. """ def get_data(self, pathname: str) -> bytes: - """ - get_data(pathname) -> string with file data. + """get_data(pathname) -> string with file data. Return the data associated with 'pathname'. Raise OSError if the file wasn't found. """ def get_filename(self, fullname: str) -> str: - """ - get_filename(fullname) -> filename string. + """get_filename(fullname) -> filename string. Return the filename for the specified module or raise ZipImportError if it couldn't be imported. """ if sys.version_info >= (3, 14): def get_resource_reader(self, fullname: str) -> ZipReader: # undocumented - """ - Return the ResourceReader for a module in a zip file. - """ + """Return the ResourceReader for a module in a zip file.""" elif sys.version_info >= (3, 10): def get_resource_reader(self, fullname: str) -> ZipReader | None: # undocumented - """ - Return the ResourceReader for a module in a zip file. - """ + """Return the ResourceReader for a module in a zip file.""" else: def get_resource_reader(self, fullname: str) -> ResourceReader | None: # undocumented - """ - Return the ResourceReader for a module in a zip file. - """ + """Return the ResourceReader for a module in a zip file.""" def get_source(self, fullname: str) -> str | None: - """ - get_source(fullname) -> source string. + """get_source(fullname) -> source string. Return the source code for the specified module. Raise ZipImportError if the module couldn't be found, return None if the archive does @@ -107,8 +96,7 @@ class zipimporter(_LoaderBasics): """ def is_package(self, fullname: str) -> bool: - """ - is_package(fullname) -> bool. + """is_package(fullname) -> bool. Return True if the module specified by fullname is a package. Raise ZipImportError if the module couldn't be found. @@ -116,8 +104,7 @@ class zipimporter(_LoaderBasics): @deprecated("Deprecated since 3.10; use exec_module() instead") def load_module(self, fullname: str) -> ModuleType: - """ - load_module(fullname) -> module. + """load_module(fullname) -> module. Load the module specified by 'fullname'. 'fullname' must be the fully qualified (dotted) module name. It returns the imported @@ -127,23 +114,16 @@ class zipimporter(_LoaderBasics): """ if sys.version_info >= (3, 10): def exec_module(self, module: ModuleType) -> None: - """ - Execute the module. - """ + """Execute the module.""" def create_module(self, spec: ModuleSpec) -> None: - """ - Use default semantics for module creation. - """ + """Use default semantics for module creation.""" def find_spec(self, fullname: str, target: ModuleType | None = None) -> ModuleSpec | None: - """ - Create a ModuleSpec for the specified module. + """Create a ModuleSpec for the specified module. Returns None if the module cannot be found. """ def invalidate_caches(self) -> None: - """ - Invalidates the cache of file data of the archive path. - """ + """Invalidates the cache of file data of the archive path.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/zlib.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/zlib.pyi index 4c65439b33..0e0c160037 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/zlib.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/zlib.pyi @@ -71,8 +71,7 @@ class _Decompress: def copy(self) -> _Decompress: ... def adler32(data: ReadableBuffer, value: int = 1, /) -> int: - """ - Compute an Adler-32 checksum of data. + """Compute an Adler-32 checksum of data. value Starting value of the checksum. @@ -82,8 +81,7 @@ def adler32(data: ReadableBuffer, value: int = 1, /) -> int: if sys.version_info >= (3, 11): def compress(data: ReadableBuffer, /, level: int = -1, wbits: int = 15) -> bytes: - """ - Returns a bytes object containing compressed data. + """Returns a bytes object containing compressed data. data Binary data to be compressed. @@ -95,8 +93,7 @@ if sys.version_info >= (3, 11): else: def compress(data: ReadableBuffer, /, level: int = -1) -> bytes: - """ - Returns a bytes object containing compressed data. + """Returns a bytes object containing compressed data. data Binary data to be compressed. @@ -107,8 +104,7 @@ else: def compressobj( level: int = -1, method: int = 8, wbits: int = 15, memLevel: int = 8, strategy: int = 0, zdict: ReadableBuffer | None = None ) -> _Compress: - """ - Return a compressor object. + """Return a compressor object. level The compression level (an integer in the range 0-9 or -1; default is @@ -134,8 +130,7 @@ def compressobj( """ def crc32(data: ReadableBuffer, value: int = 0, /) -> int: - """ - Compute a CRC-32 checksum of data. + """Compute a CRC-32 checksum of data. value Starting value of the checksum. @@ -144,8 +139,7 @@ def crc32(data: ReadableBuffer, value: int = 0, /) -> int: """ def decompress(data: ReadableBuffer, /, wbits: int = 15, bufsize: int = 16384) -> bytes: - """ - Returns a bytes object containing the uncompressed data. + """Returns a bytes object containing the uncompressed data. data Compressed data. @@ -156,8 +150,7 @@ def decompress(data: ReadableBuffer, /, wbits: int = 15, bufsize: int = 16384) - """ def decompressobj(wbits: int = 15, zdict: ReadableBuffer = b"") -> _Decompress: - """ - Return a decompressor object. + """Return a decompressor object. wbits The window buffer size and container format. diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/zoneinfo/__init__.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/zoneinfo/__init__.pyi index 95fba91af2..8a04019d39 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/zoneinfo/__init__.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/zoneinfo/__init__.pyi @@ -18,41 +18,27 @@ class ZoneInfo(tzinfo): def __new__(cls, key: str) -> Self: ... @classmethod def no_cache(cls, key: str) -> Self: - """ - Get a new instance of ZoneInfo, bypassing the cache. - """ + """Get a new instance of ZoneInfo, bypassing the cache.""" if sys.version_info >= (3, 12): @classmethod def from_file(cls, file_obj: _IOBytes, /, key: str | None = None) -> Self: - """ - Create a ZoneInfo file from a file object. - """ + """Create a ZoneInfo file from a file object.""" else: @classmethod def from_file(cls, fobj: _IOBytes, /, key: str | None = None) -> Self: - """ - Create a ZoneInfo file from a file object. - """ + """Create a ZoneInfo file from a file object.""" @classmethod def clear_cache(cls, *, only_keys: Iterable[str] | None = None) -> None: - """ - Clear the ZoneInfo cache. - """ + """Clear the ZoneInfo cache.""" def tzname(self, dt: datetime | None, /) -> str | None: - """ - Retrieve a string containing the abbreviation for the time zone that applies in a zone at a given datetime. - """ + """Retrieve a string containing the abbreviation for the time zone that applies in a zone at a given datetime.""" def utcoffset(self, dt: datetime | None, /) -> timedelta | None: - """ - Retrieve a timedelta representing the UTC offset in a zone at the given datetime. - """ + """Retrieve a timedelta representing the UTC offset in a zone at the given datetime.""" def dst(self, dt: datetime | None, /) -> timedelta | None: - """ - Retrieve a timedelta representing the amount of DST applied in a zone at the given datetime. - """ + """Retrieve a timedelta representing the amount of DST applied in a zone at the given datetime.""" def __dir__() -> list[str]: ... diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/zoneinfo/_common.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/zoneinfo/_common.pyi index 9f7aea4e2a..b527aab566 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/zoneinfo/_common.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/zoneinfo/_common.pyi @@ -11,6 +11,4 @@ def load_data( ) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...], tuple[int, ...], tuple[str, ...], bytes | None]: ... class ZoneInfoNotFoundError(KeyError): - """ - Exception raised when a ZoneInfo key is not found. - """ + """Exception raised when a ZoneInfo key is not found.""" diff --git a/crates/ty_vendored/vendor/typeshed/stdlib/zoneinfo/_tzpath.pyi b/crates/ty_vendored/vendor/typeshed/stdlib/zoneinfo/_tzpath.pyi index df1991be39..e4f17bb61f 100644 --- a/crates/ty_vendored/vendor/typeshed/stdlib/zoneinfo/_tzpath.pyi +++ b/crates/ty_vendored/vendor/typeshed/stdlib/zoneinfo/_tzpath.pyi @@ -5,18 +5,13 @@ from collections.abc import Sequence # a sequence of strings is required. This should be remedied if a solution # to this typing bug is found: https://github.com/python/typing/issues/256 def reset_tzpath(to: Sequence[StrPath] | None = None) -> None: - """ - Reset global TZPATH. - """ + """Reset global TZPATH.""" def find_tzfile(key: str) -> str | None: - """ - Retrieve the path to a TZif file from a key. - """ + """Retrieve the path to a TZif file from a key.""" def available_timezones() -> set[str]: - """ - Returns a set containing all available time zones. + """Returns a set containing all available time zones. .. caution:: @@ -28,6 +23,4 @@ def available_timezones() -> set[str]: TZPATH: tuple[str, ...] class InvalidTZPathWarning(RuntimeWarning): - """ - Warning raised if an invalid path is specified in PYTHONTZPATH. - """ + """Warning raised if an invalid path is specified in PYTHONTZPATH."""