[ty] Sync vendored typeshed stubs (#19368)

Co-authored-by: typeshedbot <>
Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
This commit is contained in:
github-actions[bot] 2025-07-15 18:14:46 +00:00 committed by GitHub
parent c0d04f2d56
commit a0d4e1f854
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
469 changed files with 10781 additions and 23229 deletions

View file

@ -423,14 +423,14 @@ mod tests {
assert_snapshot!(test.goto_type_definition(), @r#" assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:1120:7 --> stdlib/builtins.pyi:892:7
| |
1118 | def __getitem__(self, key: int, /) -> str | int | None: ... 890 | def __getitem__(self, key: int, /) -> str | int | None: ...
1119 | 891 |
1120 | class str(Sequence[str]): 892 | class str(Sequence[str]):
| ^^^ | ^^^
1121 | """ 893 | """str(object='') -> str
1122 | str(object='') -> str 894 | str(bytes_or_buffer[, encoding[, errors]]) -> str
| |
info: Source info: Source
--> main.py:4:13 --> main.py:4:13
@ -452,14 +452,14 @@ mod tests {
assert_snapshot!(test.goto_type_definition(), @r#" assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:1120:7 --> stdlib/builtins.pyi:892:7
| |
1118 | def __getitem__(self, key: int, /) -> str | int | None: ... 890 | def __getitem__(self, key: int, /) -> str | int | None: ...
1119 | 891 |
1120 | class str(Sequence[str]): 892 | class str(Sequence[str]):
| ^^^ | ^^^
1121 | """ 893 | """str(object='') -> str
1122 | str(object='') -> str 894 | str(bytes_or_buffer[, encoding[, errors]]) -> str
| |
info: Source info: Source
--> main.py:2:22 --> main.py:2:22
@ -568,14 +568,14 @@ mod tests {
assert_snapshot!(test.goto_type_definition(), @r#" assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:1120:7 --> stdlib/builtins.pyi:892:7
| |
1118 | def __getitem__(self, key: int, /) -> str | int | None: ... 890 | def __getitem__(self, key: int, /) -> str | int | None: ...
1119 | 891 |
1120 | class str(Sequence[str]): 892 | class str(Sequence[str]):
| ^^^ | ^^^
1121 | """ 893 | """str(object='') -> str
1122 | str(object='') -> str 894 | str(bytes_or_buffer[, encoding[, errors]]) -> str
| |
info: Source info: Source
--> main.py:4:18 --> main.py:4:18
@ -603,14 +603,14 @@ mod tests {
// is an int. Navigating to `str` would match pyright's behavior. // is an int. Navigating to `str` would match pyright's behavior.
assert_snapshot!(test.goto_type_definition(), @r#" assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition 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 336 | _LiteralInteger = _PositiveInteger | _NegativeInteger | Literal[0] # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed
364 | 337 |
365 | class int: 338 | class int:
| ^^^ | ^^^
366 | """ 339 | """int([x]) -> integer
367 | int([x]) -> integer 340 | int(x, base=10) -> integer
| |
info: Source info: Source
--> main.py:4:18 --> main.py:4:18
@ -637,14 +637,14 @@ f(**kwargs<CURSOR>)
assert_snapshot!(test.goto_type_definition(), @r#" assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:3458:7 --> stdlib/builtins.pyi:2892:7
| |
3456 | """ 2890 | """See PEP 585"""
3457 | 2891 |
3458 | class dict(MutableMapping[_KT, _VT]): 2892 | class dict(MutableMapping[_KT, _VT]):
| ^^^^ | ^^^^
3459 | """ 2893 | """dict() -> new empty dictionary
3460 | dict() -> new empty dictionary 2894 | dict(mapping) -> new dictionary initialized from a mapping object's
| |
info: Source info: Source
--> main.py:6:5 --> main.py:6:5
@ -668,14 +668,14 @@ f(**kwargs<CURSOR>)
assert_snapshot!(test.goto_type_definition(), @r#" assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:1120:7 --> stdlib/builtins.pyi:892:7
| |
1118 | def __getitem__(self, key: int, /) -> str | int | None: ... 890 | def __getitem__(self, key: int, /) -> str | int | None: ...
1119 | 891 |
1120 | class str(Sequence[str]): 892 | class str(Sequence[str]):
| ^^^ | ^^^
1121 | """ 893 | """str(object='') -> str
1122 | str(object='') -> str 894 | str(bytes_or_buffer[, encoding[, errors]]) -> str
| |
info: Source info: Source
--> main.py:3:17 --> main.py:3:17
@ -761,14 +761,14 @@ f(**kwargs<CURSOR>)
assert_snapshot!(test.goto_type_definition(), @r#" assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:1120:7 --> stdlib/builtins.pyi:892:7
| |
1118 | def __getitem__(self, key: int, /) -> str | int | None: ... 890 | def __getitem__(self, key: int, /) -> str | int | None: ...
1119 | 891 |
1120 | class str(Sequence[str]): 892 | class str(Sequence[str]):
| ^^^ | ^^^
1121 | """ 893 | """str(object='') -> str
1122 | str(object='') -> str 894 | str(bytes_or_buffer[, encoding[, errors]]) -> str
| |
info: Source info: Source
--> main.py:4:27 --> main.py:4:27
@ -792,14 +792,13 @@ f(**kwargs<CURSOR>)
assert_snapshot!(test.goto_type_definition(), @r#" assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition info[goto-type-definition]: Type definition
--> stdlib/types.pyi:1073:11 --> stdlib/types.pyi:922:11
| |
1071 | if sys.version_info >= (3, 10): 920 | if sys.version_info >= (3, 10):
1072 | @final 921 | @final
1073 | class NoneType: 922 | class NoneType:
| ^^^^^^^^ | ^^^^^^^^
1074 | """ 923 | """The type of the None singleton."""
1075 | The type of the None singleton.
| |
info: Source info: Source
--> main.py:3:17 --> main.py:3:17
@ -810,14 +809,14 @@ f(**kwargs<CURSOR>)
| |
info[goto-type-definition]: Type definition info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:1120:7 --> stdlib/builtins.pyi:892:7
| |
1118 | def __getitem__(self, key: int, /) -> str | int | None: ... 890 | def __getitem__(self, key: int, /) -> str | int | None: ...
1119 | 891 |
1120 | class str(Sequence[str]): 892 | class str(Sequence[str]):
| ^^^ | ^^^
1121 | """ 893 | """str(object='') -> str
1122 | str(object='') -> str 894 | str(bytes_or_buffer[, encoding[, errors]]) -> str
| |
info: Source info: Source
--> main.py:3:17 --> main.py:3:17

View file

@ -29,16 +29,16 @@ error[invalid-argument-type]: Argument to function `loads` is incorrect
| ^ Expected `str | bytes | bytearray`, found `Literal[5]` | ^ Expected `str | bytes | bytearray`, found `Literal[5]`
| |
info: Function defined here info: Function defined here
--> stdlib/json/__init__.pyi:221:5 --> stdlib/json/__init__.pyi:219:5
| |
219 | """ 217 | """
220 | 218 |
221 | def loads( 219 | def loads(
| ^^^^^ | ^^^^^
222 | s: str | bytes | bytearray, 220 | s: str | bytes | bytearray,
| -------------------------- Parameter declared here | -------------------------- Parameter declared here
223 | *, 221 | *,
224 | cls: type[JSONDecoder] | None = None, 222 | cls: type[JSONDecoder] | None = None,
| |
info: rule `invalid-argument-type` is enabled by default info: rule `invalid-argument-type` is enabled by default

View file

@ -55,15 +55,13 @@ _VersionInfo: TypeAlias = tuple[int, int, int, str, int]
class _Feature: class _Feature:
def __init__(self, optionalRelease: _VersionInfo, mandatoryRelease: _VersionInfo | None, compiler_flag: int) -> None: ... def __init__(self, optionalRelease: _VersionInfo, mandatoryRelease: _VersionInfo | None, compiler_flag: int) -> None: ...
def getOptionalRelease(self) -> _VersionInfo: 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. This is a 5-tuple, of the same form as sys.version_info.
""" """
def getMandatoryRelease(self) -> _VersionInfo | None: 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 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. the feature was dropped, or the release date is undetermined, is None.

View file

@ -15,8 +15,7 @@ _T_co = TypeVar("_T_co", covariant=True)
_TaskYieldType: TypeAlias = Future[object] | None _TaskYieldType: TypeAlias = Future[object] | None
class Future(Awaitable[_T]): class Future(Awaitable[_T]):
""" """This class is *almost* compatible with concurrent.futures.Future.
This class is *almost* compatible with concurrent.futures.Future.
Differences: Differences:
@ -41,20 +40,15 @@ class Future(Awaitable[_T]):
_asyncio_future_blocking: bool # is a part of duck-typing contract for `Future` _asyncio_future_blocking: bool # is a part of duck-typing contract for `Future`
def __init__(self, *, loop: AbstractEventLoop | None = ...) -> None: ... def __init__(self, *, loop: AbstractEventLoop | None = ...) -> None: ...
def __del__(self) -> 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: def get_loop(self) -> AbstractEventLoop:
""" """Return the event loop the Future is bound to."""
Return the event loop the Future is bound to.
"""
@property @property
def _callbacks(self) -> list[tuple[Callable[[Self], Any], Context]]: ... def _callbacks(self) -> list[tuple[Callable[[Self], Any], Context]]: ...
def add_done_callback(self, fn: Callable[[Self], object], /, *, context: Context | None = None) -> None: 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 callback is called with a single argument - the future object. If
the future is already done when this is called, the callback is 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: 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, If the future is already done or cancelled, return False. Otherwise,
change the future's state to cancelled, schedule the callbacks and change the future's state to cancelled, schedule the callbacks and
@ -71,21 +64,17 @@ class Future(Awaitable[_T]):
""" """
def cancelled(self) -> bool: def cancelled(self) -> bool:
""" """Return True if the future was cancelled."""
Return True if the future was cancelled.
"""
def done(self) -> bool: 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 Done means either that a result / exception are available, or that the
future was cancelled. future was cancelled.
""" """
def result(self) -> _T: 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 If the future has been cancelled, raises CancelledError. If the
future's result isn't yet available, raises InvalidStateError. If future's result isn't yet available, raises InvalidStateError. If
@ -93,8 +82,7 @@ class Future(Awaitable[_T]):
""" """
def exception(self) -> BaseException | None: 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 exception (or None if no exception was set) is returned only if
the future is done. If the future has been cancelled, raises 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: 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. Returns the number of callbacks removed.
""" """
def set_result(self, result: _T, /) -> None: 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 If the future is already done when this method is called, raises
InvalidStateError. InvalidStateError.
""" """
def set_exception(self, exception: type | BaseException, /) -> None: 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 If the future is already done when this method is called, raises
InvalidStateError. InvalidStateError.
""" """
def __iter__(self) -> Generator[Any, None, _T]: def __iter__(self) -> Generator[Any, None, _T]:
""" """Implement iter(self)."""
Implement iter(self).
"""
def __await__(self) -> Generator[Any, None, _T]: 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 @property
def _loop(self) -> AbstractEventLoop: ... def _loop(self) -> AbstractEventLoop: ...
def __class_getitem__(cls, item: Any, /) -> GenericAlias: def __class_getitem__(cls, item: Any, /) -> GenericAlias:
""" """See PEP 585"""
See PEP 585
"""
if sys.version_info >= (3, 12): if sys.version_info >= (3, 12):
_TaskCompatibleCoro: TypeAlias = Coroutine[Any, Any, _T_co] _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, # since the only reason why `asyncio.Future` is invariant is the `set_result()` method,
# and `asyncio.Task.set_result()` always raises. # and `asyncio.Task.set_result()` always raises.
class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportInvalidTypeArguments] 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): if sys.version_info >= (3, 12):
def __init__( 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_context(self) -> Context: ...
def get_stack(self, *, limit: int | None = None) -> list[FrameType]: 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 If the coroutine is not done, this returns the stack where it is
suspended. If the coroutine has completed successfully or was 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: 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, This produces output similar to that of the traceback module,
for the frames retrieved by get_stack(). The limit argument 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): if sys.version_info >= (3, 11):
def cancelling(self) -> int: 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 This count is incremented when .cancel() is called
and may be decremented using .uncancel(). and may be decremented using .uncancel().
""" """
def uncancel(self) -> int: 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 This should be used by tasks that catch CancelledError
and wish to continue indefinitely until they are cancelled again. 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: def __class_getitem__(cls, item: Any, /) -> GenericAlias:
""" """See PEP 585"""
See PEP 585
"""
def get_event_loop() -> AbstractEventLoop: 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 When called from a coroutine or a callback (e.g. scheduled with
call_soon or similar API), this function will always return the 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: 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. This function is thread-specific.
""" """
def _set_running_loop(loop: AbstractEventLoop | None, /) -> None: 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 is a low-level function intended to be used by event loops.
This function is thread-specific. This function is thread-specific.
""" """
def _get_running_loop() -> AbstractEventLoop: 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 is a low-level function intended to be used by event loops.
This function is thread-specific. This function is thread-specific.
""" """
def _register_task(task: Task[Any]) -> None: 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. Returns None.
""" """
def _unregister_task(task: Task[Any]) -> None: def _unregister_task(task: Task[Any]) -> None:
""" """Unregister a task.
Unregister a task.
Returns None. Returns None.
""" """
def _enter_task(loop: AbstractEventLoop, task: Task[Any]) -> 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. 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: 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. Task belongs to loop.
@ -316,18 +279,12 @@ def _leave_task(loop: AbstractEventLoop, task: Task[Any]) -> None:
if sys.version_info >= (3, 12): if sys.version_info >= (3, 12):
def current_task(loop: AbstractEventLoop | None = None) -> Task[Any] | None: 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): if sys.version_info >= (3, 14):
def future_discard_from_awaited_by(future: Future[Any], waiter: Future[Any], /) -> None: ... 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: 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]]: 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.
"""

View file

@ -24,8 +24,7 @@ if sys.version_info >= (3, 10):
*, *,
key: None = None, key: None = None,
) -> int: ) -> 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 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 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, key: None = None,
) -> int: ) -> 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 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 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, key: None = 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. 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, key: None = 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. If x is already in a, insert it to the right of the rightmost x.
@ -130,8 +126,7 @@ else:
def bisect_left( def bisect_left(
a: SupportsLenAndGetItem[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None a: SupportsLenAndGetItem[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None
) -> int: ) -> 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 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 a[i:] have e >= x. So if x already appears in the list, i points just
@ -144,8 +139,7 @@ else:
def bisect_right( def bisect_right(
a: SupportsLenAndGetItem[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None a: SupportsLenAndGetItem[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None
) -> int: ) -> 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 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 a[i:] have e > x. So if x already appears in the list, i points just
@ -158,8 +152,7 @@ else:
def insort_left( def insort_left(
a: MutableSequence[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None a: MutableSequence[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = 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. If x is already in a, insert it to the left of the leftmost x.
@ -170,8 +163,7 @@ else:
def insort_right( def insort_right(
a: MutableSequence[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None a: MutableSequence[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = 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. If x is already in a, insert it to the right of the rightmost x.

View file

@ -17,9 +17,7 @@ BLAKE2S_SALT_SIZE: int = 8
@final @final
class blake2b: class blake2b:
""" """Return a new BLAKE2b hash object."""
Return a new BLAKE2b hash object.
"""
MAX_DIGEST_SIZE: ClassVar[int] = 64 MAX_DIGEST_SIZE: ClassVar[int] = 64
MAX_KEY_SIZE: ClassVar[int] = 64 MAX_KEY_SIZE: ClassVar[int] = 64
@ -47,30 +45,20 @@ class blake2b:
usedforsecurity: bool = True, usedforsecurity: bool = True,
) -> Self: ... ) -> Self: ...
def copy(self) -> Self: def copy(self) -> Self:
""" """Return a copy of the hash object."""
Return a copy of the hash object.
"""
def digest(self) -> bytes: def digest(self) -> bytes:
""" """Return the digest value as a bytes object."""
Return the digest value as a bytes object.
"""
def hexdigest(self) -> str: 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: 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 @final
class blake2s: class blake2s:
""" """Return a new BLAKE2s hash object."""
Return a new BLAKE2s hash object.
"""
MAX_DIGEST_SIZE: ClassVar[int] = 32 MAX_DIGEST_SIZE: ClassVar[int] = 32
MAX_KEY_SIZE: ClassVar[int] = 32 MAX_KEY_SIZE: ClassVar[int] = 32
@ -98,21 +86,13 @@ class blake2s:
usedforsecurity: bool = True, usedforsecurity: bool = True,
) -> Self: ... ) -> Self: ...
def copy(self) -> Self: def copy(self) -> Self:
""" """Return a copy of the hash object."""
Return a copy of the hash object.
"""
def digest(self) -> bytes: def digest(self) -> bytes:
""" """Return the digest value as a bytes object."""
Return the digest value as a bytes object.
"""
def hexdigest(self) -> str: 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: 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.
"""

View file

@ -5,8 +5,7 @@ from typing_extensions import Self
@final @final
class BZ2Compressor: class BZ2Compressor:
""" """Create a compressor object for compressing data incrementally.
Create a compressor object for compressing data incrementally.
compresslevel compresslevel
Compression level, as a number between 1 and 9. Compression level, as a number between 1 and 9.
@ -20,8 +19,7 @@ class BZ2Compressor:
def __init__(self, compresslevel: int = 9, /) -> None: ... def __init__(self, compresslevel: int = 9, /) -> None: ...
def compress(self, data: ReadableBuffer, /) -> bytes: 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. Returns a chunk of compressed data if possible, or b'' otherwise.
@ -30,8 +28,7 @@ class BZ2Compressor:
""" """
def flush(self) -> bytes: def flush(self) -> bytes:
""" """Finish the compression process.
Finish the compression process.
Returns the compressed data left in internal buffers. Returns the compressed data left in internal buffers.
@ -40,15 +37,13 @@ class BZ2Compressor:
@final @final
class BZ2Decompressor: 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. For one-shot decompression, use the decompress() function instead.
""" """
def decompress(self, data: ReadableBuffer, max_length: int = -1) -> bytes: 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 If *max_length* is nonnegative, returns at most *max_length* bytes of
decompressed data. If this limit is reached and further output can be decompressed data. If this limit is reached and further output can be
@ -66,18 +61,12 @@ class BZ2Decompressor:
@property @property
def eof(self) -> bool: 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 @property
def needs_input(self) -> bool: 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 @property
def unused_data(self) -> bytes: def unused_data(self) -> bytes:
""" """Data found after the end of the compressed stream."""
Data found after the end of the compressed stream.
"""

View file

@ -17,8 +17,7 @@ _Handler: TypeAlias = Callable[[UnicodeError], tuple[str | bytes, int]]
_SearchFunction: TypeAlias = Callable[[str], codecs.CodecInfo | None] _SearchFunction: TypeAlias = Callable[[str], codecs.CodecInfo | None]
def register(search_function: _SearchFunction, /) -> 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 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 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): if sys.version_info >= (3, 10):
def unregister(search_function: _SearchFunction, /) -> None: 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. If the search function is not registered, do nothing.
""" """
def register_error(errors: str, handler: _Handler, /) -> None: 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 handler must be a callable object, that will be called with an exception
instance containing information about the location of the encoding/decoding 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: 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 Return the error handler for the specified error handling name or raise a
LookupError, if no handler exists under this name. LookupError, if no handler exists under this name.
@ -75,8 +71,7 @@ _StrToStrEncoding: TypeAlias = Literal["rot13", "rot_13"]
@overload @overload
def encode(obj: ReadableBuffer, encoding: _BytesToBytesEncoding, errors: str = "strict") -> bytes: 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 The default encoding is 'utf-8'. errors may be given to set a
different error handling scheme. Default is 'strict' meaning that encoding 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: ... def encode(obj: str, encoding: str = "utf-8", errors: str = "strict") -> bytes: ...
@overload @overload
def decode(obj: ReadableBuffer, encoding: _BytesToBytesEncoding, errors: str = "strict") -> bytes: # type: ignore[overload-overlap] 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 Default encoding is 'utf-8'. errors may be given to set a
different error handling scheme. Default is 'strict' meaning that encoding 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 @overload
def decode(obj: ReadableBuffer, encoding: str = "utf-8", errors: str = "strict") -> str: ... def decode(obj: ReadableBuffer, encoding: str = "utf-8", errors: str = "strict") -> str: ...
def lookup(encoding: str, /) -> codecs.CodecInfo: 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 charmap_build(map: str, /) -> _CharMap: ...
def ascii_decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... def ascii_decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ...

View file

@ -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 class dict_keys(KeysView[_KT_co], Generic[_KT_co, _VT_co]): # undocumented
def __eq__(self, value: object, /) -> bool: ... def __eq__(self, value: object, /) -> bool: ...
def __reversed__(self) -> Iterator[_KT_co]: 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] __hash__: ClassVar[None] # type: ignore[assignment]
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
def isdisjoint(self, other: Iterable[_KT_co], /) -> bool: 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): if sys.version_info >= (3, 10):
@property @property
def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: def mapping(self) -> MappingProxyType[_KT_co, _VT_co]:
""" """dictionary that this view refers to"""
dictionary that this view refers to
"""
@final @final
class dict_values(ValuesView[_VT_co], Generic[_KT_co, _VT_co]): # undocumented class dict_values(ValuesView[_VT_co], Generic[_KT_co, _VT_co]): # undocumented
def __reversed__(self) -> Iterator[_VT_co]: 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): if sys.version_info >= (3, 10):
@property @property
def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: def mapping(self) -> MappingProxyType[_KT_co, _VT_co]:
""" """dictionary that this view refers to"""
dictionary that this view refers to
"""
@final @final
class dict_items(ItemsView[_KT_co, _VT_co]): # undocumented class dict_items(ItemsView[_KT_co, _VT_co]): # undocumented
def __eq__(self, value: object, /) -> bool: ... def __eq__(self, value: object, /) -> bool: ...
def __reversed__(self) -> Iterator[tuple[_KT_co, _VT_co]]: 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] __hash__: ClassVar[None] # type: ignore[assignment]
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
def isdisjoint(self, other: Iterable[tuple[_KT_co, _VT_co]], /) -> bool: 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): if sys.version_info >= (3, 10):
@property @property
def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: 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): if sys.version_info >= (3, 12):
@runtime_checkable @runtime_checkable

View file

@ -17,14 +17,10 @@ class _Reader(Protocol):
def seek(self, n: int, /) -> Any: ... def seek(self, n: int, /) -> Any: ...
class BaseStream(BufferedIOBase): class BaseStream(BufferedIOBase):
""" """Mode-checking helper functions."""
Mode-checking helper functions.
"""
class DecompressReader(RawIOBase): class DecompressReader(RawIOBase):
""" """Adapts the decompressor API to a RawIOBase reader API"""
Adapts the decompressor API to a RawIOBase reader API
"""
def __init__( def __init__(
self, self,

View file

@ -23,8 +23,7 @@ class ContextVar(Generic[_T]):
def name(self) -> str: ... def name(self) -> str: ...
@overload @overload
def get(self) -> _T: 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: 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 * return the value of the default argument of the method, if provided; or
@ -38,8 +37,7 @@ class ContextVar(Generic[_T]):
@overload @overload
def get(self, default: _D, /) -> _D | _T: ... def get(self, default: _D, /) -> _D | _T: ...
def set(self, value: _T, /) -> Token[_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. 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: 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 The variable is reset to the value it had before the `ContextVar.set()` that
created the token was used. created the token was used.
""" """
def __class_getitem__(cls, item: Any, /) -> GenericAlias: def __class_getitem__(cls, item: Any, /) -> GenericAlias:
""" """See PEP 585"""
See PEP 585
"""
@final @final
class Token(Generic[_T]): class Token(Generic[_T]):
@ -69,21 +64,15 @@ class Token(Generic[_T]):
MISSING: ClassVar[object] MISSING: ClassVar[object]
__hash__: ClassVar[None] # type: ignore[assignment] __hash__: ClassVar[None] # type: ignore[assignment]
def __class_getitem__(cls, item: Any, /) -> GenericAlias: def __class_getitem__(cls, item: Any, /) -> GenericAlias:
""" """See PEP 585"""
See PEP 585
"""
if sys.version_info >= (3, 14): if sys.version_info >= (3, 14):
def __enter__(self) -> Self: def __enter__(self) -> Self:
""" """Enter into Token context manager."""
Enter into Token context manager.
"""
def __exit__( def __exit__(
self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None
) -> None: ) -> None:
""" """Exit from Token context manager, restore the linked ContextVar."""
Exit from Token context manager, restore the linked ContextVar.
"""
def copy_context() -> Context: ... def copy_context() -> Context: ...
@ -94,8 +83,7 @@ class Context(Mapping[ContextVar[Any], Any]):
def __init__(self) -> None: ... def __init__(self) -> None: ...
@overload @overload
def get(self, key: ContextVar[_T], default: None = None, /) -> _T | None: 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, If `key` does not exist, return `default`. If `default` is not given,
return None. return None.
@ -107,23 +95,15 @@ class Context(Mapping[ContextVar[Any], Any]):
def get(self, key: ContextVar[_T], default: _D, /) -> _T | _D: ... 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 run(self, callable: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> _T: ...
def copy(self) -> Context: 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] __hash__: ClassVar[None] # type: ignore[assignment]
def __getitem__(self, key: ContextVar[_T], /) -> _T: def __getitem__(self, key: ContextVar[_T], /) -> _T:
""" """Return self[key]."""
Return self[key].
"""
def __iter__(self) -> Iterator[ContextVar[Any]]: def __iter__(self) -> Iterator[ContextVar[Any]]:
""" """Implement iter(self)."""
Implement iter(self).
"""
def __len__(self) -> int: def __len__(self) -> int:
""" """Return len(self)."""
Return len(self).
"""
def __eq__(self, value: object, /) -> bool: ... def __eq__(self, value: object, /) -> bool: ...

View file

@ -29,8 +29,7 @@ class Error(Exception): ...
_DialectLike: TypeAlias = str | Dialect | csv.Dialect | type[Dialect | csv.Dialect] _DialectLike: TypeAlias = str | Dialect | csv.Dialect | type[Dialect | csv.Dialect]
class Dialect: class Dialect:
""" """CSV dialect
CSV dialect
The Dialect type records CSV parsing and generation options. The Dialect type records CSV parsing and generation options.
""" """
@ -59,8 +58,7 @@ class Dialect:
if sys.version_info >= (3, 10): if sys.version_info >= (3, 10):
# This class calls itself _csv.reader. # This class calls itself _csv.reader.
class Reader: class Reader:
""" """CSV reader
CSV reader
Reader objects are responsible for reading and parsing tabular data Reader objects are responsible for reading and parsing tabular data
in CSV format. in CSV format.
@ -70,19 +68,14 @@ if sys.version_info >= (3, 10):
def dialect(self) -> Dialect: ... def dialect(self) -> Dialect: ...
line_num: int line_num: int
def __iter__(self) -> Self: def __iter__(self) -> Self:
""" """Implement iter(self)."""
Implement iter(self).
"""
def __next__(self) -> list[str]: def __next__(self) -> list[str]:
""" """Implement next(self)."""
Implement next(self).
"""
# This class calls itself _csv.writer. # This class calls itself _csv.writer.
class Writer: class Writer:
""" """CSV writer
CSV writer
Writer objects are responsible for generating tabular data Writer objects are responsible for generating tabular data
in CSV format from sequence input. in CSV format from sequence input.
@ -92,32 +85,28 @@ if sys.version_info >= (3, 10):
def dialect(self) -> Dialect: ... def dialect(self) -> Dialect: ...
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
def writerow(self, row: Iterable[Any], /) -> Any: def writerow(self, row: Iterable[Any], /) -> Any:
""" """writerow(iterable)
writerow(iterable)
Construct and write a CSV record from an iterable of fields. Non-string Construct and write a CSV record from an iterable of fields. Non-string
elements will be converted to string. elements will be converted to string.
""" """
def writerows(self, rows: Iterable[Iterable[Any]], /) -> None: 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 Construct and write a series of iterables to a csv file. Non-string
elements will be converted to string. elements will be converted to string.
""" """
else: else:
def writerow(self, row: Iterable[Any]) -> Any: def writerow(self, row: Iterable[Any]) -> Any:
""" """writerow(iterable)
writerow(iterable)
Construct and write a CSV record from an iterable of fields. Non-string Construct and write a CSV record from an iterable of fields. Non-string
elements will be converted to string. elements will be converted to string.
""" """
def writerows(self, rows: Iterable[Iterable[Any]]) -> None: 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 Construct and write a series of iterables to a csv file. Non-string
elements will be converted to string. elements will be converted to string.
@ -159,8 +148,7 @@ def writer(
quoting: _QuotingType = 0, quoting: _QuotingType = 0,
strict: bool = False, strict: bool = False,
) -> _writer: ) -> _writer:
""" """csv_writer = csv.writer(fileobj [, dialect='excel']
csv_writer = csv.writer(fileobj [, dialect='excel']
[optional keyword args]) [optional keyword args])
for row in sequence: for row in sequence:
csv_writer.writerow(row) csv_writer.writerow(row)
@ -188,8 +176,7 @@ def reader(
quoting: _QuotingType = 0, quoting: _QuotingType = 0,
strict: bool = False, strict: bool = False,
) -> _reader: ) -> _reader:
""" """csv_reader = reader(iterable [, dialect='excel']
csv_reader = reader(iterable [, dialect='excel']
[optional keyword args]) [optional keyword args])
for row in csv_reader: for row in csv_reader:
process(row) process(row)
@ -217,35 +204,30 @@ def register_dialect(
quoting: _QuotingType = 0, quoting: _QuotingType = 0,
strict: bool = False, strict: bool = False,
) -> None: ) -> 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]]) dialect = csv.register_dialect(name[, dialect[, **fmtparams]])
""" """
def unregister_dialect(name: str) -> None: 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) csv.unregister_dialect(name)
""" """
def get_dialect(name: str) -> Dialect: 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) dialect = csv.get_dialect(name)
""" """
def list_dialects() -> list[str]: 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() names = csv.list_dialects()
""" """
def field_size_limit(new_limit: int = ...) -> int: 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]) csv.field_size_limit([limit])

View file

@ -33,38 +33,52 @@ if sys.platform == "win32":
_COMError_Details: TypeAlias = tuple[str | None, str | None, str | None, int | None, int | None] _COMError_Details: TypeAlias = tuple[str | None, str | None, str | None, int | None, int | None]
class COMError(Exception): class COMError(Exception):
"""Raised when a COM method call failed."""
hresult: int hresult: int
text: str | None text: str | None
details: _COMError_Details details: _COMError_Details
def __init__(self, hresult: int, text: str | None, details: _COMError_Details) -> None: ... 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_HRESULT: int
FUNCFLAG_STDCALL: 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 get_last_error() -> int: ...
def set_last_error(value: int) -> int: ... def set_last_error(value: int) -> int: ...
def LoadLibrary(name: str, load_flags: int = 0, /) -> int: ... def LoadLibrary(name: str, load_flags: int = 0, /) -> int:
def FreeLibrary(handle: int, /) -> None: ... """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: else:
def dlclose(handle: int, /) -> None: def dlclose(handle: int, /) -> None:
""" """dlclose a library"""
dlclose a library
"""
# The default for flag is RTLD_GLOBAL|RTLD_LOCAL, which is platform dependent. # The default for flag is RTLD_GLOBAL|RTLD_LOCAL, which is platform dependent.
def dlopen(name: StrOrBytesPath, flag: int = ..., /) -> int: 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: def dlsym(handle: int, name: str, /) -> int:
""" """find symbol in shared library"""
find symbol in shared library
"""
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
# This class is not exposed. It calls itself _ctypes.CType_Type. # 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] def __rmul__(self: type[_CT], value: int, /) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]
class _SimpleCData(_CData, Generic[_T], metaclass=_PyCSimpleType): class _SimpleCData(_CData, Generic[_T], metaclass=_PyCSimpleType):
""" """XXX to be provided"""
XXX to be provided
"""
value: _T value: _T
# The TypeVar can be unsolved here, # 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] def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]
class _Pointer(_PointerLike, _CData, Generic[_CT], metaclass=_PyCPointerType): class _Pointer(_PointerLike, _CData, Generic[_CT], metaclass=_PyCPointerType):
""" """XXX to be provided"""
XXX to be provided
"""
_type_: type[_CT] _type_: type[_CT]
contents: _CT contents: _CT
@ -151,22 +161,17 @@ class _Pointer(_PointerLike, _CData, Generic[_CT], metaclass=_PyCPointerType):
def __init__(self, arg: _CT) -> None: ... def __init__(self, arg: _CT) -> None: ...
@overload @overload
def __getitem__(self, key: int, /) -> Any: def __getitem__(self, key: int, /) -> Any:
""" """Return self[key]."""
Return self[key].
"""
@overload @overload
def __getitem__(self, key: slice, /) -> list[Any]: ... def __getitem__(self, key: slice, /) -> list[Any]: ...
def __setitem__(self, key: int, value: Any, /) -> None: def __setitem__(self, key: int, value: Any, /) -> None:
""" """Set self[key] to value."""
Set self[key] to value.
"""
if sys.version_info < (3, 14): if sys.version_info < (3, 14):
@overload @overload
def POINTER(type: None, /) -> type[c_void_p]: 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 type
A ctypes type. A ctypes type.
@ -178,8 +183,7 @@ if sys.version_info < (3, 14):
@overload @overload
def POINTER(type: type[_CT], /) -> type[_Pointer[_CT]]: ... def POINTER(type: type[_CT], /) -> type[_Pointer[_CT]]: ...
def pointer(obj: _CT, /) -> _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 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 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): if sys.version_info >= (3, 14):
def byref(obj: _CData | _CDataType, offset: int = 0, /) -> _CArgObject: 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: else:
def byref(obj: _CData | _CDataType, offset: int = 0) -> _CArgObject: 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 Return a pointer lookalike to a C instance, only usable
as function argument 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] def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]
class CFuncPtr(_PointerLike, _CData, metaclass=_PyCFuncPtrType): class CFuncPtr(_PointerLike, _CData, metaclass=_PyCFuncPtrType):
""" """Function Pointer"""
Function Pointer
"""
restype: type[_CDataType] | Callable[[int], Any] | None restype: type[_CDataType] | Callable[[int], Any] | None
argtypes: Sequence[type[_CDataType]] argtypes: Sequence[type[_CDataType]]
@ -246,9 +245,7 @@ class CFuncPtr(_PointerLike, _CData, metaclass=_PyCFuncPtrType):
) -> Self: ... ) -> Self: ...
def __call__(self, *args: Any, **kwargs: Any) -> Any: def __call__(self, *args: Any, **kwargs: Any) -> Any:
""" """Call self as a function."""
Call self as a function.
"""
_GetT = TypeVar("_GetT") _GetT = TypeVar("_GetT")
_SetT = TypeVar("_SetT") _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] def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]
class Union(_CData, metaclass=_UnionType): class Union(_CData, metaclass=_UnionType):
""" """Union base class"""
Union base class
"""
_fields_: ClassVar[Sequence[tuple[str, type[_CDataType]] | tuple[str, type[_CDataType], int]]] _fields_: ClassVar[Sequence[tuple[str, type[_CDataType]] | tuple[str, type[_CDataType], int]]]
_pack_: ClassVar[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] def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]
class Structure(_CData, metaclass=_PyCStructType): class Structure(_CData, metaclass=_PyCStructType):
""" """Structure base class"""
Structure base class
"""
_fields_: ClassVar[Sequence[tuple[str, type[_CDataType]] | tuple[str, type[_CDataType], int]]] _fields_: ClassVar[Sequence[tuple[str, type[_CDataType]] | tuple[str, type[_CDataType], int]]]
_pack_: ClassVar[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] def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]
class Array(_CData, Generic[_CT], metaclass=_PyCArrayType): 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 The recommended way to create concrete array types is by multiplying any
ctypes data type with a non-negative integer. Alternatively, you can subclass 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: ... def __init__(self, *args: Any) -> None: ...
@overload @overload
def __getitem__(self, key: int, /) -> Any: def __getitem__(self, key: int, /) -> Any:
""" """Return self[key]."""
Return self[key].
"""
@overload @overload
def __getitem__(self, key: slice, /) -> list[Any]: ... def __getitem__(self, key: slice, /) -> list[Any]: ...
@overload @overload
def __setitem__(self, key: int, value: Any, /) -> None: def __setitem__(self, key: int, value: Any, /) -> None:
""" """Set self[key] to value."""
Set self[key] to value.
"""
@overload @overload
def __setitem__(self, key: slice, value: Iterable[Any], /) -> None: ... 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 # Can't inherit from Sized because the metaclass conflict between
# Sized and _CData prevents using _CDataMeta. # Sized and _CData prevents using _CDataMeta.
def __len__(self) -> int: def __len__(self) -> int:
""" """Return len(self)."""
Return len(self).
"""
def __class_getitem__(cls, item: Any, /) -> GenericAlias: def __class_getitem__(cls, item: Any, /) -> GenericAlias:
""" """See PEP 585"""
See PEP 585
"""
def addressof(obj: _CData | _CDataType, /) -> int: 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: def alignment(obj_or_type: _CData | _CDataType | type[_CData | _CDataType], /) -> int:
""" """alignment(C type) -> integer
alignment(C type) -> integer
alignment(C instance) -> integer alignment(C instance) -> integer
Return the alignment requirements of a C instance Return the alignment requirements of a C instance
""" """
def get_errno() -> int: ... def get_errno() -> int: ...
def resize(obj: _CData | _CDataType, size: int, /) -> None: 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 set_errno(value: int, /) -> int: ...
def sizeof(obj_or_type: _CData | _CDataType | type[_CData | _CDataType], /) -> 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 PyObj_FromPtr(address: int, /) -> Any: ...
def Py_DECREF(o: _T, /) -> _T: ... def Py_DECREF(o: _T, /) -> _T: ...
def Py_INCREF(o: _T, /) -> _T: ... def Py_INCREF(o: _T, /) -> _T: ...
def buffer_info(o: _CData | _CDataType | type[_CData | _CDataType], /) -> tuple[str, int, tuple[int, ...]]: 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_cdeclfunction(address: int, arguments: tuple[Any, ...], /) -> Any: ...
def call_function(address: int, arguments: tuple[Any, ...], /) -> Any: ... def call_function(address: int, arguments: tuple[Any, ...], /) -> Any: ...

View file

@ -277,23 +277,16 @@ _C_API: Any
version: bytes version: bytes
def baudrate() -> int: 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: def beep() -> None:
""" """Emit a short attention sound."""
Emit a short attention sound.
"""
def can_change_color() -> bool: 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: def cbreak(flag: bool = True, /) -> None:
""" """Enter cbreak mode.
Enter cbreak mode.
flag flag
If false, the effect is the same as calling nocbreak(). 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]: 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 color_number
The number of the color (0 - (COLORS-1)). 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: 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 pair_number
The number of the color pair. The number of the color pair.
@ -328,8 +319,7 @@ def color_pair(pair_number: int, /) -> int:
""" """
def curs_set(visibility: int, /) -> int: def curs_set(visibility: int, /) -> int:
""" """Set the cursor state.
Set the cursor state.
visibility visibility
0 for invisible, 1 for normal visible, or 2 for very visible. 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: 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. 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: 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. 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: def delay_output(ms: int, /) -> None:
""" """Insert a pause in output.
Insert a pause in output.
ms ms
Duration in milliseconds. Duration in milliseconds.
""" """
def doupdate() -> None: 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: def echo(flag: bool = True, /) -> None:
""" """Enter echo mode.
Enter echo mode.
flag flag
If false, the effect is the same as calling noecho(). If false, the effect is the same as calling noecho().
@ -382,34 +366,27 @@ def echo(flag: bool = True, /) -> None:
""" """
def endwin() -> 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: def erasechar() -> bytes:
""" """Return the user's current erase character."""
Return the user's current erase character.
"""
def filter() -> None: ... def filter() -> None: ...
def flash() -> 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. That is, change it to reverse-video and then change it back in a short interval.
""" """
def flushinp() -> None: 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 This throws away any typeahead that has been typed by the user and has not
yet been processed by the program. yet been processed by the program.
""" """
def get_escdelay() -> int: 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, Gets the number of milliseconds to wait after reading an escape character,
to distinguish between an individual escape character entered on the to distinguish between an individual escape character entered on the
@ -417,39 +394,34 @@ def get_escdelay() -> int:
""" """
def get_tabsize() -> 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 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. character to spaces as it adds the tab to a window.
""" """
def getmouse() -> tuple[int, int, int, int, int]: 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 After getch() returns KEY_MOUSE to signal a mouse event, this function
returns a 5-tuple (id, x, y, z, bstate). returns a 5-tuple (id, x, y, z, bstate).
""" """
def getsyx() -> tuple[int, int]: 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). Return a (y, x) tuple. If leaveok is currently true, return (-1, -1).
""" """
def getwin(file: SupportsRead[bytes], /) -> window: 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, The routine then creates and initializes a new window using that data,
returning the new window object. returning the new window object.
""" """
def halfdelay(tenths: int, /) -> None: def halfdelay(tenths: int, /) -> None:
""" """Enter half-delay mode.
Enter half-delay mode.
tenths tenths
Maximal blocking delay in tenths of seconds (1 - 255). Maximal blocking delay in tenths of seconds (1 - 255).
@ -458,14 +430,11 @@ def halfdelay(tenths: int, /) -> None:
""" """
def has_colors() -> bool: 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): if sys.version_info >= (3, 10):
def has_extended_color_support() -> bool: 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 Extended color support allows more than 256 color-pairs for terminals
that support more than 16 colors (e.g. xterm-256color). 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): if sys.version_info >= (3, 14):
def assume_default_colors(fg: int, bg: int, /) -> None: 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. Assign terminal default foreground/background colors to color number -1.
Change the definition of the color-pair 0 to (fg, bg). 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: 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: 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: 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
Key number. Key number.
""" """
def init_color(color_number: int, r: int, g: int, b: int, /) -> None: 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 color_number
The number of the color to be changed (0 - (COLORS-1)). 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: 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 pair_number
The number of the color-pair to be changed (1 - (COLOR_PAIRS-1)). 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: def initscr() -> window:
""" """Initialize the library.
Initialize the library.
Return a WindowObject which represents the whole screen. Return a WindowObject which represents the whole screen.
""" """
def intrflush(flag: bool, /) -> None: ... def intrflush(flag: bool, /) -> None: ...
def is_term_resized(nlines: int, ncols: int, /) -> bool: 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 nlines
Height. Height.
@ -552,42 +511,34 @@ def is_term_resized(nlines: int, ncols: int, /) -> bool:
""" """
def isendwin() -> bool: def isendwin() -> bool:
""" """Return True if endwin() has been called."""
Return True if endwin() has been called.
"""
def keyname(key: int, /) -> bytes: def keyname(key: int, /) -> bytes:
""" """Return the name of specified key.
Return the name of specified key.
key key
Key number. Key number.
""" """
def killchar() -> bytes: def killchar() -> bytes:
""" """Return the user's current line kill character."""
Return the user's current line kill character.
"""
def longname() -> bytes: 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 The maximum length of a verbose description is 128 characters. It is defined
only after the call to initscr(). only after the call to initscr().
""" """
def meta(yes: bool, /) -> None: 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, If yes is True, allow 8-bit characters to be input. If yes is False,
allow only 7-bit characters. allow only 7-bit characters.
""" """
def mouseinterval(interval: int, /) -> None: 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 interval
Time in milliseconds. Time in milliseconds.
@ -598,8 +549,7 @@ def mouseinterval(interval: int, /) -> None:
""" """
def mousemask(newmask: int, /) -> tuple[int, int]: 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 Return a tuple (availmask, oldmask). availmask indicates which of the
specified mouse events can be reported; on complete failure it returns 0. 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: def napms(ms: int, /) -> int:
""" """Sleep for specified time.
Sleep for specified time.
ms ms
Duration in milliseconds. Duration in milliseconds.
""" """
def newpad(nlines: int, ncols: int, /) -> window: 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 nlines
Height. 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: 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. Return a new window.
nlines nlines
@ -644,8 +591,7 @@ def newwin(nlines: int, ncols: int, begin_y: int = ..., begin_x: int = ..., /) -
""" """
def nl(flag: bool = True, /) -> None: def nl(flag: bool = True, /) -> None:
""" """Enter newline mode.
Enter newline mode.
flag flag
If false, the effect is the same as calling nonl(). If false, the effect is the same as calling nonl().
@ -655,67 +601,58 @@ def nl(flag: bool = True, /) -> None:
""" """
def nocbreak() -> None: def nocbreak() -> None:
""" """Leave cbreak mode.
Leave cbreak mode.
Return to normal "cooked" mode with line buffering. Return to normal "cooked" mode with line buffering.
""" """
def noecho() -> None: def noecho() -> None:
""" """Leave echo mode.
Leave echo mode.
Echoing of input characters is turned off. Echoing of input characters is turned off.
""" """
def nonl() -> None: def nonl() -> None:
""" """Leave newline mode.
Leave newline mode.
Disable translation of return into newline on input, and disable low-level Disable translation of return into newline on input, and disable low-level
translation of newline into newline/return on output. translation of newline into newline/return on output.
""" """
def noqiflush() -> None: def noqiflush() -> None:
""" """Disable queue flushing.
Disable queue flushing.
When queue flushing is disabled, normal flush of input and output queues When queue flushing is disabled, normal flush of input and output queues
associated with the INTR, QUIT and SUSP characters will not be done. associated with the INTR, QUIT and SUSP characters will not be done.
""" """
def noraw() -> None: def noraw() -> None:
""" """Leave raw mode.
Leave raw mode.
Return to normal "cooked" mode with line buffering. Return to normal "cooked" mode with line buffering.
""" """
def pair_content(pair_number: int, /) -> tuple[int, int]: 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 pair_number
The number of the color pair (0 - (COLOR_PAIRS-1)). The number of the color pair (0 - (COLOR_PAIRS-1)).
""" """
def pair_number(attr: int, /) -> int: 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. color_pair() is the counterpart to this function.
""" """
def putp(string: ReadOnlyBuffer, /) -> None: 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. Note that the output of putp() always goes to standard output.
""" """
def qiflush(flag: bool = True, /) -> None: def qiflush(flag: bool = True, /) -> None:
""" """Enable queue flushing.
Enable queue flushing.
flag flag
If false, the effect is the same as calling noqiflush(). 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: def raw(flag: bool = True, /) -> None:
""" """Enter raw mode.
Enter raw mode.
flag flag
If false, the effect is the same as calling noraw(). 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: 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: 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: def resetty() -> None:
""" """Restore terminal mode."""
Restore terminal mode.
"""
def resize_term(nlines: int, ncols: int, /) -> None: 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 nlines
Height. Height.
@ -768,8 +697,7 @@ def resize_term(nlines: int, ncols: int, /) -> None:
""" """
def resizeterm(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 nlines
Height. Height.
@ -781,13 +709,10 @@ def resizeterm(nlines: int, ncols: int, /) -> None:
""" """
def savetty() -> None: def savetty() -> None:
""" """Save terminal mode."""
Save terminal mode.
"""
def set_escdelay(ms: int, /) -> None: def set_escdelay(ms: int, /) -> None:
""" """Sets the curses ESCDELAY setting.
Sets the curses ESCDELAY setting.
ms ms
length of the delay in milliseconds. length of the delay in milliseconds.
@ -798,8 +723,7 @@ def set_escdelay(ms: int, /) -> None:
""" """
def set_tabsize(size: int, /) -> None: def set_tabsize(size: int, /) -> None:
""" """Sets the curses TABSIZE setting.
Sets the curses TABSIZE setting.
size size
rendered cell width of a tab character. rendered cell width of a tab character.
@ -809,8 +733,7 @@ def set_tabsize(size: int, /) -> None:
""" """
def setsyx(y: int, x: int, /) -> None: def setsyx(y: int, x: int, /) -> None:
""" """Set the virtual screen cursor.
Set the virtual screen cursor.
y y
Y-coordinate. Y-coordinate.
@ -821,8 +744,7 @@ def setsyx(y: int, x: int, /) -> None:
""" """
def setupterm(term: str | None = None, fd: int = -1) -> None: def setupterm(term: str | None = None, fd: int = -1) -> None:
""" """Initialize the terminal.
Initialize the terminal.
term term
Terminal name. Terminal name.
@ -833,8 +755,7 @@ def setupterm(term: str | None = None, fd: int = -1) -> None:
""" """
def start_color() -> 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 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 color manipulation routine is called. It is good practice to call this
@ -845,18 +766,13 @@ def start_color() -> None:
""" """
def termattrs() -> int: 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: 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: def tigetflag(capname: str, /) -> int:
""" """Return the value of the Boolean capability.
Return the value of the Boolean capability.
capname capname
The terminfo capability name. The terminfo capability name.
@ -866,8 +782,7 @@ def tigetflag(capname: str, /) -> int:
""" """
def tigetnum(capname: str, /) -> int: def tigetnum(capname: str, /) -> int:
""" """Return the value of the numeric capability.
Return the value of the numeric capability.
capname capname
The terminfo capability name. The terminfo capability name.
@ -877,8 +792,7 @@ def tigetnum(capname: str, /) -> int:
""" """
def tigetstr(capname: str, /) -> bytes | None: def tigetstr(capname: str, /) -> bytes | None:
""" """Return the value of the string capability.
Return the value of the string capability.
capname capname
The terminfo capability name. The terminfo capability name.
@ -900,16 +814,14 @@ def tparm(
i9: int = 0, i9: int = 0,
/, /,
) -> bytes: ) -> bytes:
""" """Instantiate the specified byte string with the supplied parameters.
Instantiate the specified byte string with the supplied parameters.
str str
Parameterized byte string obtained from the terminfo database. Parameterized byte string obtained from the terminfo database.
""" """
def typeahead(fd: int, /) -> None: 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 fd
File descriptor. File descriptor.
@ -918,39 +830,30 @@ def typeahead(fd: int, /) -> None:
""" """
def unctrl(ch: _ChType, /) -> bytes: 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, Control characters are displayed as a caret followed by the character,
for example as ^C. Printing characters are left as they are. for example as ^C. Printing characters are left as they are.
""" """
def unget_wch(ch: int | str, /) -> None: 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: 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: 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. The following getmouse() will return the given state data.
""" """
def update_lines_cols() -> None: ... def update_lines_cols() -> None: ...
def use_default_colors() -> 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: 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 If used, this function should be called before initscr() or newterm() are
called. called.
@ -969,8 +872,7 @@ class window: # undocumented
encoding: str encoding: str
@overload @overload
def addch(self, ch: _ChType, attr: int = ...) -> None: 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. Paint the character.
y y
@ -992,8 +894,7 @@ class window: # undocumented
def addch(self, y: int, x: int, ch: _ChType, attr: int = ...) -> None: ... def addch(self, y: int, x: int, ch: _ChType, attr: int = ...) -> None: ...
@overload @overload
def addnstr(self, str: str, n: int, attr: int = ...) -> None: 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. Paint at most n characters of the string.
y y
@ -1017,8 +918,7 @@ class window: # undocumented
def addnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... def addnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ...
@overload @overload
def addstr(self, str: str, attr: int = ...) -> None: def addstr(self, str: str, attr: int = ...) -> None:
""" """addstr([y, x,] str, [attr])
addstr([y, x,] str, [attr])
Paint the string. Paint the string.
y y
@ -1039,23 +939,16 @@ class window: # undocumented
@overload @overload
def addstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... def addstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ...
def attroff(self, 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: 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: 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: def bkgd(self, ch: _ChType, attr: int = ..., /) -> None:
""" """Set the background property of the window.
Set the background property of the window.
ch ch
Background character. Background character.
@ -1064,8 +957,7 @@ class window: # undocumented
""" """
def bkgdset(self, ch: _ChType, attr: int = ..., /) -> None: def bkgdset(self, ch: _ChType, attr: int = ..., /) -> None:
""" """Set the window's background.
Set the window's background.
ch ch
Background character. Background character.
@ -1084,8 +976,7 @@ class window: # undocumented
bl: _ChType = ..., bl: _ChType = ...,
br: _ChType = ..., br: _ChType = ...,
) -> None: ) -> None:
""" """Draw a border around the edges of the window.
Draw a border around the edges of the window.
ls ls
Left side. Left side.
@ -1112,8 +1003,7 @@ class window: # undocumented
@overload @overload
def box(self) -> None: def box(self) -> None:
""" """box([verch=0, horch=0])
box([verch=0, horch=0])
Draw a border around the edges of the window. Draw a border around the edges of the window.
verch verch
@ -1129,8 +1019,7 @@ class window: # undocumented
def box(self, vertch: _ChType = ..., horch: _ChType = ...) -> None: ... def box(self, vertch: _ChType = ..., horch: _ChType = ...) -> None: ...
@overload @overload
def chgat(self, attr: int) -> None: def chgat(self, attr: int) -> None:
""" """chgat([y, x,] [n=-1,] attr)
chgat([y, x,] [n=-1,] attr)
Set the attributes of characters. Set the attributes of characters.
y y
@ -1163,8 +1052,7 @@ class window: # undocumented
def cursyncup(self) -> None: ... def cursyncup(self) -> None: ...
@overload @overload
def delch(self) -> None: def delch(self) -> None:
""" """delch([y, x])
delch([y, x])
Delete any character at (y, x). Delete any character at (y, x).
y y
@ -1178,8 +1066,7 @@ class window: # undocumented
def deleteln(self) -> None: ... def deleteln(self) -> None: ...
@overload @overload
def derwin(self, begin_y: int, begin_x: int) -> window: 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). Create a sub-window (window-relative coordinates).
nlines nlines
@ -1199,8 +1086,7 @@ class window: # undocumented
@overload @overload
def derwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ... def derwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ...
def echochar(self, ch: _ChType, attr: int = ..., /) -> None: 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 ch
Character to add. Character to add.
@ -1209,8 +1095,7 @@ class window: # undocumented
""" """
def enclose(self, y: int, x: int, /) -> bool: 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
Y-coordinate. Y-coordinate.
@ -1221,14 +1106,11 @@ class window: # undocumented
def erase(self) -> None: ... def erase(self) -> None: ...
def getbegyx(self) -> tuple[int, int]: ... def getbegyx(self) -> tuple[int, int]: ...
def getbkgd(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 @overload
def getch(self) -> int: def getch(self) -> int:
""" """getch([y, x])
getch([y, x])
Get a character code from terminal keyboard. Get a character code from terminal keyboard.
y y
@ -1245,8 +1127,7 @@ class window: # undocumented
def getch(self, y: int, x: int) -> int: ... def getch(self, y: int, x: int) -> int: ...
@overload @overload
def get_wch(self) -> int | str: def get_wch(self) -> int | str:
""" """get_wch([y, x])
get_wch([y, x])
Get a wide character from terminal keyboard. Get a wide character from terminal keyboard.
y y
@ -1262,8 +1143,7 @@ class window: # undocumented
def get_wch(self, y: int, x: int) -> int | str: ... def get_wch(self, y: int, x: int) -> int | str: ...
@overload @overload
def getkey(self) -> str: def getkey(self) -> str:
""" """getkey([y, x])
getkey([y, x])
Get a character (string) from terminal keyboard. Get a character (string) from terminal keyboard.
y y
@ -1282,8 +1162,7 @@ class window: # undocumented
def getparyx(self) -> tuple[int, int]: ... def getparyx(self) -> tuple[int, int]: ...
@overload @overload
def getstr(self) -> bytes: 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. Read a string from the user, with primitive line editing capacity.
y y
@ -1303,8 +1182,7 @@ class window: # undocumented
def getyx(self) -> tuple[int, int]: ... def getyx(self) -> tuple[int, int]: ...
@overload @overload
def hline(self, ch: _ChType, n: int) -> None: 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. Display a horizontal line.
y y
@ -1326,8 +1204,7 @@ class window: # undocumented
def immedok(self, flag: bool) -> None: ... def immedok(self, flag: bool) -> None: ...
@overload @overload
def inch(self) -> int: def inch(self) -> int:
""" """inch([y, x])
inch([y, x])
Return the character at the given position in the window. Return the character at the given position in the window.
y y
@ -1342,8 +1219,7 @@ class window: # undocumented
def inch(self, y: int, x: int) -> int: ... def inch(self, y: int, x: int) -> int: ...
@overload @overload
def insch(self, ch: _ChType, attr: int = ...) -> None: 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. Insert a character before the current or specified position.
y y
@ -1365,8 +1241,7 @@ class window: # undocumented
def insertln(self) -> None: ... def insertln(self) -> None: ...
@overload @overload
def insnstr(self, str: str, n: int, attr: int = ...) -> None: 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. Insert at most n characters of the string.
y y
@ -1392,8 +1267,7 @@ class window: # undocumented
def insnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... def insnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ...
@overload @overload
def insstr(self, str: str, attr: int = ...) -> None: 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. Insert the string before the current or specified position.
y y
@ -1416,8 +1290,7 @@ class window: # undocumented
def insstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... def insstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ...
@overload @overload
def instr(self, n: int = ...) -> bytes: 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. Return a string of characters, extracted from the window.
y y
@ -1436,8 +1309,7 @@ class window: # undocumented
@overload @overload
def instr(self, y: int, x: int, n: int = ...) -> bytes: ... def instr(self, y: int, x: int, n: int = ...) -> bytes: ...
def is_linetouched(self, line: int, /) -> bool: 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
Line number. Line number.
@ -1455,8 +1327,7 @@ class window: # undocumented
def notimeout(self, yes: bool) -> None: ... def notimeout(self, yes: bool) -> None: ...
@overload @overload
def noutrefresh(self) -> None: def noutrefresh(self) -> None:
""" """noutrefresh([pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol])
noutrefresh([pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol])
Mark for refresh but wait. Mark for refresh but wait.
This function updates the data structure representing the desired state of the 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: ... def noutrefresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ...
@overload @overload
def overlay(self, destwin: window) -> None: 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. Overlay the window on top of destwin.
The windows need not be the same size, only the overlapping region is copied. The windows need not be the same size, only the overlapping region is copied.
@ -1488,8 +1358,7 @@ class window: # undocumented
) -> None: ... ) -> None: ...
@overload @overload
def overwrite(self, destwin: window) -> None: def overwrite(self, destwin: window) -> None:
""" """overwrite(destwin, [sminrow, smincol, dminrow, dmincol, dmaxrow,
overwrite(destwin, [sminrow, smincol, dminrow, dmincol, dmaxrow,
dmaxcol]) dmaxcol])
Overwrite the window on top of destwin. 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 self, destwin: window, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int
) -> None: ... ) -> None: ...
def putwin(self, file: SupportsWrite[bytes], /) -> 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. This information can be later retrieved using the getwin() function.
""" """
def redrawln(self, beg: int, num: int, /) -> None: def redrawln(self, beg: int, num: int, /) -> None:
""" """Mark the specified lines corrupted.
Mark the specified lines corrupted.
beg beg
Starting line number. Starting line number.
@ -1529,8 +1396,7 @@ class window: # undocumented
def redrawwin(self) -> None: ... def redrawwin(self) -> None: ...
@overload @overload
def refresh(self) -> None: def refresh(self) -> None:
""" """refresh([pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol])
refresh([pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol])
Update the display immediately. Update the display immediately.
Synchronize actual screen with previous drawing/deleting methods. 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 refresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ...
def resize(self, nlines: int, ncols: int) -> None: ... def resize(self, nlines: int, ncols: int) -> None: ...
def scroll(self, lines: int = ...) -> None: def scroll(self, lines: int = ...) -> None:
""" """scroll([lines=1])
scroll([lines=1])
Scroll the screen or scrolling region. Scroll the screen or scrolling region.
lines lines
@ -1562,8 +1427,7 @@ class window: # undocumented
def scrollok(self, flag: bool) -> None: ... def scrollok(self, flag: bool) -> None: ...
def setscrreg(self, top: int, bottom: int, /) -> None: def setscrreg(self, top: int, bottom: int, /) -> None:
""" """Define a software scrolling region.
Define a software scrolling region.
top top
First line number. First line number.
@ -1577,8 +1441,7 @@ class window: # undocumented
def standout(self) -> None: ... def standout(self) -> None: ...
@overload @overload
def subpad(self, begin_y: int, begin_x: int) -> window: 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). Create a sub-window (screen-relative coordinates).
nlines nlines
@ -1598,8 +1461,7 @@ class window: # undocumented
def subpad(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ... def subpad(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ...
@overload @overload
def subwin(self, begin_y: int, begin_x: int) -> window: 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). Create a sub-window (screen-relative coordinates).
nlines nlines
@ -1622,8 +1484,7 @@ class window: # undocumented
def syncup(self) -> None: ... def syncup(self) -> None: ...
def timeout(self, delay: int) -> None: ... def timeout(self, delay: int) -> None: ...
def touchline(self, start: int, count: int, changed: bool = ...) -> 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. Pretend count lines have been changed, starting with line start.
If changed is supplied, it specifies whether the affected lines are marked If changed is supplied, it specifies whether the affected lines are marked
@ -1634,8 +1495,7 @@ class window: # undocumented
def untouchwin(self) -> None: ... def untouchwin(self) -> None: ...
@overload @overload
def vline(self, ch: _ChType, n: int) -> None: 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. Display a vertical line.
y y

View file

@ -9,85 +9,55 @@ class error(Exception): ...
@final @final
class panel: class panel:
def above(self) -> panel: def above(self) -> panel:
""" """Return the panel above the current panel."""
Return the panel above the current panel.
"""
def below(self) -> panel: def below(self) -> panel:
""" """Return the panel below the current panel."""
Return the panel below the current panel.
"""
def bottom(self) -> None: 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: 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: def hide(self) -> None:
""" """Hide the panel.
Hide the panel.
This does not delete the object, it just makes the window on screen invisible. This does not delete the object, it just makes the window on screen invisible.
""" """
def move(self, y: int, x: int, /) -> None: 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: 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: 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: def show(self) -> None:
""" """Display the panel (which might have been hidden)."""
Display the panel (which might have been hidden).
"""
def top(self) -> None: def top(self) -> None:
""" """Push panel to the top of the stack."""
Push panel to the top of the stack.
"""
def userptr(self) -> object: def userptr(self) -> object:
""" """Return the user pointer for the panel."""
Return the user pointer for the panel.
"""
def window(self) -> window: def window(self) -> window:
""" """Return the window object associated with the panel."""
Return the window object associated with the panel.
"""
def bottom_panel() -> 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: 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: def top_panel() -> panel:
""" """Return the top panel in the panel stack."""
Return the top panel in the panel stack.
"""
def update_panels() -> panel: 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. This does not call curses.doupdate(), so you'll have to do this yourself.
""" """

View file

@ -40,8 +40,7 @@ if sys.platform != "win32":
if sys.version_info >= (3, 11): if sys.version_info >= (3, 11):
def open(filename: StrOrBytesPath, flags: str = "r", mode: int = 0o666, /) -> _dbm: def open(filename: StrOrBytesPath, flags: str = "r", mode: int = 0o666, /) -> _dbm:
""" """Return a database object.
Return a database object.
filename filename
The filename to open. The filename to open.
@ -53,8 +52,7 @@ if sys.platform != "win32":
""" """
else: else:
def open(filename: str, flags: str = "r", mode: int = 0o666, /) -> _dbm: def open(filename: str, flags: str = "r", mode: int = 0o666, /) -> _dbm:
""" """Return a database object.
Return a database object.
filename filename
The filename to open. The filename to open.

View file

@ -49,14 +49,10 @@ if sys.version_info >= (3, 14):
IEEE_CONTEXT_MAX_BITS: Final[int] IEEE_CONTEXT_MAX_BITS: Final[int]
def setcontext(context: Context, /) -> None: def setcontext(context: Context, /) -> None:
""" """Set a new default context."""
Set a new default context.
"""
def getcontext() -> Context: def getcontext() -> Context:
""" """Get the current default context."""
Get the current default context.
"""
if sys.version_info >= (3, 11): if sys.version_info >= (3, 11):
def localcontext( def localcontext(
@ -71,8 +67,7 @@ if sys.version_info >= (3, 11):
traps: dict[_TrapType, bool] | None = ..., traps: dict[_TrapType, bool] | None = ...,
flags: dict[_TrapType, bool] | None = ..., flags: dict[_TrapType, bool] | None = ...,
) -> _ContextManager: ) -> _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 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 exiting the with-statement. If no context is specified, a copy of the current
default context is used. default context is used.
@ -80,8 +75,7 @@ if sys.version_info >= (3, 11):
else: else:
def localcontext(ctx: Context | None = None) -> _ContextManager: 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 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 exiting the with-statement. If no context is specified, a copy of the current
default context is used. default context is used.
@ -89,8 +83,7 @@ else:
if sys.version_info >= (3, 14): if sys.version_info >= (3, 14):
def IEEEContext(bits: int, /) -> Context: 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 IEEE interchange formats. The argument must be a multiple of 32 and less
than IEEE_CONTEXT_MAX_BITS. than IEEE_CONTEXT_MAX_BITS.
""" """

View file

@ -24,8 +24,7 @@ def __import__(
fromlist: Sequence[str] = (), fromlist: Sequence[str] = (),
level: int = 0, level: int = 0,
) -> ModuleType: ) -> ModuleType:
""" """Import a module.
Import a module.
The 'globals' argument is used to infer where the import is occurring from The 'globals' argument is used to infer where the import is occurring from
to handle relative imports. The 'locals' argument is ignored. The to handle relative imports. The 'locals' argument is ignored. The
@ -38,22 +37,17 @@ def __import__(
def spec_from_loader( def spec_from_loader(
name: str, loader: LoaderProtocol | None, *, origin: str | None = None, is_package: bool | None = None name: str, loader: LoaderProtocol | None, *, origin: str | None = None, is_package: bool | None = None
) -> importlib.machinery.ModuleSpec | 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: 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( def _init_module_attrs(
spec: importlib.machinery.ModuleSpec, module: types.ModuleType, *, override: bool = False spec: importlib.machinery.ModuleSpec, module: types.ModuleType, *, override: bool = False
) -> types.ModuleType: ... ) -> types.ModuleType: ...
class ModuleSpec: 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 A module's spec is the source for information about the module. For
data associated with the module, including source, use the spec's data associated with the module, including source, use the spec's
@ -105,16 +99,13 @@ class ModuleSpec:
cached: str | None cached: str | None
@property @property
def parent(self) -> str | None: def parent(self) -> str | None:
""" """The name of the module's parent."""
The name of the module's parent.
"""
has_location: bool has_location: bool
def __eq__(self, other: object) -> bool: ... def __eq__(self, other: object) -> bool: ...
__hash__: ClassVar[None] # type: ignore[assignment] __hash__: ClassVar[None] # type: ignore[assignment]
class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): 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 All methods are either class or static methods to avoid the need to
instantiate the class. instantiate the class.
@ -132,29 +123,22 @@ class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader)
# InspectLoader # InspectLoader
@classmethod @classmethod
def is_package(cls, fullname: str) -> bool: 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 @classmethod
def load_module(cls, fullname: str) -> types.ModuleType: 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. This method is deprecated. Use loader.exec_module() instead.
""" """
@classmethod @classmethod
def get_code(cls, fullname: str) -> None: 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 @classmethod
def get_source(cls, fullname: str) -> None: 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 # Loader
if sys.version_info < (3, 12): if sys.version_info < (3, 12):
@staticmethod @staticmethod
@ -162,31 +146,22 @@ class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader)
if sys.version_info >= (3, 10): if sys.version_info >= (3, 10):
@staticmethod @staticmethod
def create_module(spec: ModuleSpec) -> types.ModuleType | None: def create_module(spec: ModuleSpec) -> types.ModuleType | None:
""" """Create a built-in module"""
Create a built-in module
"""
@staticmethod @staticmethod
def exec_module(module: types.ModuleType) -> None: def exec_module(module: types.ModuleType) -> None:
""" """Exec a built-in module"""
Exec a built-in module
"""
else: else:
@classmethod @classmethod
def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None: def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None:
""" """Create a built-in module"""
Create a built-in module
"""
@classmethod @classmethod
def exec_module(cls, module: types.ModuleType) -> None: 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): 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 All methods are either class or static methods to avoid the need to
instantiate the class. instantiate the class.
@ -204,29 +179,22 @@ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader):
# InspectLoader # InspectLoader
@classmethod @classmethod
def is_package(cls, fullname: str) -> bool: 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 @classmethod
def load_module(cls, fullname: str) -> types.ModuleType: def load_module(cls, fullname: str) -> types.ModuleType:
""" """Load a frozen module.
Load a frozen module.
This method is deprecated. Use exec_module() instead. This method is deprecated. Use exec_module() instead.
""" """
@classmethod @classmethod
def get_code(cls, fullname: str) -> None: def get_code(cls, fullname: str) -> None:
""" """Return the code object for the frozen module."""
Return the code object for the frozen module.
"""
@classmethod @classmethod
def get_source(cls, fullname: str) -> None: 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 # Loader
if sys.version_info < (3, 12): if sys.version_info < (3, 12):
@staticmethod @staticmethod
@ -234,15 +202,11 @@ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader):
if sys.version_info >= (3, 10): if sys.version_info >= (3, 10):
@staticmethod @staticmethod
def create_module(spec: ModuleSpec) -> types.ModuleType | None: def create_module(spec: ModuleSpec) -> types.ModuleType | None:
""" """Set __file__, if able."""
Set __file__, if able.
"""
else: else:
@classmethod @classmethod
def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None: def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None:
""" """Set __file__, if able."""
Set __file__, if able.
"""
@staticmethod @staticmethod
def exec_module(module: types.ModuleType) -> None: ... def exec_module(module: types.ModuleType) -> None: ...

View file

@ -36,8 +36,7 @@ else:
MAGIC_NUMBER: bytes MAGIC_NUMBER: bytes
def cache_from_source(path: StrPath, debug_override: bool | None = None, *, optimization: Any | None = None) -> str: 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 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. .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: 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 .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 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: 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. Universal newline support is used in the decoding.
""" """
@ -78,8 +75,7 @@ def spec_from_file_location(
loader: LoaderProtocol | None = None, loader: LoaderProtocol | None = None,
submodule_search_locations: list[str] | None = ..., submodule_search_locations: list[str] | None = ...,
) -> importlib.machinery.ModuleSpec | 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 To indicate that the module is a package, set
submodule_search_locations to a list of directory paths. An 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." "Future versions of Python may not enable this finder by default."
) )
class WindowsRegistryFinder(importlib.abc.MetaPathFinder): 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): if sys.version_info < (3, 12):
@classmethod @classmethod
@ -108,29 +102,24 @@ class WindowsRegistryFinder(importlib.abc.MetaPathFinder):
) -> ModuleSpec | None: ... ) -> ModuleSpec | None: ...
class PathFinder(importlib.abc.MetaPathFinder): 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): if sys.version_info >= (3, 10):
@staticmethod @staticmethod
def invalidate_caches() -> None: 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). stored in sys.path_importer_cache (where implemented).
""" """
else: else:
@classmethod @classmethod
def invalidate_caches(cls) -> None: 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). stored in sys.path_importer_cache (where implemented).
""" """
if sys.version_info >= (3, 10): if sys.version_info >= (3, 10):
@staticmethod @staticmethod
def find_distributions(context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: def find_distributions(context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]:
""" """Find distributions.
Find distributions.
Return an iterable of all Distribution instances capable of Return an iterable of all Distribution instances capable of
loading the metadata for packages matching ``context.name`` loading the metadata for packages matching ``context.name``
@ -140,8 +129,7 @@ class PathFinder(importlib.abc.MetaPathFinder):
else: else:
@classmethod @classmethod
def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]:
""" """Find distributions.
Find distributions.
Return an iterable of all Distribution instances capable of Return an iterable of all Distribution instances capable of
loading the metadata for packages matching ``context.name`` loading the metadata for packages matching ``context.name``
@ -153,8 +141,7 @@ class PathFinder(importlib.abc.MetaPathFinder):
def find_spec( def find_spec(
cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None
) -> ModuleSpec | 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. 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] EXTENSION_SUFFIXES: list[str]
class FileFinder(importlib.abc.PathEntryFinder): class FileFinder(importlib.abc.PathEntryFinder):
""" """File-based finder.
File-based finder.
Interactions with the file system are cached for performance, being Interactions with the file system are cached for performance, being
refreshed when the directory the finder is handling has been modified. refreshed when the directory the finder is handling has been modified.
@ -178,8 +164,7 @@ class FileFinder(importlib.abc.PathEntryFinder):
path: str path: str
def __init__(self, path: str, *loader_details: tuple[type[importlib.abc.Loader], list[str]]) -> None: 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 2-tuples containing the loader and the file suffixes the loader
recognizes. recognizes.
""" """
@ -188,8 +173,7 @@ class FileFinder(importlib.abc.PathEntryFinder):
def path_hook( def path_hook(
cls, *loader_details: tuple[type[importlib.abc.Loader], list[str]] cls, *loader_details: tuple[type[importlib.abc.Loader], list[str]]
) -> Callable[[str], importlib.abc.PathEntryFinder]: ) -> 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 which will return an instance using the specified loaders and the path
called on the closure. called on the closure.
@ -198,56 +182,43 @@ class FileFinder(importlib.abc.PathEntryFinder):
""" """
class _LoaderBasics: class _LoaderBasics:
""" """Base class of common code needed by both SourceLoader and
Base class of common code needed by both SourceLoader and
SourcelessFileLoader. SourcelessFileLoader.
""" """
def is_package(self, fullname: str) -> bool: 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'. the path returned by get_filename has a filename of '__init__.py'.
""" """
def create_module(self, spec: ModuleSpec) -> types.ModuleType | None: 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: def exec_module(self, module: types.ModuleType) -> None:
""" """Execute the module."""
Execute the module.
"""
def load_module(self, fullname: str) -> types.ModuleType: def load_module(self, fullname: str) -> types.ModuleType:
""" """This method is deprecated."""
This method is deprecated.
"""
class SourceLoader(_LoaderBasics): class SourceLoader(_LoaderBasics):
def path_mtime(self, path: str) -> float: 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). specified path (a str).
Raises OSError when the path cannot be handled. Raises OSError when the path cannot be handled.
""" """
def set_data(self, path: str, data: bytes) -> None: 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. Implementing this method allows for the writing of bytecode files.
""" """
def get_source(self, fullname: str) -> str | None: 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]: 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). path (a str).
Possible keys: Possible keys:
@ -262,47 +233,38 @@ class SourceLoader(_LoaderBasics):
def source_to_code( def source_to_code(
self, data: ReadableBuffer | str | _ast.Module | _ast.Expression | _ast.Interactive, path: ReadableBuffer | StrPath self, data: ReadableBuffer | str | _ast.Module | _ast.Expression | _ast.Interactive, path: ReadableBuffer | StrPath
) -> types.CodeType: ) -> 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. The 'data' argument can be any object type that compile() supports.
""" """
def get_code(self, fullname: str) -> types.CodeType | None: 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 Reading of bytecode requires path_stats to be implemented. To write
bytecode, set_data must also be implemented. bytecode, set_data must also be implemented.
""" """
class FileLoader: 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. require file system usage.
""" """
name: str name: str
path: str path: str
def __init__(self, fullname: str, path: str) -> None: 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. finder.
""" """
def get_data(self, path: str) -> bytes: 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: 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: 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. This method is deprecated. Use exec_module() instead.
""" """
@ -316,19 +278,13 @@ class FileLoader:
def contents(self) -> Iterator[str]: ... def contents(self) -> Iterator[str]: ...
class SourceFileLoader(importlib.abc.FileLoader, FileLoader, importlib.abc.SourceLoader, SourceLoader): # type: ignore[misc] # incompatible method arguments in base classes 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: 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]: 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 def source_to_code( # type: ignore[override] # incompatible with InspectLoader.source_to_code
self, self,
@ -337,55 +293,39 @@ class SourceFileLoader(importlib.abc.FileLoader, FileLoader, importlib.abc.Sourc
*, *,
_optimize: int = -1, _optimize: int = -1,
) -> types.CodeType: ) -> 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. The 'data' argument can be any object type that compile() supports.
""" """
class SourcelessFileLoader(importlib.abc.FileLoader, FileLoader, _LoaderBasics): 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_code(self, fullname: str) -> types.CodeType | None: ...
def get_source(self, fullname: str) -> 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): class ExtensionFileLoader(FileLoader, _LoaderBasics, importlib.abc.ExecutionLoader):
""" """Loader for extension modules.
Loader for extension modules.
The constructor is designed to work with FileFinder. The constructor is designed to work with FileFinder.
""" """
def __init__(self, name: str, path: str) -> None: ... def __init__(self, name: str, path: str) -> None: ...
def get_filename(self, name: str | None = None) -> str: 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: 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: 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: def exec_module(self, module: types.ModuleType) -> None:
""" """Initialize an extension module"""
Initialize an extension module
"""
def get_code(self, fullname: str) -> None: 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 __eq__(self, other: object) -> bool: ...
def __hash__(self) -> int: ... def __hash__(self) -> int: ...
@ -399,15 +339,12 @@ if sys.version_info >= (3, 11):
def get_source(self, fullname: str) -> Literal[""]: ... def get_source(self, fullname: str) -> Literal[""]: ...
def get_code(self, fullname: str) -> types.CodeType: ... def get_code(self, fullname: str) -> types.CodeType: ...
def create_module(self, spec: ModuleSpec) -> None: 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: ... def exec_module(self, module: types.ModuleType) -> None: ...
@deprecated("load_module() is deprecated; use exec_module() instead") @deprecated("load_module() is deprecated; use exec_module() instead")
def load_module(self, fullname: str) -> types.ModuleType: def load_module(self, fullname: str) -> types.ModuleType:
""" """Load a namespace module.
Load a namespace module.
This method is deprecated. Use exec_module() instead. This method is deprecated. Use exec_module() instead.
""" """
@ -417,8 +354,7 @@ if sys.version_info >= (3, 11):
@staticmethod @staticmethod
@deprecated("module_repr() is deprecated, and has been removed in Python 3.12") @deprecated("module_repr() is deprecated, and has been removed in Python 3.12")
def module_repr(module: types.ModuleType) -> str: 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. 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_source(self, fullname: str) -> Literal[""]: ...
def get_code(self, fullname: str) -> types.CodeType: ... def get_code(self, fullname: str) -> types.CodeType: ...
def create_module(self, spec: ModuleSpec) -> None: 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: ... def exec_module(self, module: types.ModuleType) -> None: ...
@deprecated("load_module() is deprecated; use exec_module() instead") @deprecated("load_module() is deprecated; use exec_module() instead")
def load_module(self, fullname: str) -> types.ModuleType: def load_module(self, fullname: str) -> types.ModuleType:
""" """Load a namespace module.
Load a namespace module.
This method is deprecated. Use exec_module() instead. This method is deprecated. Use exec_module() instead.
""" """
@ -449,8 +382,7 @@ else:
@staticmethod @staticmethod
@deprecated("module_repr() is deprecated, and has been removed in Python 3.12") @deprecated("module_repr() is deprecated, and has been removed in Python 3.12")
def module_repr(module: types.ModuleType) -> str: 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. The method is deprecated. The import machinery does the job itself.
""" """
@ -460,15 +392,13 @@ else:
@classmethod @classmethod
@deprecated("module_repr() is deprecated, and has been removed in Python 3.12") @deprecated("module_repr() is deprecated, and has been removed in Python 3.12")
def module_repr(cls, module: types.ModuleType) -> str: 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. The method is deprecated. The import machinery does the job itself.
""" """
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
class AppleFrameworkLoader(ExtensionFileLoader, importlib.abc.ExecutionLoader): 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. compatibility with Apple's iOS App Store policies.
""" """

View file

@ -56,8 +56,7 @@ if sys.platform != "win32":
if sys.version_info >= (3, 11): if sys.version_info >= (3, 11):
def open(filename: StrOrBytesPath, flags: str = "r", mode: int = 0o666, /) -> _gdbm: 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. The filename argument is the name of the database file.

View file

@ -27,8 +27,7 @@ class _HashObject(Protocol):
def update(self, obj: ReadableBuffer, /) -> None: ... def update(self, obj: ReadableBuffer, /) -> None: ...
class HASH: 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: Methods:
@ -50,31 +49,22 @@ class HASH:
@property @property
def name(self) -> str: ... def name(self) -> str: ...
def copy(self) -> Self: def copy(self) -> Self:
""" """Return a copy of the hash object."""
Return a copy of the hash object.
"""
def digest(self) -> bytes: def digest(self) -> bytes:
""" """Return the digest value as a bytes object."""
Return the digest value as a bytes object.
"""
def hexdigest(self) -> str: 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: 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): if sys.version_info >= (3, 10):
class UnsupportedDigestmodError(ValueError): ... class UnsupportedDigestmodError(ValueError): ...
class HASHXOF(HASH): 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: Methods:
@ -90,19 +80,14 @@ class HASHXOF(HASH):
""" """
def digest(self, length: int) -> bytes: # type: ignore[override] 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] 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 @final
class HMAC: class HMAC:
""" """The object used to calculate HMAC of a message.
The object used to calculate HMAC of a message.
Methods: Methods:
@ -124,32 +109,24 @@ class HMAC:
@property @property
def name(self) -> str: ... def name(self) -> str: ...
def copy(self) -> Self: def copy(self) -> Self:
""" """Return a copy ("clone") of the HMAC object."""
Return a copy ("clone") of the HMAC object.
"""
def digest(self) -> bytes: 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: 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 This may be used to exchange the value safely in email or other non-binary
environments. environments.
""" """
def update(self, msg: ReadableBuffer) -> None: def update(self, msg: ReadableBuffer) -> None:
""" """Update the HMAC object with msg."""
Update the HMAC object with msg.
"""
@overload @overload
def compare_digest(a: ReadableBuffer, b: ReadableBuffer, /) -> bool: def compare_digest(a: ReadableBuffer, b: ReadableBuffer, /) -> bool:
""" """Return 'a == b'.
Return 'a == b'.
This function uses an approach designed to prevent This function uses an approach designed to prevent
timing analysis, making it appropriate for cryptography. timing analysis, making it appropriate for cryptography.
@ -165,8 +142,7 @@ def compare_digest(a: ReadableBuffer, b: ReadableBuffer, /) -> bool:
@overload @overload
def compare_digest(a: AnyStr, b: AnyStr, /) -> bool: ... def compare_digest(a: AnyStr, b: AnyStr, /) -> bool: ...
def get_fips_mode() -> int: 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 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 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: 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): if sys.version_info >= (3, 13):
def new(name: str, data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None) -> HASH: 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 An optional string argument may be provided and will be
automatically hashed. 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: 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: 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: 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: 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: 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: 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( def openssl_sha3_224(
data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None
) -> HASH: ) -> 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( def openssl_sha3_256(
data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None
) -> HASH: ) -> 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( def openssl_sha3_384(
data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None
) -> HASH: ) -> 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( def openssl_sha3_512(
data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None
) -> HASH: ) -> 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( def openssl_shake_128(
data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None
) -> HASHXOF: ) -> 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( def openssl_shake_256(
data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None
) -> HASHXOF: ) -> 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: else:
def new(name: str, string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: 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 An optional string argument may be provided and will be
automatically hashed. automatically hashed.
@ -276,78 +224,48 @@ else:
""" """
def openssl_md5(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: def hmac_digest(key: bytes | bytearray, msg: ReadableBuffer, digest: str) -> bytes:
""" """Single-shot HMAC."""
Single-shot HMAC.
"""
def pbkdf2_hmac( def pbkdf2_hmac(
hash_name: str, password: ReadableBuffer, salt: ReadableBuffer, iterations: int, dklen: int | None = None hash_name: str, password: ReadableBuffer, salt: ReadableBuffer, iterations: int, dklen: int | None = None
) -> bytes: ) -> 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: 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.
"""

View file

@ -37,31 +37,23 @@ _T = TypeVar("_T") # list items must be comparable
__about__: Final[str] __about__: Final[str]
def heapify(heap: list[Any], /) -> None: # list items must be comparable 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: 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: 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: 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 The combined action runs more efficiently than heappush() followed by
a separate call to heappop(). a separate call to heappop().
""" """
def heapreplace(heap: list[_T], item: _T, /) -> _T: 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 This is more efficient than heappop() followed by heappush(), and can be
more appropriate when using a fixed-size heap. Note that the value 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): if sys.version_info >= (3, 14):
def heapify_max(heap: list[Any], /) -> None: # list items must be comparable 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: def heappop_max(heap: list[_T], /) -> _T:
""" """Maxheap variant of heappop."""
Maxheap variant of heappop.
"""
def heappush_max(heap: list[_T], item: _T, /) -> None: 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: 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 The combined action runs more efficiently than heappush_max() followed by
a separate call to heappop_max(). a separate call to heappop_max().
""" """
def heapreplace_max(heap: list[_T], item: _T, /) -> _T: def heapreplace_max(heap: list[_T], item: _T, /) -> _T:
""" """Maxheap variant of heapreplace."""
Maxheap variant of heapreplace.
"""

View file

@ -14,76 +14,54 @@ if sys.version_info >= (3, 14):
def source_hash(key: int, source: ReadableBuffer) -> bytes: ... def source_hash(key: int, source: ReadableBuffer) -> bytes: ...
def create_builtin(spec: ModuleSpec, /) -> types.ModuleType: 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: def create_dynamic(spec: ModuleSpec, file: Any = None, /) -> types.ModuleType:
""" """Create an extension module."""
Create an extension module.
"""
def acquire_lock() -> None: 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 This lock should be used by import hooks to ensure thread-safety when importing
modules. On platforms without threads, this function does nothing. modules. On platforms without threads, this function does nothing.
""" """
def exec_builtin(mod: types.ModuleType, /) -> int: def exec_builtin(mod: types.ModuleType, /) -> int:
""" """Initialize a built-in module."""
Initialize a built-in module.
"""
def exec_dynamic(mod: types.ModuleType, /) -> int: def exec_dynamic(mod: types.ModuleType, /) -> int:
""" """Initialize an extension module."""
Initialize an extension module.
"""
def extension_suffixes() -> list[str]: 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: def init_frozen(name: str, /) -> types.ModuleType:
""" """Initializes a frozen module."""
Initializes a frozen module.
"""
def is_builtin(name: str, /) -> int: 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: 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: 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: 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. On platforms without threads, return False.
""" """
def release_lock() -> None: def release_lock() -> None:
""" """Release the interpreter's import lock.
Release the interpreter's import lock.
On platforms without threads, this function does nothing. On platforms without threads, this function does nothing.
""" """
if sys.version_info >= (3, 11): if sys.version_info >= (3, 11):
def find_frozen(name: str, /, *, withdata: bool = False) -> tuple[memoryview | None, bool, str | None] | None: 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): 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: 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: else:
def get_frozen_object(name: str, /) -> types.CodeType: def get_frozen_object(name: str, /) -> types.CodeType:
""" """Create a code object for a frozen module."""
Create a code object for a frozen module.
"""

View file

@ -16,41 +16,29 @@ class ChannelNotFoundError(ChannelError): ...
# Mark as final, since instantiating ChannelID is not supported. # Mark as final, since instantiating ChannelID is not supported.
@final @final
class ChannelID: 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 @property
def end(self) -> Literal["send", "recv", "both"]: def end(self) -> Literal["send", "recv", "both"]:
""" """'send', 'recv', or 'both'"""
'send', 'recv', or 'both'
"""
@property @property
def send(self) -> Self: def send(self) -> Self:
""" """the 'send' end of the channel"""
the 'send' end of the channel
"""
@property @property
def recv(self) -> Self: def recv(self) -> Self:
""" """the 'recv' end of the channel"""
the 'recv' end of the channel
"""
def __eq__(self, other: object) -> bool: ... def __eq__(self, other: object) -> bool: ...
def __ge__(self, other: ChannelID) -> bool: ... def __ge__(self, other: ChannelID) -> bool: ...
def __gt__(self, other: ChannelID) -> bool: ... def __gt__(self, other: ChannelID) -> bool: ...
def __hash__(self) -> int: ... def __hash__(self) -> int: ...
def __index__(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: def __int__(self) -> int:
""" """int(self)"""
int(self)
"""
def __le__(self, other: ChannelID) -> bool: ... def __le__(self, other: ChannelID) -> bool: ...
def __lt__(self, other: ChannelID) -> bool: ... def __lt__(self, other: ChannelID) -> bool: ...
@ -58,8 +46,7 @@ class ChannelID:
@final @final
class ChannelInfo(structseq[int], tuple[bool, bool, bool, int, int, int, int, int]): class ChannelInfo(structseq[int], tuple[bool, bool, bool, int, int, int, int, int]):
""" """ChannelInfo
ChannelInfo
A named tuple of a channel's state. 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 @property
def open(self) -> bool: def open(self) -> bool:
""" """both ends are open"""
both ends are open
"""
@property @property
def closing(self) -> bool: def closing(self) -> bool:
""" """send is closed, recv is non-empty"""
send is closed, recv is non-empty
"""
@property @property
def closed(self) -> bool: def closed(self) -> bool:
""" """both ends are closed"""
both ends are closed
"""
@property @property
def count(self) -> int: # type: ignore[override] def count(self) -> int: # type: ignore[override]
""" """queued objects"""
queued objects
"""
@property @property
def num_interp_send(self) -> int: def num_interp_send(self) -> int:
""" """interpreters bound to the send end"""
interpreters bound to the send end
"""
@property @property
def num_interp_send_released(self) -> int: def num_interp_send_released(self) -> int:
""" """interpreters bound to the send end and released"""
interpreters bound to the send end and released
"""
@property @property
def num_interp_recv(self) -> int: def num_interp_recv(self) -> int:
""" """interpreters bound to the send end"""
interpreters bound to the send end
"""
@property @property
def num_interp_recv_released(self) -> int: def num_interp_recv_released(self) -> int:
""" """interpreters bound to the send end and released"""
interpreters bound to the send end and released
"""
@property @property
def num_interp_both(self) -> int: def num_interp_both(self) -> int:
""" """interpreters bound to both ends"""
interpreters bound to both ends
"""
@property @property
def num_interp_both_recv_released(self) -> int: 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 @property
def num_interp_both_send_released(self) -> int: 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 @property
def num_interp_both_released(self) -> int: 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 @property
def recv_associated(self) -> bool: def recv_associated(self) -> bool:
""" """current interpreter is bound to the recv end"""
current interpreter is bound to the recv end
"""
@property @property
def recv_released(self) -> bool: def recv_released(self) -> bool:
""" """current interpreter *was* bound to the recv end"""
current interpreter *was* bound to the recv end
"""
@property @property
def send_associated(self) -> bool: def send_associated(self) -> bool:
""" """current interpreter is bound to the send end"""
current interpreter is bound to the send end
"""
@property @property
def send_released(self) -> bool: 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: 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. Create a new cross-interpreter channel and return a unique generated ID.
""" """
def destroy(cid: SupportsIndex) -> None: def destroy(cid: SupportsIndex) -> None:
""" """channel_destroy(cid)
channel_destroy(cid)
Close and finalize the channel. Afterward attempts to use the channel Close and finalize the channel. Afterward attempts to use the channel
will behave as though it never existed. will behave as though it never existed.
""" """
def list_all() -> list[ChannelID]: def list_all() -> list[ChannelID]:
""" """channel_list_all() -> [cid]
channel_list_all() -> [cid]
Return the list of all IDs for active channels. Return the list of all IDs for active channels.
""" """
def list_interpreters(cid: SupportsIndex, *, send: bool) -> list[int]: 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. 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: 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. Add the object's data to the channel's queue.
By default this waits for the object to be received. 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: 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. Add the object's buffer to the channel's queue.
By default this waits for the object to be received. By default this waits for the object to be received.
""" """
def recv(cid: SupportsIndex, default: object = ...) -> tuple[Any, Literal[1, 2, 3]]: 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. 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: 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. 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: def get_count(cid: SupportsIndex) -> int:
""" """get_count(cid)
get_count(cid)
Return the number of items in the channel. Return the number of items in the channel.
""" """
def get_info(cid: SupportsIndex) -> ChannelInfo: def get_info(cid: SupportsIndex) -> ChannelInfo:
""" """get_info(cid)
get_info(cid)
Return details about the channel. Return details about the channel.
""" """
def get_channel_defaults(cid: SupportsIndex) -> Literal[1, 2, 3]: 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. 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: 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' Close the channel for the current interpreter. 'send' and 'recv'
(bool) may be used to indicate the ends to close. By default both (bool) may be used to indicate the ends to close. By default both

View file

@ -9,23 +9,19 @@ from typing_extensions import TypeAlias
_UnboundOp: TypeAlias = Literal[1, 2, 3] _UnboundOp: TypeAlias = Literal[1, 2, 3]
class QueueError(RuntimeError): class QueueError(RuntimeError):
""" """Indicates that a queue-related error happened."""
Indicates that a queue-related error happened.
"""
class QueueNotFoundError(QueueError): ... class QueueNotFoundError(QueueError): ...
def bind(qid: SupportsIndex) -> None: def bind(qid: SupportsIndex) -> None:
""" """bind(qid)
bind(qid)
Take a reference to the identified queue. Take a reference to the identified queue.
The queue is not destroyed until there are no references left. The queue is not destroyed until there are no references left.
""" """
def create(maxsize: SupportsIndex, fmt: SupportsIndex, unboundop: _UnboundOp) -> int: 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. 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. 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: def destroy(qid: SupportsIndex) -> None:
""" """destroy(qid)
destroy(qid)
Clear and destroy the queue. Afterward attempts to use the queue Clear and destroy the queue. Afterward attempts to use the queue
will behave as though it never existed. will behave as though it never existed.
""" """
def get(qid: SupportsIndex) -> tuple[Any, int, _UnboundOp | None]: 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. Return a new object from the data at the front of the queue.
The unbound op is also returned. 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: def get_count(qid: SupportsIndex) -> int:
""" """get_count(qid)
get_count(qid)
Return the number of items in the queue. Return the number of items in the queue.
""" """
def get_maxsize(qid: SupportsIndex) -> int: def get_maxsize(qid: SupportsIndex) -> int:
""" """get_maxsize(qid)
get_maxsize(qid)
Return the maximum number of items in the queue. Return the maximum number of items in the queue.
""" """
def get_queue_defaults(qid: SupportsIndex) -> tuple[int, _UnboundOp]: 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. Return the queue's default values, set when it was created.
""" """
def is_full(qid: SupportsIndex) -> bool: def is_full(qid: SupportsIndex) -> bool:
""" """is_full(qid)
is_full(qid)
Return true if the queue has a maxsize and has reached it. Return true if the queue has a maxsize and has reached it.
""" """
def list_all() -> list[tuple[int, int, _UnboundOp]]: 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. Return the list of IDs for all queues.
Each corresponding default unbound op and fallback is also included. Each corresponding default unbound op and fallback is also included.
""" """
def put(qid: SupportsIndex, obj: Any, fmt: SupportsIndex, unboundop: _UnboundOp) -> None: 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. Add the object's data to the queue.
""" """
def release(qid: SupportsIndex) -> None: def release(qid: SupportsIndex) -> None:
""" """release(qid)
release(qid)
Release a reference to the queue. Release a reference to the queue.
The queue is destroyed once there are no references left. The queue is destroyed once there are no references left.

View file

@ -12,26 +12,19 @@ _Configs: TypeAlias = Literal["default", "isolated", "legacy", "empty", ""]
_SharedDict: TypeAlias = dict[str, Any] # many objects can be shared _SharedDict: TypeAlias = dict[str, Any] # many objects can be shared
class InterpreterError(Exception): class InterpreterError(Exception):
""" """A cross-interpreter operation failed"""
A cross-interpreter operation failed
"""
class InterpreterNotFoundError(InterpreterError): class InterpreterNotFoundError(InterpreterError):
""" """An interpreter was not found"""
An interpreter was not found
"""
class NotShareableError(ValueError): ... class NotShareableError(ValueError): ...
class CrossInterpreterBufferView: class CrossInterpreterBufferView:
def __buffer__(self, flags: int, /) -> memoryview: 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: 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. 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: 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. 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: def destroy(id: SupportsIndex, *, restrict: bool = False) -> None:
""" """destroy(id, *, restrict=False)
destroy(id, *, restrict=False)
Destroy the identified interpreter. 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]]: 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. Return a list containing the ID of every existing interpreter.
""" """
def get_current() -> tuple[int, int]: def get_current() -> tuple[int, int]:
""" """get_current() -> (ID, whence)
get_current() -> (ID, whence)
Return the ID of current interpreter. Return the ID of current interpreter.
""" """
def get_main() -> tuple[int, int]: def get_main() -> tuple[int, int]:
""" """get_main() -> (ID, whence)
get_main() -> (ID, whence)
Return the ID of main interpreter. Return the ID of main interpreter.
""" """
def is_running(id: SupportsIndex, *, restrict: bool = False) -> bool: 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. Return whether or not the identified interpreter is running.
""" """
def get_config(id: SupportsIndex, *, restrict: bool = False) -> types.SimpleNamespace: 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. Return a representation of the config used to initialize the interpreter.
""" """
def whence(id: SupportsIndex) -> int: def whence(id: SupportsIndex) -> int:
""" """whence(id) -> int
whence(id) -> int
Return an identifier for where the interpreter was created. Return an identifier for where the interpreter was created.
""" """
@ -117,8 +102,7 @@ def exec(
*, *,
restrict: bool = False, restrict: bool = False,
) -> None | types.SimpleNamespace: ) -> 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. Execute the provided code in the identified interpreter.
This is equivalent to running the builtin exec() under the target This is equivalent to running the builtin exec() under the target
@ -143,8 +127,7 @@ def call(
*, *,
restrict: bool = False, restrict: bool = False,
) -> object: ) -> 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. Call the provided object in the identified interpreter.
Pass the given args and kwargs, if possible. Pass the given args and kwargs, if possible.
@ -157,8 +140,7 @@ def run_string(
*, *,
restrict: bool = False, restrict: bool = False,
) -> None: ) -> 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. Execute the provided string in the identified interpreter.
@ -168,8 +150,7 @@ def run_string(
def run_func( def run_func(
id: SupportsIndex, func: types.CodeType | Callable[[], object], shared: _SharedDict | None = None, *, restrict: bool = False id: SupportsIndex, func: types.CodeType | Callable[[], object], shared: _SharedDict | None = None, *, restrict: bool = False
) -> None: ) -> 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. Execute the body of the provided function in the identified interpreter.
Code objects are also supported. In both cases, closures and args 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: 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. 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 incref(id: SupportsIndex, *, implieslink: bool = False, restrict: bool = False) -> None: ...
def decref(id: SupportsIndex, *, restrict: bool = False) -> None: ... def decref(id: SupportsIndex, *, restrict: bool = False) -> None: ...
def is_shareable(obj: object) -> bool: 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 Return True if the object's data may be shared between interpreters and
False otherwise. False otherwise.
""" """
def capture_exception(exc: BaseException | None = None) -> types.SimpleNamespace: 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 Return a snapshot of an exception. If "exc" is None
then the current exception, if any, is used (but not cleared). then the current exception, if any, is used (but not cleared).

View file

@ -51,8 +51,7 @@ DEFAULT_BUFFER_SIZE: Final = 8192
open = builtins.open open = builtins.open
def open_code(path: str) -> IO[bytes]: 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 This may perform extra validation beyond open(), but is otherwise interchangeable
with calling open(path, 'rb'). with calling open(path, 'rb').
@ -61,8 +60,7 @@ def open_code(path: str) -> IO[bytes]:
BlockingIOError = builtins.BlockingIOError BlockingIOError = builtins.BlockingIOError
class _IOBase: 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 This class provides dummy implementations for many methods that
derived classes can override selectively; the default implementations derived classes can override selectively; the default implementations
@ -94,57 +92,47 @@ class _IOBase:
""" """
def __iter__(self) -> Iterator[bytes]: def __iter__(self) -> Iterator[bytes]:
""" """Implement iter(self)."""
Implement iter(self).
"""
def __next__(self) -> bytes: def __next__(self) -> bytes:
""" """Implement next(self)."""
Implement next(self).
"""
def __enter__(self) -> Self: ... def __enter__(self) -> Self: ...
def __exit__( def __exit__(
self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None
) -> None: ... ) -> None: ...
def close(self) -> 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. This method has no effect if the file is already closed.
""" """
def fileno(self) -> int: 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. Raise OSError if the IO object does not use a file descriptor.
""" """
def flush(self) -> None: 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. This is not implemented for read-only and non-blocking streams.
""" """
def isatty(self) -> bool: 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. Return False if it can't be determined.
""" """
def readable(self) -> bool: def readable(self) -> bool:
""" """Return whether object was opened for reading.
Return whether object was opened for reading.
If False, read() will raise OSError. If False, read() will raise OSError.
""" """
read: Callable[..., Any] read: Callable[..., Any]
def readlines(self, hint: int = -1, /) -> list[bytes]: 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 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 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: 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 offset
The stream position, relative to 'whence'. The stream position, relative to 'whence'.
@ -171,44 +158,37 @@ class _IOBase:
""" """
def seekable(self) -> bool: 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. If False, seek(), tell() and truncate() will raise OSError.
This method may need to do a test seek(). This method may need to do a test seek().
""" """
def tell(self) -> int: def tell(self) -> int:
""" """Return current stream position."""
Return current stream position.
"""
def truncate(self, size: int | None = None, /) -> int: 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 File pointer is left unchanged. Size defaults to the current IO position
as reported by tell(). Return the new size. as reported by tell(). Return the new size.
""" """
def writable(self) -> bool: def writable(self) -> bool:
""" """Return whether object was opened for writing.
Return whether object was opened for writing.
If False, write() will raise OSError. If False, write() will raise OSError.
""" """
write: Callable[..., Any] write: Callable[..., Any]
def writelines(self, lines: Iterable[ReadableBuffer], /) -> None: 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 Line separators are not added, so it is usual for each of the
lines provided to have a line separator at the end. lines provided to have a line separator at the end.
""" """
def readline(self, size: int | None = -1, /) -> bytes: 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. If size is specified, at most size bytes will be read.
@ -218,23 +198,17 @@ class _IOBase:
""" """
def __del__(self) -> None: def __del__(self) -> None:
""" """Called when the instance is about to be destroyed."""
Called when the instance is about to be destroyed.
"""
@property @property
def closed(self) -> bool: ... def closed(self) -> bool: ...
def _checkClosed(self) -> None: ... # undocumented def _checkClosed(self) -> None: ... # undocumented
class _RawIOBase(_IOBase): class _RawIOBase(_IOBase):
""" """Base class for raw binary I/O."""
Base class for raw binary I/O.
"""
def readall(self) -> bytes: 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 # The following methods can return None if the file is in non-blocking mode
# and no data is available. # and no data is available.
def readinto(self, buffer: WriteableBuffer, /) -> int | MaybeNone: ... def readinto(self, buffer: WriteableBuffer, /) -> int | MaybeNone: ...
@ -242,8 +216,7 @@ class _RawIOBase(_IOBase):
def read(self, size: int = -1, /) -> bytes | MaybeNone: ... def read(self, size: int = -1, /) -> bytes | MaybeNone: ...
class _BufferedIOBase(_IOBase): 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 The main difference with RawIOBase is that the read() method
supports omitting the size argument, and does not have a default supports omitting the size argument, and does not have a default
@ -259,8 +232,7 @@ class _BufferedIOBase(_IOBase):
""" """
def detach(self) -> RawIOBase: 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 After the raw stream has been detached, the buffer is in an unusable
state. state.
@ -268,8 +240,7 @@ class _BufferedIOBase(_IOBase):
def readinto(self, buffer: WriteableBuffer, /) -> int: ... def readinto(self, buffer: WriteableBuffer, /) -> int: ...
def write(self, buffer: ReadableBuffer, /) -> 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 Return the number of bytes written, which is always
the length of b in bytes. the length of b in bytes.
@ -280,8 +251,7 @@ class _BufferedIOBase(_IOBase):
def readinto1(self, buffer: WriteableBuffer, /) -> int: ... def readinto1(self, buffer: WriteableBuffer, /) -> int: ...
def read(self, size: int | None = -1, /) -> bytes: 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 If the size argument is omitted, None, or negative, read and
return all data until EOF. return all data until EOF.
@ -300,16 +270,14 @@ class _BufferedIOBase(_IOBase):
""" """
def read1(self, size: int = -1, /) -> bytes: 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. Return an empty bytes object on EOF.
A short result does not imply that EOF is imminent. 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 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, The mode can be 'r' (default), 'w', 'x' or 'a' for reading,
writing, exclusive creation or appending. The file will be created if it 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: ... ) -> None: ...
@property @property
def closefd(self) -> bool: 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: 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 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 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: 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. If size is less than 0, read all bytes in the file making multiple read calls.
See ``FileIO.readall``. 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 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: ... def __init__(self, initial_bytes: ReadableBuffer = b"") -> None: ...
# BytesIO does not contain a "name" field. This workaround is necessary # 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[]. # as a read-only property on IO[].
name: Any name: Any
def getvalue(self) -> bytes: def getvalue(self) -> bytes:
""" """Retrieve the entire contents of the BytesIO object."""
Retrieve the entire contents of the BytesIO object.
"""
def getbuffer(self) -> memoryview: 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: 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. If the size argument is negative or omitted, read until EOF is reached.
Return an empty bytes object at EOF. Return an empty bytes object at EOF.
""" """
def readlines(self, size: int | None = None, /) -> list[bytes]: 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. Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the 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: 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: Seek to byte offset pos relative to position indicated by whence:
0 Start of stream (the default). pos should be >= 0; 0 Start of stream (the default). pos should be >= 0;
@ -441,9 +396,7 @@ class _BufferedReaderStream(Protocol):
_BufferedReaderStreamT = TypeVar("_BufferedReaderStreamT", bound=_BufferedReaderStream, default=_BufferedReaderStream) _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 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 raw: _BufferedReaderStreamT
def __init__(self, raw: _BufferedReaderStreamT, buffer_size: int = 8192) -> None: ... 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: ... def truncate(self, pos: int | None = None, /) -> int: ...
class BufferedWriter(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of writelines in the base classes 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 The constructor creates a BufferedWriter for the given writeable raw
stream. If the buffer_size is not given, it defaults to 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: ... def truncate(self, pos: int | None = None, /) -> int: ...
class BufferedRandom(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of methods in the base classes 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, The constructor creates a reader and writer for a seekable stream,
raw, given in the first argument. If the buffer_size is omitted it 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: ... def truncate(self, pos: int | None = None, /) -> int: ...
class BufferedRWPair(BufferedIOBase, _BufferedIOBase, Generic[_BufferedReaderStreamT]): 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 A buffered reader object and buffered writer object put together to
form a sequential IO object that can read and write. This is typically 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: ... def peek(self, size: int = 0, /) -> bytes: ...
class _TextIOBase(_IOBase): 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 This class provides a character and line based interface to stream
I/O. There is no readinto method because Python's character strings I/O. There is no readinto method because Python's character strings
@ -512,49 +461,40 @@ class _TextIOBase(_IOBase):
errors: str | None errors: str | None
newlines: str | tuple[str, ...] | None newlines: str | tuple[str, ...] | None
def __iter__(self) -> Iterator[str]: # type: ignore[override] def __iter__(self) -> Iterator[str]: # type: ignore[override]
""" """Implement iter(self)."""
Implement iter(self).
"""
def __next__(self) -> str: # type: ignore[override] def __next__(self) -> str: # type: ignore[override]
""" """Implement next(self)."""
Implement next(self).
"""
def detach(self) -> BinaryIO: 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. After the underlying buffer has been detached, the TextIO is in an unusable state.
""" """
def write(self, s: str, /) -> int: def write(self, s: str, /) -> int:
""" """Write string s to stream.
Write string s to stream.
Return the number of characters written Return the number of characters written
(which is always equal to the length of the string). (which is always equal to the length of the string).
""" """
def writelines(self, lines: Iterable[str], /) -> None: # type: ignore[override] 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 Line separators are not added, so it is usual for each of the
lines provided to have a line separator at the end. lines provided to have a line separator at the end.
""" """
def readline(self, size: int = -1, /) -> str: # type: ignore[override] 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. Return an empty string if EOF is hit immediately.
If size is specified, at most size characters will be read. If size is specified, at most size characters will be read.
""" """
def readlines(self, hint: int = -1, /) -> list[str]: # type: ignore[override] 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 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 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: 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. Read from underlying buffer until we have size characters or we hit EOF.
If size is negative or omitted, read until 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) _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 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 encoding gives the name of the encoding that the stream will be
decoded or encoded with. It defaults to locale.getencoding(). 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, line_buffering: bool | None = None,
write_through: bool | None = None, write_through: bool | None = None,
) -> None: ) -> None:
""" """Reconfigure the text stream with new parameters.
Reconfigure the text stream with new parameters.
This also does an implicit stream flush. 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 # TextIOWrapper's version of seek only supports a limited subset of
# operations. # operations.
def seek(self, cookie: int, whence: int = 0, /) -> int: 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 cookie
Zero or an opaque number returned by tell(). 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: ... def truncate(self, pos: int | None = None, /) -> int: ...
class StringIO(TextIOBase, _TextIOBase, TextIO): # type: ignore[misc] # incompatible definitions of write in the base classes 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 The initial_value argument sets the value of object. The newline
argument is like the one of TextIOWrapper's constructor. 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[]. # as a read-only property on IO[].
name: Any name: Any
def getvalue(self) -> str: def getvalue(self) -> str:
""" """Retrieve the entire contents of the object."""
Retrieve the entire contents of the object.
"""
@property @property
def line_buffering(self) -> bool: ... def line_buffering(self) -> bool: ...
def seek(self, pos: int, whence: int = 0, /) -> int: 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: Seek to character offset pos relative to position indicated by whence:
0 Start of stream (the default). pos should be >= 0; 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: 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 The pos argument defaults to the current file position, as
returned by tell(). The current file position is unchanged. returned by tell(). The current file position is unchanged.
@ -727,8 +658,7 @@ class StringIO(TextIOBase, _TextIOBase, TextIO): # type: ignore[misc] # incomp
""" """
class IncrementalNewlineDecoder: 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 wraps another incremental decoder, translating \\r\\n and \\r into \\n.
It also records the types of newlines encountered. When used with It also records the types of newlines encountered. When used with
@ -749,8 +679,7 @@ class IncrementalNewlineDecoder:
if sys.version_info >= (3, 10): if sys.version_info >= (3, 10):
@overload @overload
def text_encoding(encoding: None, stacklevel: int = 2, /) -> Literal["locale", "utf-8"]: 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. When encoding is not None, this function returns it.
Otherwise, this function returns the default text encoding Otherwise, this function returns the default text encoding

View file

@ -8,57 +8,39 @@ from typing_extensions import Self
@final @final
class make_encoder: 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 @property
def sort_keys(self) -> bool: def sort_keys(self) -> bool:
""" """sort_keys"""
sort_keys
"""
@property @property
def skipkeys(self) -> bool: def skipkeys(self) -> bool:
""" """skipkeys"""
skipkeys
"""
@property @property
def key_separator(self) -> str: def key_separator(self) -> str:
""" """key_separator"""
key_separator
"""
@property @property
def indent(self) -> str | None: def indent(self) -> str | None:
""" """indent"""
indent
"""
@property @property
def markers(self) -> dict[int, Any] | None: def markers(self) -> dict[int, Any] | None:
""" """markers"""
markers
"""
@property @property
def default(self) -> Callable[[Any], Any]: def default(self) -> Callable[[Any], Any]:
""" """default"""
default
"""
@property @property
def encoder(self) -> Callable[[str], str]: def encoder(self) -> Callable[[str], str]:
""" """encoder"""
encoder
"""
@property @property
def item_separator(self) -> str: def item_separator(self) -> str:
""" """item_separator"""
item_separator
"""
def __new__( def __new__(
cls, cls,
@ -73,15 +55,11 @@ class make_encoder:
allow_nan: bool, allow_nan: bool,
) -> Self: ... ) -> Self: ...
def __call__(self, obj: object, _current_indent_level: int) -> Any: def __call__(self, obj: object, _current_indent_level: int) -> Any:
""" """Call self as a function."""
Call self as a function.
"""
@final @final
class make_scanner: class make_scanner:
""" """JSON scanner object"""
JSON scanner object
"""
object_hook: Any object_hook: Any
object_pairs_hook: Any object_pairs_hook: Any
@ -92,27 +70,22 @@ class make_scanner:
# TODO: 'context' needs the attrs above (ducktype), but not __call__. # TODO: 'context' needs the attrs above (ducktype), but not __call__.
def __new__(cls, context: make_scanner) -> Self: ... def __new__(cls, context: make_scanner) -> Self: ...
def __call__(self, string: str, index: int) -> tuple[Any, int]: 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: def encode_basestring(s: str, /) -> str:
""" """encode_basestring(string) -> string
encode_basestring(string) -> string
Return a JSON representation of a Python string Return a JSON representation of a Python string
""" """
def encode_basestring_ascii(s: str, /) -> str: 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 Return an ASCII-only JSON representation of a Python string
""" """
def scanstring(string: str, end: int, strict: bool = ...) -> tuple[str, int]: 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 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. character in s after the quote that started the JSON string.

View file

@ -36,30 +36,20 @@ LC_ALL: Final[int]
CHAR_MAX: Final = 127 CHAR_MAX: Final = 127
def setlocale(category: int, locale: str | None = None, /) -> str: def setlocale(category: int, locale: str | None = None, /) -> str:
""" """Activates/queries locale processing."""
Activates/queries locale processing.
"""
def localeconv() -> _LocaleConv: def localeconv() -> _LocaleConv:
""" """Returns numeric and monetary locale-specific parameters."""
Returns numeric and monetary locale-specific parameters.
"""
if sys.version_info >= (3, 11): if sys.version_info >= (3, 11):
def getencoding() -> str: def getencoding() -> str:
""" """Get the current locale encoding."""
Get the current locale encoding.
"""
def strcoll(os1: str, os2: str, /) -> int: 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: 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 # native gettext functions
# https://docs.python.org/3/library/locale.html#access-to-message-catalogs # https://docs.python.org/3/library/locale.html#access-to-message-catalogs
@ -130,42 +120,30 @@ if sys.platform != "win32":
ALT_DIGITS: Final[int] ALT_DIGITS: Final[int]
def nl_langinfo(key: int, /) -> str: 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` # This is dependent on `libintl.h` which is a part of `gettext`
# system dependency. These functions might be missing. # system dependency. These functions might be missing.
# But, we always say that they are present. # But, we always say that they are present.
def gettext(msg: str, /) -> str: def gettext(msg: str, /) -> str:
""" """gettext(msg) -> string
gettext(msg) -> string
Return translation of msg. Return translation of msg.
""" """
def dgettext(domain: str | None, msg: str, /) -> str: def dgettext(domain: str | None, msg: str, /) -> str:
""" """dgettext(domain, msg) -> string
dgettext(domain, msg) -> string
Return translation of msg in domain. Return translation of msg in domain.
""" """
def dcgettext(domain: str | None, msg: str, category: int, /) -> str: 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: 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: 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: 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.
"""

View file

@ -9,8 +9,7 @@ from types import CodeType
from typing import Any, Final, final from typing import Any, Final, final
class Profiler: 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. The default timer is a fast built-in one based on real time.
For custom timer functions returning integers, 'timeunit' can 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 self, timer: Callable[[], float] | None = None, timeunit: float = 0.0, subcalls: bool = True, builtins: bool = True
) -> None: ... ) -> None: ...
def getstats(self) -> list[profiler_entry]: def getstats(self) -> list[profiler_entry]:
""" """list of profiler_entry objects.
list of profiler_entry objects.
getstats() -> 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: def enable(self, subcalls: bool = True, builtins: bool = True) -> None:
""" """Start collecting profiling information.
Start collecting profiling information.
subcalls subcalls
If True, also records for each function If True, also records for each function
@ -61,14 +58,10 @@ class Profiler:
""" """
def disable(self) -> None: def disable(self) -> None:
""" """Stop collecting profiling information."""
Stop collecting profiling information.
"""
def clear(self) -> None: def clear(self) -> None:
""" """Clear all profiling information collected so far."""
Clear all profiling information collected so far.
"""
@final @final
class profiler_entry(structseq[Any], tuple[CodeType | str, int, int, float, float, list[profiler_subentry]]): class profiler_entry(structseq[Any], tuple[CodeType | str, int, int, float, float, list[profiler_subentry]]):

View file

@ -37,8 +37,7 @@ PRESET_EXTREME: int # v big number
@final @final
class LZMADecompressor: class LZMADecompressor:
""" """Create a decompressor object for decompressing data incrementally.
Create a decompressor object for decompressing data incrementally.
format format
Specifies the container format of the input stream. If this is 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 __init__(self, format: int | None = ..., memlimit: int | None = ..., filters: _FilterChain | None = ...) -> None: ...
def decompress(self, data: ReadableBuffer, max_length: int = -1) -> bytes: 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 If *max_length* is nonnegative, returns at most *max_length* bytes of
decompressed data. If this limit is reached and further output can be decompressed data. If this limit is reached and further output can be
@ -83,32 +81,23 @@ class LZMADecompressor:
@property @property
def check(self) -> int: 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 @property
def eof(self) -> bool: 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 @property
def unused_data(self) -> bytes: def unused_data(self) -> bytes:
""" """Data found after the end of the compressed stream."""
Data found after the end of the compressed stream.
"""
@property @property
def needs_input(self) -> bool: 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 @final
class LZMACompressor: 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. Create a compressor object for compressing data incrementally.
@ -146,8 +135,7 @@ class LZMACompressor:
) -> None: ... ) -> None: ...
def compress(self, data: ReadableBuffer, /) -> bytes: 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. Returns a chunk of compressed data if possible, or b'' otherwise.
@ -156,8 +144,7 @@ class LZMACompressor:
""" """
def flush(self) -> bytes: def flush(self) -> bytes:
""" """Finish the compression process.
Finish the compression process.
Returns the compressed data left in internal buffers. Returns the compressed data left in internal buffers.
@ -165,13 +152,10 @@ class LZMACompressor:
""" """
class LZMAError(Exception): class LZMAError(Exception):
""" """Call to liblzma failed."""
Call to liblzma failed.
"""
def is_check_supported(check_id: int, /) -> bool: 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. Always returns True for CHECK_NONE and CHECK_CRC32.
""" """

View file

@ -9,16 +9,13 @@ import sys
from typing import Any from typing import Any
class ParserBase: 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. by the SGML/HTML and XHTML parsers.
""" """
def reset(self) -> None: ... def reset(self) -> None: ...
def getpos(self) -> tuple[int, int]: 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 unknown_decl(self, data: str) -> None: ...
def parse_comment(self, i: int, report: bool = True) -> int: ... # undocumented def parse_comment(self, i: int, report: bool = True) -> int: ... # undocumented

View file

@ -1,3 +1,7 @@
"""
Documentation
"""
import sys import sys
if sys.platform == "win32": if sys.platform == "win32":
@ -46,11 +50,34 @@ if sys.platform == "win32":
__new__: None # type: ignore[assignment] __new__: None # type: ignore[assignment]
__init__: None # type: ignore[assignment] __init__: None # type: ignore[assignment]
def UuidCreate() -> str: ... def UuidCreate() -> str:
def FCICreate(cabname: str, files: list[str], /) -> None: ... """Return the string representation of a new unique identifier."""
def OpenDatabase(path: str, persist: int, /) -> _Database: ...
def CreateRecord(count: int, /) -> _Record: ...
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_NAMES: int
MSICOLINFO_TYPES: int MSICOLINFO_TYPES: int
MSIDBOPEN_CREATE: int MSIDBOPEN_CREATE: int

View file

@ -51,170 +51,104 @@ class _SupportsPos(Protocol[_T_co]):
# All four comparison functions must have the same signature, or we get false-positive errors # All four comparison functions must have the same signature, or we get false-positive errors
def lt(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: def lt(a: _SupportsComparison, b: _SupportsComparison, /) -> Any:
""" """Same as a < b."""
Same as a < b.
"""
def le(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: def le(a: _SupportsComparison, b: _SupportsComparison, /) -> Any:
""" """Same as a <= b."""
Same as a <= b.
"""
def eq(a: object, b: object, /) -> Any: def eq(a: object, b: object, /) -> Any:
""" """Same as a == b."""
Same as a == b.
"""
def ne(a: object, b: object, /) -> Any: def ne(a: object, b: object, /) -> Any:
""" """Same as a != b."""
Same as a != b.
"""
def ge(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: def ge(a: _SupportsComparison, b: _SupportsComparison, /) -> Any:
""" """Same as a >= b."""
Same as a >= b.
"""
def gt(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: def gt(a: _SupportsComparison, b: _SupportsComparison, /) -> Any:
""" """Same as a > b."""
Same as a > b.
"""
def not_(a: object, /) -> bool: def not_(a: object, /) -> bool:
""" """Same as not a."""
Same as not a.
"""
def truth(a: object, /) -> bool: 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: 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: 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: def abs(a: SupportsAbs[_T], /) -> _T:
""" """Same as abs(a)."""
Same as abs(a).
"""
def add(a: Any, b: Any, /) -> Any: def add(a: Any, b: Any, /) -> Any:
""" """Same as a + b."""
Same as a + b.
"""
def and_(a: Any, b: Any, /) -> Any: def and_(a: Any, b: Any, /) -> Any:
""" """Same as a & b."""
Same as a & b.
"""
def floordiv(a: Any, b: Any, /) -> Any: def floordiv(a: Any, b: Any, /) -> Any:
""" """Same as a // b."""
Same as a // b.
"""
def index(a: SupportsIndex, /) -> int: def index(a: SupportsIndex, /) -> int:
""" """Same as a.__index__()"""
Same as a.__index__()
"""
def inv(a: _SupportsInversion[_T_co], /) -> _T_co: def inv(a: _SupportsInversion[_T_co], /) -> _T_co:
""" """Same as ~a."""
Same as ~a.
"""
def invert(a: _SupportsInversion[_T_co], /) -> _T_co: def invert(a: _SupportsInversion[_T_co], /) -> _T_co:
""" """Same as ~a."""
Same as ~a.
"""
def lshift(a: Any, b: Any, /) -> Any: def lshift(a: Any, b: Any, /) -> Any:
""" """Same as a << b."""
Same as a << b.
"""
def mod(a: Any, b: Any, /) -> Any: def mod(a: Any, b: Any, /) -> Any:
""" """Same as a % b."""
Same as a % b.
"""
def mul(a: Any, b: Any, /) -> Any: def mul(a: Any, b: Any, /) -> Any:
""" """Same as a * b."""
Same as a * b.
"""
def matmul(a: Any, b: Any, /) -> Any: def matmul(a: Any, b: Any, /) -> Any:
""" """Same as a @ b."""
Same as a @ b.
"""
def neg(a: _SupportsNeg[_T_co], /) -> _T_co: def neg(a: _SupportsNeg[_T_co], /) -> _T_co:
""" """Same as -a."""
Same as -a.
"""
def or_(a: Any, b: Any, /) -> Any: def or_(a: Any, b: Any, /) -> Any:
""" """Same as a | b."""
Same as a | b.
"""
def pos(a: _SupportsPos[_T_co], /) -> _T_co: def pos(a: _SupportsPos[_T_co], /) -> _T_co:
""" """Same as +a."""
Same as +a.
"""
def pow(a: Any, b: Any, /) -> Any: def pow(a: Any, b: Any, /) -> Any:
""" """Same as a ** b."""
Same as a ** b.
"""
def rshift(a: Any, b: Any, /) -> Any: def rshift(a: Any, b: Any, /) -> Any:
""" """Same as a >> b."""
Same as a >> b.
"""
def sub(a: Any, b: Any, /) -> Any: def sub(a: Any, b: Any, /) -> Any:
""" """Same as a - b."""
Same as a - b.
"""
def truediv(a: Any, b: Any, /) -> Any: def truediv(a: Any, b: Any, /) -> Any:
""" """Same as a / b."""
Same as a / b.
"""
def xor(a: Any, b: Any, /) -> Any: 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]: 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: 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: 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 @overload
def delitem(a: MutableSequence[Any], b: SupportsIndex, /) -> None: def delitem(a: MutableSequence[Any], b: SupportsIndex, /) -> None:
""" """Same as del a[b]."""
Same as del a[b].
"""
@overload @overload
def delitem(a: MutableSequence[Any], b: slice, /) -> None: ... 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: ... def delitem(a: MutableMapping[_K, Any], b: _K, /) -> None: ...
@overload @overload
def getitem(a: Sequence[_T], b: slice, /) -> Sequence[_T]: def getitem(a: Sequence[_T], b: slice, /) -> Sequence[_T]:
""" """Same as a[b]."""
Same as a[b].
"""
@overload @overload
def getitem(a: SupportsGetItem[_K, _V], b: _K, /) -> _V: ... def getitem(a: SupportsGetItem[_K, _V], b: _K, /) -> _V: ...
def indexOf(a: Iterable[_T], b: _T, /) -> int: 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 @overload
def setitem(a: MutableSequence[_T], b: SupportsIndex, c: _T, /) -> None: def setitem(a: MutableSequence[_T], b: SupportsIndex, c: _T, /) -> None:
""" """Same as a[b] = c."""
Same as a[b] = c.
"""
@overload @overload
def setitem(a: MutableSequence[_T], b: slice, c: Sequence[_T], /) -> None: ... def setitem(a: MutableSequence[_T], b: slice, c: Sequence[_T], /) -> None: ...
@overload @overload
def setitem(a: MutableMapping[_K, _V], b: _K, c: _V, /) -> None: ... def setitem(a: MutableMapping[_K, _V], b: _K, c: _V, /) -> None: ...
def length_hint(obj: object, default: int = 0, /) -> int: 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. 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: def iadd(a: Any, b: Any, /) -> Any:
""" """Same as a += b."""
Same as a += b.
"""
def iand(a: Any, b: Any, /) -> Any: def iand(a: Any, b: Any, /) -> Any:
""" """Same as a &= b."""
Same as a &= b.
"""
def iconcat(a: Any, b: Any, /) -> Any: 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: def ifloordiv(a: Any, b: Any, /) -> Any:
""" """Same as a //= b."""
Same as a //= b.
"""
def ilshift(a: Any, b: Any, /) -> Any: def ilshift(a: Any, b: Any, /) -> Any:
""" """Same as a <<= b."""
Same as a <<= b.
"""
def imod(a: Any, b: Any, /) -> Any: def imod(a: Any, b: Any, /) -> Any:
""" """Same as a %= b."""
Same as a %= b.
"""
def imul(a: Any, b: Any, /) -> Any: def imul(a: Any, b: Any, /) -> Any:
""" """Same as a *= b."""
Same as a *= b.
"""
def imatmul(a: Any, b: Any, /) -> Any: def imatmul(a: Any, b: Any, /) -> Any:
""" """Same as a @= b."""
Same as a @= b.
"""
def ior(a: Any, b: Any, /) -> Any: def ior(a: Any, b: Any, /) -> Any:
""" """Same as a |= b."""
Same as a |= b.
"""
def ipow(a: Any, b: Any, /) -> Any: def ipow(a: Any, b: Any, /) -> Any:
""" """Same as a **= b."""
Same as a **= b.
"""
def irshift(a: Any, b: Any, /) -> Any: def irshift(a: Any, b: Any, /) -> Any:
""" """Same as a >>= b."""
Same as a >>= b.
"""
def isub(a: Any, b: Any, /) -> Any: def isub(a: Any, b: Any, /) -> Any:
""" """Same as a -= b."""
Same as a -= b.
"""
def itruediv(a: Any, b: Any, /) -> Any: def itruediv(a: Any, b: Any, /) -> Any:
""" """Same as a /= b."""
Same as a /= b.
"""
def ixor(a: Any, b: Any, /) -> Any: def ixor(a: Any, b: Any, /) -> Any:
""" """Same as a ^= b."""
Same as a ^= b.
"""
if sys.version_info >= (3, 11): if sys.version_info >= (3, 11):
def call(obj: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> _R: 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: def _compare_digest(a: AnyStr, b: AnyStr, /) -> bool:
""" """Return 'a == b'.
Return 'a == b'.
This function uses an approach designed to prevent This function uses an approach designed to prevent
timing analysis, making it appropriate for cryptography. 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): if sys.version_info >= (3, 14):
def is_none(a: object, /) -> TypeIs[None]: 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]: def is_not_none(a: _T | None, /) -> TypeIs[_T]:
""" """Same as a is not None."""
Same as a is not None.
"""

View file

@ -16,73 +16,49 @@ _COMPILER_CONFIG_VARS: Final[tuple[str, ...]] # undocumented
_INITPRE: Final[str] # undocumented _INITPRE: Final[str] # undocumented
def _find_executable(executable: str, path: str | None = None) -> str | None: # 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 A string listing directories separated by 'os.pathsep'; defaults to
os.environ['PATH']. Returns the complete filename or None if not found. os.environ['PATH']. Returns the complete filename or None if not found.
""" """
def _read_output(commandstring: str, capture_stderr: bool = False) -> str | None: # undocumented 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 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 _SYSTEM_VERSION: Final[str | None] # undocumented
def _get_system_version() -> str: # 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 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 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 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 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 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 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 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 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]: 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. compile flags if the user has specified one them in extra_compile_flags.
This is needed because '-arch ARCH' adds another architecture to the 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]: 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 Called internally from sysconfig with a mutable mapping
containing name/value pairs parsed from the configured 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]: 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 This customization is performed when the first
extension module build is requested 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]: 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()
"""

View file

@ -30,8 +30,7 @@ def dump(
fix_imports: bool = True, fix_imports: bool = True,
buffer_callback: _BufferCallback = None, buffer_callback: _BufferCallback = None,
) -> 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 This is equivalent to ``Pickler(file, protocol).dump(obj)``, but may
be more efficient. 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: 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 The optional *protocol* argument tells the pickler to use the given
protocol; supported protocols are 0, 1, 2, 3, 4 and 5. The default protocol; supported protocols are 0, 1, 2, 3, 4 and 5. The default
@ -89,8 +87,7 @@ def load(
errors: str = "strict", errors: str = "strict",
buffers: Iterable[Any] | None = (), buffers: Iterable[Any] | None = (),
) -> Any: ) -> 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 This is equivalent to ``Unpickler(file).load()``, but may be more
efficient. efficient.
@ -124,8 +121,7 @@ def loads(
errors: str = "strict", errors: str = "strict",
buffers: Iterable[Any] | None = (), buffers: Iterable[Any] | None = (),
) -> Any: ) -> 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 The protocol version of the pickle is detected automatically, so no
protocol argument is needed. Bytes past the pickled object's protocol argument is needed. Bytes past the pickled object's
@ -151,8 +147,7 @@ class PicklerMemoProxy:
def copy(self, /) -> dict[int, tuple[int, Any]]: ... def copy(self, /) -> dict[int, tuple[int, Any]]: ...
class Pickler: 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 The optional *protocol* argument tells the pickler to use the given
protocol; supported protocols are 0, 1, 2, 3, 4 and 5. The default protocol; supported protocols are 0, 1, 2, 3, 4 and 5. The default
@ -200,13 +195,10 @@ class Pickler:
@memo.setter @memo.setter
def memo(self, value: PicklerMemoProxy | dict[int, tuple[int, Any]]) -> None: ... def memo(self, value: PicklerMemoProxy | dict[int, tuple[int, Any]]) -> None: ...
def dump(self, obj: 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: 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 The memo is the data structure that remembers which objects the
pickler has already seen, so that shared or recursive objects are 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]]: ... def copy(self, /) -> dict[int, tuple[int, Any]]: ...
class Unpickler: 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 The protocol version of the pickle is detected automatically, so no
protocol argument is needed. Bytes past the pickled object's protocol argument is needed. Bytes past the pickled object's
@ -259,8 +250,7 @@ class Unpickler:
@memo.setter @memo.setter
def memo(self, value: UnpicklerMemoProxy | dict[int, tuple[int, Any]]) -> None: ... def memo(self, value: UnpicklerMemoProxy | dict[int, tuple[int, Any]]) -> None: ...
def load(self) -> Any: def load(self) -> Any:
""" """Load a pickle.
Load a pickle.
Read a pickled object representation from the open file object given Read a pickled object representation from the open file object given
in the constructor, and return the reconstituted object hierarchy 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: 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 If necessary, the module will be imported. Subclasses may override
this method (e.g. to restrict unpickling of arbitrary classes and this method (e.g. to restrict unpickling of arbitrary classes and

View file

@ -34,8 +34,7 @@ if sys.platform != "win32":
preexec_fn: Callable[[], None], preexec_fn: Callable[[], None],
/, /,
) -> int: ) -> 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 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 child and duplicate the few that are needed before calling exec() in the
@ -84,8 +83,7 @@ if sys.platform != "win32":
allow_vfork: bool, allow_vfork: bool,
/, /,
) -> int: ) -> 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 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 child and duplicate the few that are needed before calling exec() in the

View file

@ -6,8 +6,7 @@ _T = TypeVar("_T")
_CacheToken = NewType("_CacheToken", int) _CacheToken = NewType("_CacheToken", int)
def get_cache_token() -> _CacheToken: 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 The token is an opaque object (supporting equality testing) identifying the
current version of the ABC cache for virtual subclasses. The token changes current version of the ABC cache for virtual subclasses. The token changes
@ -15,8 +14,7 @@ def get_cache_token() -> _CacheToken:
""" """
class ABCMeta(type): 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 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 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], / mcls: type[_typeshed.Self], name: str, bases: tuple[type[Any], ...], namespace: dict[str, Any], /
) -> _typeshed.Self: ... ) -> _typeshed.Self: ...
def register(cls, subclass: type[_T]) -> type[_T]: 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. Returns the subclass, to allow usage as a class decorator.
""" """

View file

@ -9,24 +9,17 @@ from typing import Any, Generic, TypeVar
_T = TypeVar("_T") _T = TypeVar("_T")
class Empty(Exception): 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]): class SimpleQueue(Generic[_T]):
""" """Simple, unbounded, reentrant FIFO queue."""
Simple, unbounded, reentrant FIFO queue.
"""
def __init__(self) -> None: ... def __init__(self) -> None: ...
def empty(self) -> bool: 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: 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), If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is block if necessary until an item is available. If 'timeout' is
@ -38,35 +31,28 @@ class SimpleQueue(Generic[_T]):
""" """
def get_nowait(self) -> _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 Only get an item if one is immediately available. Otherwise
raise the Empty exception. raise the Empty exception.
""" """
def put(self, item: _T, block: bool = True, timeout: float | None = None) -> None: 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 The optional 'block' and 'timeout' arguments are ignored, as this method
never blocks. They are provided for compatibility with the Queue class. never blocks. They are provided for compatibility with the Queue class.
""" """
def put_nowait(self, item: _T) -> None: 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 This is exactly equivalent to `put(item)` and is only provided
for compatibility with the Queue class. for compatibility with the Queue class.
""" """
def qsize(self) -> int: 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: def __class_getitem__(cls, item: Any, /) -> GenericAlias:
""" """See PEP 585"""
See PEP 585
"""

View file

@ -8,35 +8,24 @@ from typing_extensions import TypeAlias
_State: TypeAlias = tuple[int, ...] _State: TypeAlias = tuple[int, ...]
class Random: 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 __init__(self, seed: object = ...) -> None: ...
def seed(self, n: object = None, /) -> None: def seed(self, n: object = None, /) -> None:
""" """seed([n]) -> None.
seed([n]) -> None.
Defaults to use urandom and falls back to a combination Defaults to use urandom and falls back to a combination
of the current time and the process identifier. of the current time and the process identifier.
""" """
def getstate(self) -> _State: def getstate(self) -> _State:
""" """getstate() -> tuple containing the current state."""
getstate() -> tuple containing the current state.
"""
def setstate(self, state: _State, /) -> None: def setstate(self, state: _State, /) -> None:
""" """setstate(state) -> None. Restores generator state."""
setstate(state) -> None. Restores generator state.
"""
def random(self) -> float: def random(self) -> float:
""" """random() -> x in the interval [0, 1)."""
random() -> x in the interval [0, 1).
"""
def getrandbits(self, k: int, /) -> int: 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.
"""

View file

@ -1,4 +1,5 @@
""" """
The objects used by the site module to add custom builtins. 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: ... def __call__(self, code: sys._ExitCode = None) -> NoReturn: ...
class _Printer: 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. contributors and the copyright notice.
""" """
@ -23,8 +23,7 @@ class _Printer:
def __call__(self) -> None: ... def __call__(self) -> None: ...
class _Helper: class _Helper:
""" """Define the builtin 'help'.
Define the builtin 'help'.
This is a wrapper around pydoc.help that provides a helpful message This is a wrapper around pydoc.help that provides a helpful message
when 'help' is typed at the Python interactive prompt. when 'help' is typed at the Python interactive prompt.

View file

@ -738,8 +738,7 @@ if sys.platform != "win32" and sys.platform != "darwin":
# ===== Classes ===== # ===== Classes =====
class socket: 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 socket(family=-1, type=-1, proto=-1, fileno=None) -> socket object
Open a socket of the given type. The family argument specifies the Open a socket of the given type. The family argument specifies the
@ -787,27 +786,19 @@ class socket:
@property @property
def family(self) -> int: def family(self) -> int:
""" """the socket family"""
the socket family
"""
@property @property
def type(self) -> int: def type(self) -> int:
""" """the socket type"""
the socket type
"""
@property @property
def proto(self) -> int: def proto(self) -> int:
""" """the socket protocol"""
the socket protocol
"""
# F811: "Redefinition of unused `timeout`" # F811: "Redefinition of unused `timeout`"
@property @property
def timeout(self) -> float | None: # noqa: F811 def timeout(self) -> float | None: # noqa: F811
""" """the socket timeout"""
the socket timeout
"""
if sys.platform == "win32": if sys.platform == "win32":
def __init__( def __init__(
self, family: int = ..., type: int = ..., proto: int = ..., fileno: SupportsIndex | bytes | None = ... 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 __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: SupportsIndex | None = ...) -> None: ...
def bind(self, address: _Address, /) -> 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 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 pair (host, port); the host must refer to the local host. For raw packet
@ -825,31 +815,27 @@ class socket:
""" """
def close(self) -> None: def close(self) -> None:
""" """close()
close()
Close the socket. It cannot be used after this call. Close the socket. It cannot be used after this call.
""" """
def connect(self, address: _Address, /) -> None: def connect(self, address: _Address, /) -> None:
""" """connect(address)
connect(address)
Connect the socket to a remote address. For IP sockets, the address Connect the socket to a remote address. For IP sockets, the address
is a pair (host, port). is a pair (host, port).
""" """
def connect_ex(self, address: _Address, /) -> int: 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) This is like connect(address), but returns an error code (the errno value)
instead of raising an exception when an error occurs. instead of raising an exception when an error occurs.
""" """
def detach(self) -> int: def detach(self) -> int:
""" """detach()
detach()
Close the socket object without closing the underlying file descriptor. Close the socket object without closing the underlying file descriptor.
The object cannot be used after this call, but the file descriptor The object cannot be used after this call, but the file descriptor
@ -857,23 +843,20 @@ class socket:
""" """
def fileno(self) -> int: def fileno(self) -> int:
""" """fileno() -> integer
fileno() -> integer
Return the integer file descriptor of the socket. Return the integer file descriptor of the socket.
""" """
def getpeername(self) -> _RetAddress: def getpeername(self) -> _RetAddress:
""" """getpeername() -> address info
getpeername() -> address info
Return the address of the remote endpoint. For IP sockets, the address Return the address of the remote endpoint. For IP sockets, the address
info is a pair (hostaddr, port). info is a pair (hostaddr, port).
""" """
def getsockname(self) -> _RetAddress: def getsockname(self) -> _RetAddress:
""" """getsockname() -> address info
getsockname() -> address info
Return the address of the local endpoint. The format depends on the Return the address of the local endpoint. The format depends on the
address family. For IPv4 sockets, the address info is a pair address family. For IPv4 sockets, the address info is a pair
@ -883,8 +866,7 @@ class socket:
@overload @overload
def getsockopt(self, level: int, optname: int, /) -> int: 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. Get a socket option. See the Unix manual for level and option.
If a nonzero buffersize argument is given, the return value is a If a nonzero buffersize argument is given, the return value is a
@ -894,16 +876,14 @@ class socket:
@overload @overload
def getsockopt(self, level: int, optname: int, buflen: int, /) -> bytes: ... def getsockopt(self, level: int, optname: int, buflen: int, /) -> bytes: ...
def getblocking(self) -> bool: def getblocking(self) -> bool:
""" """getblocking()
getblocking()
Returns True if socket is in blocking mode, or False if it Returns True if socket is in blocking mode, or False if it
is in non-blocking mode. is in non-blocking mode.
""" """
def gettimeout(self) -> float | None: def gettimeout(self) -> float | None:
""" """gettimeout() -> timeout
gettimeout() -> timeout
Returns the timeout in seconds (float) associated with socket Returns the timeout in seconds (float) associated with socket
operations. A timeout of None indicates that timeouts on 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 ioctl(self, control: int, option: int | tuple[int, int, int] | bool, /) -> None: ...
def listen(self, backlog: int = ..., /) -> None: def listen(self, backlog: int = ..., /) -> None:
""" """listen([backlog])
listen([backlog])
Enable a server to accept connections. If backlog is specified, it must be 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 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: 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 Receive up to buffersize bytes from the socket. For the optional flags
argument, see the Unix manual. When no data is available, block until 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]: 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. Like recv(buffersize, flags) but also return the sender's address info.
""" """
if sys.platform != "win32": if sys.platform != "win32":
def recvmsg(self, bufsize: int, ancbufsize: int = ..., flags: int = ..., /) -> tuple[bytes, list[_CMSG], int, Any]: 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 Receive normal data (up to bufsize bytes) and ancillary data from the
socket. The ancbufsize argument sets the size in bytes of the socket. The ancbufsize argument sets the size in bytes of the
@ -973,8 +949,7 @@ class socket:
def recvmsg_into( def recvmsg_into(
self, buffers: Iterable[WriteableBuffer], ancbufsize: int = ..., flags: int = ..., / self, buffers: Iterable[WriteableBuffer], ancbufsize: int = ..., flags: int = ..., /
) -> tuple[int, list[_CMSG], int, Any]: ) -> 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 Receive normal data and ancillary data from the socket, scattering the
non-ancillary data into a series of buffers. The buffers argument 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]: 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. 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: 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 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 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: 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 Send a data string to the socket. For the optional flags
argument, see the Unix manual. Return the number of bytes argument, see the Unix manual. Return the number of bytes
@ -1035,8 +1007,7 @@ class socket:
""" """
def sendall(self, data: ReadableBuffer, flags: int = ..., /) -> None: 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 Send a data string to the socket. For the optional flags
argument, see the Unix manual. This calls send() repeatedly argument, see the Unix manual. This calls send() repeatedly
@ -1046,8 +1017,7 @@ class socket:
@overload @overload
def sendto(self, data: ReadableBuffer, address: _Address, /) -> int: 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. Like send(data, flags) but allows specifying the destination address.
For IP sockets, the address is a pair (hostaddr, port). For IP sockets, the address is a pair (hostaddr, port).
@ -1064,8 +1034,7 @@ class socket:
address: _Address | None = ..., address: _Address | None = ...,
/, /,
) -> int: ) -> int:
""" """sendmsg(buffers[, ancdata[, flags[, address]]]) -> count
sendmsg(buffers[, ancdata[, flags[, address]]]) -> count
Send normal and ancillary data to the socket, gathering the Send normal and ancillary data to the socket, gathering the
non-ancillary data from a series of buffers and concatenating it into non-ancillary data from a series of buffers and concatenating it into
@ -1085,16 +1054,14 @@ class socket:
def sendmsg_afalg( def sendmsg_afalg(
self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ...
) -> 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 Set operation mode, IV and length of associated data for an AF_ALG
operation socket. operation socket.
""" """
def setblocking(self, flag: bool, /) -> None: def setblocking(self, flag: bool, /) -> None:
""" """setblocking(flag)
setblocking(flag)
Set the socket to blocking (flag is true) or non-blocking (false). Set the socket to blocking (flag is true) or non-blocking (false).
setblocking(True) is equivalent to settimeout(None); setblocking(True) is equivalent to settimeout(None);
@ -1102,8 +1069,7 @@ class socket:
""" """
def settimeout(self, value: float | None, /) -> None: def settimeout(self, value: float | None, /) -> None:
""" """settimeout(timeout)
settimeout(timeout)
Set a timeout on socket operations. 'timeout' can be a float, Set a timeout on socket operations. 'timeout' can be a float,
giving in seconds, or None. Setting a timeout of None disables giving in seconds, or None. Setting a timeout of None disables
@ -1113,8 +1079,7 @@ class socket:
@overload @overload
def setsockopt(self, level: int, optname: int, value: int | ReadableBuffer, /) -> None: 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, value: buffer)
setsockopt(level, option, None, optlen: int) setsockopt(level, option, None, optlen: int)
@ -1129,8 +1094,7 @@ class socket:
def share(self, process_id: int, /) -> bytes: ... def share(self, process_id: int, /) -> bytes: ...
def shutdown(self, how: int, /) -> None: def shutdown(self, how: int, /) -> None:
""" """shutdown(flag)
shutdown(flag)
Shut down the reading side of the socket (flag == SHUT_RD), the writing side 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). of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).
@ -1141,16 +1105,14 @@ SocketType = socket
# ===== Functions ===== # ===== Functions =====
def close(fd: SupportsIndex, /) -> None: def close(fd: SupportsIndex, /) -> None:
""" """close(integer) -> None
close(integer) -> None
Close an integer socket file descriptor. This is like os.close(), but for 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. sockets; on some platforms os.close() won't work for socket file descriptors.
""" """
def dup(fd: SupportsIndex, /) -> int: def dup(fd: SupportsIndex, /) -> int:
""" """dup(integer) -> integer
dup(integer) -> integer
Duplicate an integer socket file descriptor. This is like os.dup(), but for 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. sockets; on some platforms os.dup() won't work for socket file descriptors.
@ -1165,60 +1127,52 @@ def getaddrinfo(
proto: int = ..., proto: int = ...,
flags: int = ..., flags: int = ...,
) -> list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]]: ) -> 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) -> list of (family, type, proto, canonname, sockaddr)
Resolve host and port into addrinfo struct. Resolve host and port into addrinfo struct.
""" """
def gethostbyname(hostname: str, /) -> str: 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. 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]]: 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, 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. for a host. The host argument is a string giving a host name or IP number.
""" """
def gethostname() -> str: def gethostname() -> str:
""" """gethostname() -> string
gethostname() -> string
Return the current host name. Return the current host name.
""" """
def gethostbyaddr(ip_address: str, /) -> tuple[str, list[str], list[str]]: 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, 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. 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]: 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. Get host and port for a sockaddr.
""" """
def getprotobyname(protocolname: str, /) -> int: def getprotobyname(protocolname: str, /) -> int:
""" """getprotobyname(name) -> integer
getprotobyname(name) -> integer
Return the protocol number for the named protocol. (Rarely used.) Return the protocol number for the named protocol. (Rarely used.)
""" """
def getservbyname(servicename: str, protocolname: str = ..., /) -> int: 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. Return a port number from a service name and protocol name.
The optional protocol name, if given, should be 'tcp' or 'udp', 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: 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. Return the service name from a port number and protocol name.
The optional protocol name, if given, should be 'tcp' or 'udp', 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 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 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 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 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 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: 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: 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 Convert an IP address from string format to a packed string suitable
for use with low-level network functions. for use with low-level network functions.
""" """
def inet_ntop(address_family: int, packed_ip: ReadableBuffer, /) -> str: 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. Convert a packed IP address of the given family to string format.
""" """
def getdefaulttimeout() -> float | None: def getdefaulttimeout() -> float | None:
""" """getdefaulttimeout() -> timeout
getdefaulttimeout() -> timeout
Returns the default timeout in seconds (float) for new socket objects. Returns the default timeout in seconds (float) for new socket objects.
A value of None indicates that new socket objects have no timeout. 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`" # F811: "Redefinition of unused `timeout`"
def setdefaulttimeout(timeout: float | None, /) -> None: # noqa: F811 def setdefaulttimeout(timeout: float | None, /) -> None: # noqa: F811
""" """setdefaulttimeout(timeout)
setdefaulttimeout(timeout)
Set the default timeout in seconds (float) for new socket objects. Set the default timeout in seconds (float) for new socket objects.
A value of None indicates that new socket objects have no timeout. 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": if sys.platform != "win32":
def sethostname(name: str, /) -> None: def sethostname(name: str, /) -> None:
""" """sethostname(name)
sethostname(name)
Sets the hostname to name. Sets the hostname to name.
""" """
def CMSG_LEN(length: int, /) -> int: 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 Return the total length, without trailing padding, of an ancillary
data item with associated data of the given length. This value can 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: 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 Return the buffer size needed for recvmsg() to receive an ancillary
data item with associated data of the given length, along with any 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]: 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 Create a pair of socket objects from the sockets returned by the platform
socketpair() function. socketpair() function.
@ -1342,27 +1275,21 @@ if sys.platform != "win32":
""" """
def if_nameindex() -> list[tuple[int, str]]: def if_nameindex() -> list[tuple[int, str]]:
""" """if_nameindex()
if_nameindex()
Returns a list of network interface information (index, name) tuples. Returns a list of network interface information (index, name) tuples.
""" """
def if_nametoindex(oname: str, /) -> int: 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): if sys.version_info >= (3, 14):
def if_indextoname(if_index: int, /) -> str: 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: else:
def if_indextoname(index: int, /) -> str: 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. Returns the interface name corresponding to the interface index if_index.
""" """

View file

@ -215,16 +215,12 @@ if sys.version_info >= (3, 11):
# Can take or return anything depending on what's in the registry. # Can take or return anything depending on what's in the registry.
@overload @overload
def adapt(obj: Any, proto: Any, /) -> Any: def adapt(obj: Any, proto: Any, /) -> Any:
""" """Adapt given object to given protocol."""
Adapt given object to given protocol.
"""
@overload @overload
def adapt(obj: Any, proto: Any, alt: _T, /) -> Any | _T: ... def adapt(obj: Any, proto: Any, alt: _T, /) -> Any | _T: ...
def complete_statement(statement: str) -> bool: 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): if sys.version_info >= (3, 12):
@overload @overload
@ -239,8 +235,7 @@ if sys.version_info >= (3, 12):
*, *,
autocommit: bool = ..., autocommit: bool = ...,
) -> Connection: ) -> 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 You can use ":memory:" to open a database connection to a database that
resides in RAM instead of on disk. resides in RAM instead of on disk.
@ -289,8 +284,7 @@ else:
cached_statements: int = 128, cached_statements: int = 128,
uri: bool = False, uri: bool = False,
) -> Connection: ) -> 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 You can use ":memory:" to open a database connection to a database that resides
in RAM instead of on disk. in RAM instead of on disk.
@ -321,15 +315,12 @@ else:
) -> _ConnectionT: ... ) -> _ConnectionT: ...
def enable_callback_tracebacks(enable: bool, /) -> None: 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): if sys.version_info < (3, 12):
# takes a pos-or-keyword argument because there is a C wrapper # takes a pos-or-keyword argument because there is a C wrapper
def enable_shared_cache(do_enable: int) -> None: 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. This method is deprecated and will be removed in Python 3.12.
Shared cache is strongly discouraged by the SQLite 3 documentation. 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): if sys.version_info >= (3, 10):
def register_adapter(type: type[_T], adapter: _Adapter[_T], /) -> None: 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: 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: else:
def register_adapter(type: type[_T], caster: _Adapter[_T], /) -> None: 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. Registers an adapter with sqlite3's adapter registry.
""" """
def register_converter(name: str, converter: _Converter, /) -> None: def register_converter(name: str, converter: _Converter, /) -> None:
""" """register_converter(typename, callable)
register_converter(typename, callable)
Registers a converter with sqlite3. Registers a converter with sqlite3.
""" """

View file

@ -51,22 +51,18 @@ class _CertInfo(TypedDict):
crlDistributionPoints: NotRequired[tuple[str, ...] | None] crlDistributionPoints: NotRequired[tuple[str, ...] | None]
def RAND_add(string: str | ReadableBuffer, entropy: float, /) -> 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 entropy (a float) is a lower bound on the entropy contained in
string. See RFC 4086. string. See RFC 4086.
""" """
def RAND_bytes(n: int, /) -> bytes: 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): if sys.version_info < (3, 12):
def RAND_pseudo_bytes(n: int, /) -> tuple[bytes, bool]: 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 Return a pair (bytes, is_cryptographic). is_cryptographic is True
if the bytes generated are cryptographically strong. 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_egd(path: str) -> None: ...
def RAND_status() -> bool: 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 It is necessary to seed the PRNG with RAND_add() on some platforms before
using the ssl() function. using the ssl() function.
""" """
def get_default_verify_paths() -> tuple[str, str, str, str]: 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'. The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
""" """
if sys.platform == "win32": if sys.platform == "win32":
_EnumRetType: TypeAlias = list[tuple[bytes, str, set[str] | bool]] _EnumRetType: TypeAlias = list[tuple[bytes, str, set[str] | bool]]
def enum_certificates(store_name: str) -> _EnumRetType: ... def enum_certificates(store_name: str) -> _EnumRetType:
def enum_crls(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]: 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 By default objects are looked up by OID. With name=True short and
long name are also matched. long name are also matched.
""" """
def nid2obj(nid: int, /) -> tuple[int, str, str, str]: 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: class _SSLContext:
check_hostname: bool check_hostname: bool
@ -124,8 +131,7 @@ class _SSLContext:
verify_mode: int verify_mode: int
def __new__(cls, protocol: int, /) -> Self: ... def __new__(cls, protocol: int, /) -> Self: ...
def cert_store_stats(self) -> dict[str, int]: 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 X.509 certificates with a CA extension and certificate revocation lists
inside the context's cert store. inside the context's cert store.
@ -136,8 +142,7 @@ class _SSLContext:
@overload @overload
def get_ca_certs(self, binary_form: Literal[False] = False) -> list[_PeerCertRetDictType]: 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 If the optional argument is True, returns a DER-encoded copy of the CA
certificate. certificate.
@ -177,8 +182,7 @@ class MemoryBIO:
pending: int pending: int
def __new__(self) -> Self: ... def __new__(self) -> Self: ...
def read(self, size: int = -1, /) -> bytes: 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 size is not specified, read the entire buffer.
If the return value is an empty bytes instance, this means either If the return value is an empty bytes instance, this means either
@ -187,15 +191,13 @@ class MemoryBIO:
""" """
def write(self, b: ReadableBuffer, /) -> int: 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. Returns the number of bytes written.
""" """
def write_eof(self) -> None: 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. When all data has been read, the "eof" property will be True.
""" """
@ -205,33 +207,23 @@ class SSLSession:
__hash__: ClassVar[None] # type: ignore[assignment] __hash__: ClassVar[None] # type: ignore[assignment]
@property @property
def has_ticket(self) -> bool: def has_ticket(self) -> bool:
""" """Does the session contain a ticket?"""
Does the session contain a ticket?
"""
@property @property
def id(self) -> bytes: def id(self) -> bytes:
""" """Session ID."""
Session ID.
"""
@property @property
def ticket_lifetime_hint(self) -> int: def ticket_lifetime_hint(self) -> int:
""" """Ticket life time hint."""
Ticket life time hint.
"""
@property @property
def time(self) -> int: def time(self) -> int:
""" """Session creation time (seconds since epoch)."""
Session creation time (seconds since epoch).
"""
@property @property
def timeout(self) -> int: 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. # _ssl.Certificate is weird: it can't be instantiated or subclassed.
# Instances can only be created via methods of the private _ssl._SSLSocket class, # Instances can only be created via methods of the private _ssl._SSLSocket class,

View file

@ -137,89 +137,73 @@ UF_NOUNLINK: Final = 0x00000010
UF_OPAQUE: Final = 0x00000008 UF_OPAQUE: Final = 0x00000008
def S_IMODE(mode: int, /) -> int: 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: 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: 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. Return True if mode is from a block special device file.
""" """
def S_ISCHR(mode: int, /) -> bool: 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. Return True if mode is from a character special device file.
""" """
def S_ISDIR(mode: int, /) -> bool: def S_ISDIR(mode: int, /) -> bool:
""" """S_ISDIR(mode) -> bool
S_ISDIR(mode) -> bool
Return True if mode is from a directory. Return True if mode is from a directory.
""" """
def S_ISDOOR(mode: int, /) -> bool: def S_ISDOOR(mode: int, /) -> bool:
""" """S_ISDOOR(mode) -> bool
S_ISDOOR(mode) -> bool
Return True if mode is from a door. Return True if mode is from a door.
""" """
def S_ISFIFO(mode: int, /) -> bool: def S_ISFIFO(mode: int, /) -> bool:
""" """S_ISFIFO(mode) -> bool
S_ISFIFO(mode) -> bool
Return True if mode is from a FIFO (named pipe). Return True if mode is from a FIFO (named pipe).
""" """
def S_ISLNK(mode: int, /) -> bool: def S_ISLNK(mode: int, /) -> bool:
""" """S_ISLNK(mode) -> bool
S_ISLNK(mode) -> bool
Return True if mode is from a symbolic link. Return True if mode is from a symbolic link.
""" """
def S_ISPORT(mode: int, /) -> bool: def S_ISPORT(mode: int, /) -> bool:
""" """S_ISPORT(mode) -> bool
S_ISPORT(mode) -> bool
Return True if mode is from an event port. Return True if mode is from an event port.
""" """
def S_ISREG(mode: int, /) -> bool: def S_ISREG(mode: int, /) -> bool:
""" """S_ISREG(mode) -> bool
S_ISREG(mode) -> bool
Return True if mode is from a regular file. Return True if mode is from a regular file.
""" """
def S_ISSOCK(mode: int, /) -> bool: def S_ISSOCK(mode: int, /) -> bool:
""" """S_ISSOCK(mode) -> bool
S_ISSOCK(mode) -> bool
Return True if mode is from a socket. Return True if mode is from a socket.
""" """
def S_ISWHT(mode: int, /) -> bool: def S_ISWHT(mode: int, /) -> bool:
""" """S_ISWHT(mode) -> bool
S_ISWHT(mode) -> bool
Return True if mode is from a whiteout. Return True if mode is from a whiteout.
""" """
def filemode(mode: int, /) -> str: 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": if sys.platform == "win32":
IO_REPARSE_TAG_SYMLINK: Final = 0xA000000C IO_REPARSE_TAG_SYMLINK: Final = 0xA000000C

View file

@ -34,16 +34,14 @@ from collections.abc import Iterator
from typing import Any from typing import Any
def pack(fmt: str | bytes, /, *v: Any) -> bytes: 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 Return a bytes object containing the values v1, v2, ... packed according
to the format string. See help(struct) for more on format strings. 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: 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 Pack the values v1, v2, ... according to the format string and write
the packed bytes into the writable buffer buf starting at offset. Note 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, ...]: 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). 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, ...]: 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). 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, ...]]: 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 The bytes are unpacked according to the format string, like
a repeated invocation of unpack_from(). 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: 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: class Struct:
""" """Struct(fmt) --> compiled struct object"""
Struct(fmt) --> compiled struct object
"""
@property @property
def format(self) -> str: def format(self) -> str:
""" """struct format string"""
struct format string
"""
@property @property
def size(self) -> int: def size(self) -> int:
""" """struct size in bytes"""
struct size in bytes
"""
def __init__(self, format: str | bytes) -> None: ... def __init__(self, format: str | bytes) -> None: ...
def pack(self, *v: Any) -> bytes: 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 Return a bytes object containing values v1, v2, ... packed according
to the format string S.format. See help(struct) for more on format 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: 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 Pack the values v1, v2, ... according to the format string S.format
and write the packed bytes into the writable buffer buf starting at 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, ...]: 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 Unpack according to the format string Struct.format. The buffer's size
in bytes must be Struct.size. in bytes must be Struct.size.
@ -132,8 +116,7 @@ class Struct:
""" """
def unpack_from(self, buffer: ReadableBuffer, offset: int = 0) -> tuple[Any, ...]: 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. 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, ...]]: 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 Tuples are unpacked from the given bytes source, like a repeated
invocation of unpack_from(). invocation of unpack_from().

View file

@ -17,8 +17,7 @@ _Ts = TypeVarTuple("_Ts")
error = RuntimeError error = RuntimeError
def _count() -> int: 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 the main thread. The returned number comprises all threads created
through `start_new_thread()` as well as `threading.Thread`, and not through `start_new_thread()` as well as `threading.Thread`, and not
yet finished. yet finished.
@ -30,8 +29,7 @@ def _count() -> int:
@final @final
class RLock: class RLock:
def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: 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 for the lock to be available or not. If `blocking` is False
and another thread holds the lock, the method will return False and another thread holds the lock, the method will return False
immediately. If `blocking` is True and another thread holds immediately. If `blocking` is True and another thread holds
@ -46,8 +44,7 @@ class RLock:
""" """
def release(self) -> None: 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, 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 and must be locked by the same thread that unlocks it; otherwise a
`RuntimeError` is raised. `RuntimeError` is raised.
@ -58,13 +55,10 @@ class RLock:
""" """
__enter__ = acquire __enter__ = acquire
def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: 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): if sys.version_info >= (3, 14):
def locked(self) -> bool: def locked(self) -> bool:
""" """locked()
locked()
Return a boolean indicating whether this object is locked right now. 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( def start_joinable_thread(
function: Callable[[], object], handle: _ThreadHandle | None = None, daemon: bool = True function: Callable[[], object], handle: _ThreadHandle | None = None, daemon: bool = True
) -> _ThreadHandle: ) -> _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. 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 Unlike start_new_thread(), this returns a handle object with methods to join
@ -95,8 +88,7 @@ if sys.version_info >= (3, 13):
@final @final
class lock: 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: call threading.Lock(). Methods are:
acquire() -- lock the lock, possibly blocking until it can be obtained 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: 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 locked (even by the same thread), waiting for another thread to release
the lock, and return True once the lock is acquired. the lock, and return True once the lock is acquired.
With an argument, this will only block if the argument is true, 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: 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, 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. but it needn't be locked by the same thread that unlocks it.
""" """
def locked(self) -> bool: 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: 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: def release_lock(self) -> None:
""" """An obsolete synonym of release()."""
An obsolete synonym of release().
"""
def locked_lock(self) -> bool: def locked_lock(self) -> bool:
""" """An obsolete synonym of locked()."""
An obsolete synonym of locked().
"""
def __enter__(self) -> bool: def __enter__(self) -> bool:
""" """Lock the lock."""
Lock the lock.
"""
def __exit__( def __exit__(
self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None
) -> None: ) -> None:
""" """Release the lock."""
Release the lock.
"""
LockType = lock LockType = lock
else: else:
@final @final
class LockType: 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: call threading.Lock(). Methods are:
acquire() -- lock the lock, possibly blocking until it can be obtained 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: 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) (acquire_lock() is an obsolete synonym)
Lock the lock. Without argument, this blocks if the lock is already Lock the lock. Without argument, this blocks if the lock is already
@ -188,8 +164,7 @@ else:
""" """
def release(self) -> None: def release(self) -> None:
""" """release()
release()
(release_lock() is an obsolete synonym) (release_lock() is an obsolete synonym)
Release the lock, allowing another thread that is blocked waiting for Release the lock, allowing another thread that is blocked waiting for
@ -198,16 +173,14 @@ else:
""" """
def locked(self) -> bool: def locked(self) -> bool:
""" """locked() -> bool
locked() -> bool
(locked_lock() is an obsolete synonym) (locked_lock() is an obsolete synonym)
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: 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) (acquire_lock() is an obsolete synonym)
Lock the lock. Without argument, this blocks if the lock is already Lock the lock. Without argument, this blocks if the lock is already
@ -219,8 +192,7 @@ else:
""" """
def release_lock(self) -> None: def release_lock(self) -> None:
""" """release()
release()
(release_lock() is an obsolete synonym) (release_lock() is an obsolete synonym)
Release the lock, allowing another thread that is blocked waiting for Release the lock, allowing another thread that is blocked waiting for
@ -229,16 +201,14 @@ else:
""" """
def locked_lock(self) -> bool: def locked_lock(self) -> bool:
""" """locked() -> bool
locked() -> bool
(locked_lock() is an obsolete synonym) (locked_lock() is an obsolete synonym)
Return whether the lock is in the locked state. Return whether the lock is in the locked state.
""" """
def __enter__(self) -> bool: def __enter__(self) -> bool:
""" """acquire(blocking=True, timeout=-1) -> bool
acquire(blocking=True, timeout=-1) -> bool
(acquire_lock() is an obsolete synonym) (acquire_lock() is an obsolete synonym)
Lock the lock. Without argument, this blocks if the lock is already Lock the lock. Without argument, this blocks if the lock is already
@ -252,8 +222,7 @@ else:
def __exit__( def __exit__(
self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None
) -> None: ) -> None:
""" """release()
release()
(release_lock() is an obsolete synonym) (release_lock() is an obsolete synonym)
Release the lock, allowing another thread that is blocked waiting for Release the lock, allowing another thread that is blocked waiting for
@ -263,8 +232,7 @@ else:
@overload @overload
def start_new_thread(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]], /) -> int: 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 The thread will call the function with positional arguments from the
tuple args and keyword arguments taken from the optional dictionary 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() # Obsolete synonym for start_new_thread()
@overload @overload
def start_new(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]], /) -> int: 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 @overload
def start_new(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any], /) -> int: ... def start_new(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any], /) -> int: ...
if sys.version_info >= (3, 10): if sys.version_info >= (3, 10):
def interrupt_main(signum: signal.Signals = ..., /) -> None: 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. where the corresponding signal handler will be executed.
If *signum* is omitted, SIGINT is assumed. If *signum* is omitted, SIGINT is assumed.
A subthread can use this function to interrupt the main thread. A subthread can use this function to interrupt the main thread.
@ -300,38 +265,30 @@ if sys.version_info >= (3, 10):
else: else:
def interrupt_main() -> None: def interrupt_main() -> None:
""" """interrupt_main()
interrupt_main()
Raise a KeyboardInterrupt in the main thread. Raise a KeyboardInterrupt in the main thread.
A subthread can use this function to interrupt the main thread. A subthread can use this function to interrupt the main thread.
""" """
def exit() -> NoReturn: 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. thread to exit silently unless the exception is caught.
""" """
def exit_thread() -> NoReturn: # Obsolete synonym for exit() def exit_thread() -> NoReturn: # Obsolete synonym for exit()
""" """An obsolete synonym of exit()."""
An obsolete synonym of exit().
"""
def allocate_lock() -> LockType: 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. information about locks.
""" """
def allocate() -> LockType: # Obsolete synonym for allocate_lock() def allocate() -> LockType: # Obsolete synonym for allocate_lock()
""" """An obsolete synonym of allocate_lock()."""
An obsolete synonym of allocate_lock().
"""
def get_ident() -> int: 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. amongst other threads that exist simultaneously.
This may be used to identify per-thread resources. This may be used to identify per-thread resources.
Even though on some platforms threads identities may appear to be 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: 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 optional size argument specifies the stack size (in bytes) to be used
for subsequently created threads, and must be 0 (use platform or for subsequently created threads, and must be 0 (use platform or
configured default) or a positive integer value of at least 32,768 (32k). 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 TIMEOUT_MAX: float
def get_native_id() -> int: # only available on some platforms 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 by the OS (kernel). This may be used to uniquely identify a
particular thread within a system. particular thread within a system.
""" """
@final @final
class _ExceptHookArgs(structseq[Any], tuple[type[BaseException], BaseException | None, TracebackType | None, Thread | None]): class _ExceptHookArgs(structseq[Any], tuple[type[BaseException], BaseException | None, TracebackType | None, Thread | None]):
""" """ExceptHookArgs
ExceptHookArgs
Type used to pass arguments to threading.excepthook. Type used to pass arguments to threading.excepthook.
""" """
@ -382,47 +336,34 @@ class _ExceptHookArgs(structseq[Any], tuple[type[BaseException], BaseException |
@property @property
def exc_type(self) -> type[BaseException]: def exc_type(self) -> type[BaseException]:
""" """Exception type"""
Exception type
"""
@property @property
def exc_value(self) -> BaseException | None: def exc_value(self) -> BaseException | None:
""" """Exception value"""
Exception value
"""
@property @property
def exc_traceback(self) -> TracebackType | None: def exc_traceback(self) -> TracebackType | None:
""" """Exception traceback"""
Exception traceback
"""
@property @property
def thread(self) -> Thread | None: def thread(self) -> Thread | None:
""" """Thread"""
Thread
"""
_excepthook: Callable[[_ExceptHookArgs], Any] _excepthook: Callable[[_ExceptHookArgs], Any]
if sys.version_info >= (3, 12): if sys.version_info >= (3, 12):
def daemon_threads_allowed() -> bool: 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. and False otherwise.
""" """
if sys.version_info >= (3, 14): if sys.version_info >= (3, 14):
def set_name(name: str) -> None: def set_name(name: str) -> None:
""" """Set the name of the current thread."""
Set the name of the current thread.
"""
class _local: class _local:
""" """Thread-local data"""
Thread-local data
"""
def __getattribute__(self, name: str, /) -> Any: ... def __getattribute__(self, name: str, /) -> Any: ...
def __setattr__(self, name: str, value: Any, /) -> None: ... def __setattr__(self, name: str, value: Any, /) -> None: ...

View file

@ -16,9 +16,7 @@ __all__ = ["local"]
_LocalDict: TypeAlias = dict[Any, Any] _LocalDict: TypeAlias = dict[Any, Any]
class _localimpl: class _localimpl:
""" """A class managing thread-local dicts"""
A class managing thread-local dicts
"""
key: str key: str
dicts: dict[int, tuple[ReferenceType[Any], _LocalDict]] dicts: dict[int, tuple[ReferenceType[Any], _LocalDict]]
@ -26,15 +24,12 @@ class _localimpl:
localargs: tuple[list[Any], dict[str, Any]] localargs: tuple[list[Any], dict[str, Any]]
locallock: RLock locallock: RLock
def get_dict(self) -> _LocalDict: 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. defined.
""" """
def create_dict(self) -> _LocalDict: 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: class local:
def __new__(cls, /, *args: Any, **kw: Any) -> Self: ... def __new__(cls, /, *args: Any, **kw: Any) -> Self: ...

View file

@ -20,15 +20,11 @@ from typing_extensions import TypeAlias
class Tcl_Obj: class Tcl_Obj:
@property @property
def string(self) -> str: 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 @property
def typename(self) -> str: def typename(self) -> str:
""" """name of the Tcl type"""
name of the Tcl type
"""
__hash__: ClassVar[None] # type: ignore[assignment] __hash__: ClassVar[None] # type: ignore[assignment]
def __eq__(self, value, /): ... def __eq__(self, value, /): ...
def __ge__(self, value, /): ... def __ge__(self, value, /): ...
@ -99,14 +95,10 @@ class TkappType:
def willdispatch(self): ... def willdispatch(self): ...
if sys.version_info >= (3, 12): if sys.version_info >= (3, 12):
def gettrace(self, /) -> _TkinterTraceFunc | None: def gettrace(self, /) -> _TkinterTraceFunc | None:
""" """Get the tracing function."""
Get the tracing function.
"""
def settrace(self, func: _TkinterTraceFunc | None, /) -> None: 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 # These should be kept in sync with tkinter.tix constants, except ALL_EVENTS which doesn't match TCL_ALL_EVENTS
ALL_EVENTS: Final = -3 ALL_EVENTS: Final = -3
@ -139,8 +131,7 @@ if sys.version_info >= (3, 13):
use: str | None = None, use: str | None = None,
/, /,
): ):
""" """wantTk
wantTk
if false, then Tk_Init() doesn't get called if false, then Tk_Init() doesn't get called
sync sync
if true, then pass -sync to wish if true, then pass -sync to wish
@ -160,8 +151,7 @@ else:
use: str | None = None, use: str | None = None,
/, /,
): ):
""" """wantTk
wantTk
if false, then Tk_Init() doesn't get called if false, then Tk_Init() doesn't get called
sync sync
if true, then pass -sync to wish if true, then pass -sync to wish
@ -170,13 +160,10 @@ else:
""" """
def getbusywaitinterval(): 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, /): 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. It should be set to a divisor of the maximum time between frames in an animation.
""" """

View file

@ -6,8 +6,7 @@ from collections.abc import Sequence
from tracemalloc import _FrameTuple, _TraceTuple from tracemalloc import _FrameTuple, _TraceTuple
def _get_object_traceback(obj: object, /) -> Sequence[_FrameTuple] | None: 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 a tuple of (filename: str, lineno: int) tuples.
Return None if the tracemalloc module is disabled or did not 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]: 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. Return a list of (size: int, traceback: tuple) tuples.
traceback is a tuple of (filename: str, lineno: int) tuples. traceback is a tuple of (filename: str, lineno: int) tuples.
@ -25,55 +23,45 @@ def _get_traces() -> Sequence[_TraceTuple]:
""" """
def clear_traces() -> None: 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: 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 By default, a trace of an allocated memory block only stores
the most recent frame: the limit is 1. the most recent frame: the limit is 1.
""" """
def get_traced_memory() -> tuple[int, int]: 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). Returns a tuple: (current: int, peak: int).
""" """
def get_tracemalloc_memory() -> 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. This memory is used internally to trace memory allocations.
""" """
def is_tracing() -> bool: 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: 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. Do nothing if the tracemalloc module is not tracing memory allocations.
""" """
def start(nframe: int = 1, /) -> None: 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 Also set the maximum number of frames stored in the traceback of a
trace to nframe. trace to nframe.
""" """
def stop() -> None: def stop() -> None:
""" """Stop tracing Python memory allocations.
Stop tracing Python memory allocations.
Also clear traces of memory blocks allocated by Python. Also clear traces of memory blocks allocated by Python.
""" """

View file

@ -20,8 +20,7 @@ if sys.version_info >= (3, 12):
*, *,
skip_file_prefixes: tuple[str, ...] = (), skip_file_prefixes: tuple[str, ...] = (),
) -> None: ) -> None:
""" """Issue a warning, or maybe ignore it or raise an exception.
Issue a warning, or maybe ignore it or raise an exception.
message message
Text of the warning message. Text of the warning message.
@ -50,9 +49,7 @@ if sys.version_info >= (3, 12):
else: else:
@overload @overload
def warn(message: str, category: type[Warning] | None = None, stacklevel: int = 1, source: Any | None = None) -> None: 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 @overload
def warn(message: Warning, category: Any = None, stacklevel: int = 1, source: Any | None = None) -> None: ... 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 = ..., module_globals: dict[str, Any] | None = ...,
source: Any | None = ..., 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 @overload
def warn_explicit( def warn_explicit(

View file

@ -10,20 +10,15 @@ _C = TypeVar("_C", bound=Callable[..., Any])
_T = TypeVar("_T") _T = TypeVar("_T")
def getweakrefcount(object: Any, /) -> int: 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]: 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 # Return CallableProxyType if object is callable, ProxyType otherwise
@overload @overload
def proxy(object: _C, callback: Callable[[_C], Any] | None = None, /) -> CallableProxyType[_C]: 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 'callback', if given, is called with a reference to the
proxy when 'object' is about to be finalized. proxy when 'object' is about to be finalized.

View file

@ -46,8 +46,7 @@ class WeakSet(MutableSet[_T]):
def __or__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... def __or__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ...
def isdisjoint(self, other: Iterable[_T]) -> bool: ... def isdisjoint(self, other: Iterable[_T]) -> bool: ...
def __class_getitem__(cls, item: Any, /) -> GenericAlias: 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,). E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
""" """

View file

@ -172,7 +172,9 @@ if sys.platform == "win32":
ERROR_ACCESS_DENIED: Final = 5 ERROR_ACCESS_DENIED: Final = 5
ERROR_PRIVILEGE_NOT_HELD: Final = 1314 ERROR_PRIVILEGE_NOT_HELD: Final = 1314
def CloseHandle(handle: int, /) -> None: ... def CloseHandle(handle: int, /) -> None:
"""Close handle."""
@overload @overload
def ConnectNamedPipe(handle: int, overlapped: Literal[True]) -> Overlapped: ... def ConnectNamedPipe(handle: int, overlapped: Literal[True]) -> Overlapped: ...
@overload @overload
@ -201,7 +203,15 @@ if sys.platform == "win32":
security_attributes: int, security_attributes: int,
/, /,
) -> 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( def CreateProcess(
application_name: str | None, application_name: str | None,
command_line: str | None, command_line: str | None,
@ -213,7 +223,20 @@ if sys.platform == "win32":
current_directory: str | None, current_directory: str | None,
startup_info: Any, 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( def DuplicateHandle(
source_process_handle: int, source_process_handle: int,
source_handle: int, source_handle: int,
@ -222,16 +245,49 @@ if sys.platform == "win32":
inherit_handle: bool, inherit_handle: bool,
options: int = 0, 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 ExitProcess(ExitCode: int, /) -> NoReturn: ...
def GetACP() -> int: ... def GetACP() -> int:
"""Get the current Windows ANSI code page identifier."""
def GetFileType(handle: int) -> int: ... def GetFileType(handle: int) -> int: ...
def GetCurrentProcess() -> int: ... def GetCurrentProcess() -> int:
def GetExitCodeProcess(process: int, /) -> 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 GetLastError() -> int: ...
def GetModuleFileName(module_handle: int, /) -> str: ... def GetModuleFileName(module_handle: int, /) -> str:
def GetStdHandle(std_handle: int, /) -> int: ... """Return the fully-qualified path for the file that contains module.
def GetVersion() -> int: ...
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 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]: ... def PeekNamedPipe(handle: int, size: int = 0, /) -> tuple[int, int] | tuple[bytes, int, int]: ...
if sys.version_info >= (3, 10): if sys.version_info >= (3, 10):
@ -247,9 +303,18 @@ if sys.platform == "win32":
def SetNamedPipeHandleState( def SetNamedPipeHandleState(
named_pipe: int, mode: int | None, max_collection_count: int | None, collect_data_timeout: int | None, / named_pipe: int, mode: int | None, max_collection_count: int | None, collect_data_timeout: int | None, /
) -> 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 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: ... def WaitNamedPipe(name: str, timeout: int, /) -> None: ...
@overload @overload
def WriteFile(handle: int, buffer: ReadableBuffer, overlapped: Literal[True]) -> tuple[Overlapped, int]: ... 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]: ... def WriteFile(handle: int, buffer: ReadableBuffer, overlapped: int | bool) -> tuple[Any, int]: ...
@final @final
class Overlapped: class Overlapped:
"""OVERLAPPED structure wrapper"""
event: int event: int
def GetOverlappedResult(self, wait: bool, /) -> tuple[int, int]: ... def GetOverlappedResult(self, wait: bool, /) -> tuple[int, int]: ...
def cancel(self) -> None: ... def cancel(self) -> None: ...
def getbuffer(self) -> bytes | None: ... def getbuffer(self) -> bytes | None: ...
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
def BatchedWaitForMultipleObjects( def BatchedWaitForMultipleObjects(handle_seq: Sequence[int], wait_all: bool, milliseconds: int = 0xFFFFFFFF) -> list[int]:
handle_seq: Sequence[int], wait_all: bool, milliseconds: int = 0xFFFFFFFF """Supports a larger number of handles than WaitForMultipleObjects
) -> list[int]: ...
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 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 CreateMutexW(security_attributes: int, initial_owner: bool, name: str) -> int: ...
def GetLongPathName(path: str) -> str: ... def GetLongPathName(path: str) -> str:
def GetShortPathName(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 OpenEventW(desired_access: int, inherit_handle: bool, name: str) -> int: ...
def OpenMutexW(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: ... def ReleaseMutex(mutex: int) -> None: ...
@ -279,5 +376,14 @@ if sys.platform == "win32":
def SetEvent(event: int) -> None: ... def SetEvent(event: int) -> None: ...
if sys.version_info >= (3, 12): 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: ... def NeedCurrentDirectoryForExePath(exe_name: str, /) -> bool: ...

View file

@ -46,8 +46,7 @@ _ZstdCompressorFlushFrame: TypeAlias = Literal[2]
@final @final
class ZstdCompressor: class ZstdCompressor:
""" """Create a compressor object for compressing data incrementally.
Create a compressor object for compressing data incrementally.
level level
The compression level to use. Defaults to COMPRESSION_LEVEL_DEFAULT. The compression level to use. Defaults to COMPRESSION_LEVEL_DEFAULT.
@ -69,8 +68,7 @@ class ZstdCompressor:
def compress( def compress(
self, /, data: ReadableBuffer, mode: _ZstdCompressorContinue | _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 0 self, /, data: ReadableBuffer, mode: _ZstdCompressorContinue | _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 0
) -> bytes: ) -> bytes:
""" """Provide data to the compressor object.
Provide data to the compressor object.
mode mode
Can be these 3 values ZstdCompressor.CONTINUE, Can be these 3 values ZstdCompressor.CONTINUE,
@ -82,8 +80,7 @@ class ZstdCompressor:
""" """
def flush(self, /, mode: _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 2) -> bytes: def flush(self, /, mode: _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 2) -> bytes:
""" """Finish the compression process.
Finish the compression process.
mode mode
Can be these 2 values ZstdCompressor.FLUSH_FRAME, Can be these 2 values ZstdCompressor.FLUSH_FRAME,
@ -95,8 +92,7 @@ class ZstdCompressor:
""" """
def set_pledged_input_size(self, size: int | None, /) -> None: 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 size
The size of the uncompressed data to be provided to the compressor. The size of the uncompressed data to be provided to the compressor.
@ -112,8 +108,7 @@ class ZstdCompressor:
@property @property
def last_mode(self) -> _ZstdCompressorContinue | _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame: 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. .FLUSH_BLOCK, .FLUSH_FRAME. Initialized to .FLUSH_FRAME.
It can be used to get the current state of a compressor, such as, data It can be used to get the current state of a compressor, such as, data
@ -122,8 +117,7 @@ class ZstdCompressor:
@final @final
class ZstdDecompressor: class ZstdDecompressor:
""" """Create a decompressor object for decompressing data incrementally.
Create a decompressor object for decompressing data incrementally.
zstd_dict zstd_dict
A ZstdDict object, a pre-trained Zstandard dictionary. 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 __init__(self, zstd_dict: ZstdDict | None = None, options: Mapping[int, int] | None = None) -> None: ...
def decompress(self, /, data: ReadableBuffer, max_length: int = -1) -> bytes: 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 data
A bytes-like object, Zstandard data to be decompressed. A bytes-like object, Zstandard data to be decompressed.
@ -162,15 +155,13 @@ class ZstdDecompressor:
@property @property
def eof(self) -> bool: 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. after that, an EOFError exception will be raised.
""" """
@property @property
def needs_input(self) -> bool: 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 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 to False. In this case, passing b'' to the .decompress() method may output
further data. further data.
@ -178,8 +169,7 @@ class ZstdDecompressor:
@property @property
def unused_data(self) -> bytes: 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 When ZstdDecompressor object stops after a frame is
decompressed, unused input data after the frame. Otherwise this will be b''. decompressed, unused input data after the frame. Otherwise this will be b''.
@ -187,8 +177,7 @@ class ZstdDecompressor:
@final @final
class ZstdDict: class ZstdDict:
""" """Represents a Zstandard dictionary.
Represents a Zstandard dictionary.
dict_content dict_content
The content of a Zstandard dictionary as a bytes-like object. 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 __init__(self, dict_content: bytes, /, *, is_raw: bool = False) -> None: ...
def __len__(self, /) -> int: def __len__(self, /) -> int:
""" """Return len(self)."""
Return len(self).
"""
@property @property
def as_digested_dict(self) -> tuple[Self, int]: 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: Pass this attribute as zstd_dict argument:
compress(dat, zstd_dict=zd.as_digested_dict) compress(dat, zstd_dict=zd.as_digested_dict)
@ -225,8 +211,7 @@ class ZstdDict:
@property @property
def as_prefix(self) -> tuple[Self, int]: 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: Pass this attribute as zstd_dict argument:
compress(dat, zstd_dict=zd.as_prefix) compress(dat, zstd_dict=zd.as_prefix)
@ -239,8 +224,7 @@ class ZstdDict:
@property @property
def as_undigested_dict(self) -> tuple[Self, int]: 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: Pass this attribute as zstd_dict argument:
compress(dat, zstd_dict=zd.as_undigested_dict) compress(dat, zstd_dict=zd.as_undigested_dict)
@ -253,14 +237,11 @@ class ZstdDict:
@property @property
def dict_content(self) -> bytes: 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 @property
def dict_id(self) -> int: 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. A non-zero value represents an ordinary Zstandard dictionary, conforming to the standardised format.
@ -268,15 +249,12 @@ class ZstdDict:
""" """
class ZstdError(Exception): class ZstdError(Exception):
""" """An error occurred in the zstd library."""
An error occurred in the zstd library.
"""
def finalize_dict( def finalize_dict(
custom_dict_bytes: bytes, samples_bytes: bytes, samples_sizes: tuple[int, ...], dict_size: int, compression_level: int, / custom_dict_bytes: bytes, samples_bytes: bytes, samples_sizes: tuple[int, ...], dict_size: int, compression_level: int, /
) -> bytes: ) -> bytes:
""" """Finalize a Zstandard dictionary.
Finalize a Zstandard dictionary.
custom_dict_bytes custom_dict_bytes
Custom dictionary content. Custom dictionary content.
@ -291,16 +269,14 @@ def finalize_dict(
""" """
def get_frame_info(frame_buffer: ReadableBuffer) -> tuple[int, int]: 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 frame_buffer
A bytes-like object, containing the header of a Zstandard frame. A bytes-like object, containing the header of a Zstandard frame.
""" """
def get_frame_size(frame_buffer: ReadableBuffer) -> int: 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 frame_buffer
A bytes-like object, it should start from the beginning of a frame, 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]: def get_param_bounds(parameter: int, is_compress: bool) -> tuple[int, int]:
""" """Get CompressionParameter/DecompressionParameter bounds.
Get CompressionParameter/DecompressionParameter bounds.
parameter parameter
The parameter to get bounds. 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: 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 c_parameter_type
CompressionParameter IntEnum type object 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: 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 samples_bytes
Concatenation of samples. Concatenation of samples.

View file

@ -16,8 +16,7 @@ _P = ParamSpec("_P")
# These definitions have special processing in mypy # These definitions have special processing in mypy
class ABCMeta(type): 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 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 directly, and then acts as a mix-in class. You can also register
@ -41,30 +40,22 @@ class ABCMeta(type):
) -> _typeshed.Self: ... ) -> _typeshed.Self: ...
def __instancecheck__(cls: ABCMeta, instance: Any) -> bool: def __instancecheck__(cls: ABCMeta, instance: Any) -> bool:
""" """Override for isinstance(instance, cls)."""
Override for isinstance(instance, cls).
"""
def __subclasscheck__(cls: ABCMeta, subclass: type) -> bool: 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: 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]: 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. Returns the subclass, to allow usage as a class decorator.
""" """
def abstractmethod(funcobj: _FuncT) -> _FuncT: 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 Requires that the metaclass is ABCMeta or derived from it. A
class that has a metaclass derived from ABCMeta cannot be 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") @deprecated("Use 'classmethod' with 'abstractmethod' instead")
class abstractclassmethod(classmethod[_T, _P, _R_co]): class abstractclassmethod(classmethod[_T, _P, _R_co]):
""" """A decorator indicating abstract classmethods.
A decorator indicating abstract classmethods.
Deprecated, use 'classmethod' with 'abstractmethod' instead: Deprecated, use 'classmethod' with 'abstractmethod' instead:
@ -100,8 +90,7 @@ class abstractclassmethod(classmethod[_T, _P, _R_co]):
@deprecated("Use 'staticmethod' with 'abstractmethod' instead") @deprecated("Use 'staticmethod' with 'abstractmethod' instead")
class abstractstaticmethod(staticmethod[_P, _R_co]): class abstractstaticmethod(staticmethod[_P, _R_co]):
""" """A decorator indicating abstract staticmethods.
A decorator indicating abstract staticmethods.
Deprecated, use 'staticmethod' with 'abstractmethod' instead: Deprecated, use 'staticmethod' with 'abstractmethod' instead:
@ -117,8 +106,7 @@ class abstractstaticmethod(staticmethod[_P, _R_co]):
@deprecated("Use 'property' with 'abstractmethod' instead") @deprecated("Use 'property' with 'abstractmethod' instead")
class abstractproperty(property): class abstractproperty(property):
""" """A decorator indicating abstract properties.
A decorator indicating abstract properties.
Deprecated, use 'property' with 'abstractmethod' instead: Deprecated, use 'property' with 'abstractmethod' instead:
@ -132,16 +120,14 @@ class abstractproperty(property):
__isabstractmethod__: Literal[True] __isabstractmethod__: Literal[True]
class ABC(metaclass=ABCMeta): 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. inheritance.
""" """
__slots__ = () __slots__ = ()
def get_cache_token() -> object: 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 The token is an opaque object (supporting equality testing) identifying the
current version of the ABC cache for virtual subclasses. The token changes 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): if sys.version_info >= (3, 10):
def update_abstractmethods(cls: type[_T]) -> type[_T]: 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 If a class has had one of its abstract methods implemented after the
class was created, the method will not be considered implemented until class was created, the method will not be considered implemented until

View file

@ -144,9 +144,7 @@ __all__ = ["Error", "open"]
class Error(Exception): ... class Error(Exception): ...
class _aifc_params(NamedTuple): class _aifc_params(NamedTuple):
""" """_aifc_params(nchannels, sampwidth, framerate, nframes, comptype, compname)"""
_aifc_params(nchannels, sampwidth, framerate, nframes, comptype, compname)
"""
nchannels: int nchannels: int
sampwidth: int sampwidth: int

View file

@ -32,8 +32,7 @@ if sys.version_info >= (3, 14):
@final @final
class ForwardRef: class ForwardRef:
""" """Wrapper that holds a forward reference.
Wrapper that holds a forward reference.
Constructor arguments: Constructor arguments:
* arg: a string representing the code to be evaluated. * arg: a string representing the code to be evaluated.
@ -60,8 +59,7 @@ if sys.version_info >= (3, 14):
owner: object = None, owner: object = None,
format: Literal[Format.STRING], format: Literal[Format.STRING],
) -> str: ) -> 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. If the forward reference cannot be evaluated, raise an exception.
""" """
@ -106,8 +104,7 @@ if sys.version_info >= (3, 14):
@overload @overload
def call_evaluate_function(evaluate: EvaluateFunc, format: Literal[Format.STRING], *, owner: object = None) -> str: 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 the value of type aliases and the bounds, constraints, and defaults of
type parameter objects. 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: ... def call_evaluate_function(evaluate: EvaluateFunc, format: Format, *, owner: object = None) -> AnnotationForm: ...
@overload @overload
def call_annotate_function(annotate: AnnotateFunc, format: Literal[Format.STRING], *, owner: object = None) -> dict[str, str]: 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 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 can be called with any of the format arguments in the Format enum, but
compiler-generated __annotate__ functions only support the VALUE format. compiler-generated __annotate__ functions only support the VALUE format.
@ -147,8 +143,7 @@ if sys.version_info >= (3, 14):
@overload @overload
def call_annotate_function(annotate: AnnotateFunc, format: Format, *, owner: object = None) -> dict[str, AnnotationForm]: ... 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: 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. Return None if the namespace does not contain an annotate function.
This is useful in metaclass ``__new__`` methods to retrieve the 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, eval_str: bool = False,
format: Literal[Format.STRING], format: Literal[Format.STRING],
) -> dict[str, str]: ) -> 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 obj may be a callable, class, module, or other object with
__annotate__ or __annotations__ attributes. __annotate__ or __annotations__ attributes.
@ -234,8 +228,7 @@ if sys.version_info >= (3, 14):
format: Format = Format.VALUE, # noqa: Y011 format: Format = Format.VALUE, # noqa: Y011
) -> dict[str, AnnotationForm]: ... ) -> dict[str, AnnotationForm]: ...
def type_repr(value: object) -> str: 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 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 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]: 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. Always returns a fresh a dictionary.
""" """

View file

@ -105,8 +105,7 @@ ZERO_OR_MORE: Final = "*"
_UNRECOGNIZED_ARGS_ATTR: Final = "_unrecognized_args" # undocumented _UNRECOGNIZED_ARGS_ATTR: Final = "_unrecognized_args" # undocumented
class ArgumentError(Exception): 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 The string value of this exception is the message, augmented with
information about the argument that caused it. information about the argument that caused it.
@ -118,8 +117,7 @@ class ArgumentError(Exception):
# undocumented # undocumented
class _AttributeHolder: class _AttributeHolder:
""" """Abstract base class that provides __repr__.
Abstract base class that provides __repr__.
The __repr__ method returns a string in the format:: The __repr__ method returns a string in the format::
ClassName(attr=name, attr=name, ...) ClassName(attr=name, attr=name, ...)
@ -171,8 +169,7 @@ class _ActionsContainer:
version: str = ..., version: str = ...,
**kwargs: Any, **kwargs: Any,
) -> Action: ) -> Action:
""" """add_argument(dest, ..., name=value, ...)
add_argument(dest, ..., name=value, ...)
add_argument(option_string, option_string, ..., name=value, ...) add_argument(option_string, option_string, ..., name=value, ...)
""" """
@ -201,8 +198,7 @@ class _FormatterClass(Protocol):
def __call__(self, *, prog: str) -> HelpFormatter: ... def __call__(self, *, prog: str) -> HelpFormatter: ...
class ArgumentParser(_AttributeHolder, _ActionsContainer): class ArgumentParser(_AttributeHolder, _ActionsContainer):
""" """Object for parsing command line strings into Python objects.
Object for parsing command line strings into Python objects.
Keyword Arguments: Keyword Arguments:
- prog -- The name of the program (default: - 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 convert_arg_line_to_args(self, arg_line: str) -> list[str]: ...
def exit(self, status: int = 0, message: str | None = None) -> NoReturn: ... def exit(self, status: int = 0, message: str | None = None) -> NoReturn: ...
def error(self, message: str) -> NoReturn: def error(self, message: str) -> NoReturn:
""" """error(message: string)
error(message: string)
Prints a usage message incorporating the message to stderr and Prints a usage message incorporating the message to stderr and
exits. exits.
@ -378,8 +373,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
def _print_message(self, message: str, file: SupportsWrite[str] | None = None) -> None: ... def _print_message(self, message: str, file: SupportsWrite[str] | None = None) -> None: ...
class HelpFormatter: 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 Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail. 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: ... def _get_default_metavar_for_positional(self, action: Action) -> str: ...
class RawDescriptionHelpFormatter(HelpFormatter): 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 Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail. provided by the class are considered an implementation detail.
""" """
class RawTextHelpFormatter(RawDescriptionHelpFormatter): 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 Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail. provided by the class are considered an implementation detail.
""" """
class ArgumentDefaultsHelpFormatter(HelpFormatter): 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 Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail. provided by the class are considered an implementation detail.
""" """
class MetavarTypeHelpFormatter(HelpFormatter): 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') metavar value (instead of the argument 'dest')
Only the name of this class is considered a public API. All the methods Only the name of this class is considered a public API. All the methods
@ -479,8 +469,7 @@ class MetavarTypeHelpFormatter(HelpFormatter):
""" """
class Action(_AttributeHolder): 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 Action objects are used by an ArgumentParser to represent the information
needed to parse a single argument from one or more strings from the needed to parse a single argument from one or more strings from the
@ -665,8 +654,7 @@ else:
) -> None: ... ) -> None: ...
class Namespace(_AttributeHolder): class Namespace(_AttributeHolder):
""" """Simple object for storing attributes.
Simple object for storing attributes.
Implements equality by attribute names and values, and provides a simple Implements equality by attribute names and values, and provides a simple
string representation. string representation.
@ -682,8 +670,7 @@ class Namespace(_AttributeHolder):
if sys.version_info >= (3, 14): if sys.version_info >= (3, 14):
@deprecated("Deprecated in Python 3.14; Simply open files after parsing arguments") @deprecated("Deprecated in Python 3.14; Simply open files after parsing arguments")
class FileType: 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 Instances of FileType are typically passed as type= arguments to the
ArgumentParser add_argument() method. ArgumentParser add_argument() method.
@ -711,8 +698,7 @@ if sys.version_info >= (3, 14):
else: else:
class FileType: 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 Instances of FileType are typically passed as type= arguments to the
ArgumentParser add_argument() method. ArgumentParser add_argument() method.
@ -1044,9 +1030,7 @@ class _SubParsersAction(Action, Generic[_ArgumentParserT]):
# undocumented # undocumented
class ArgumentTypeError(Exception): 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 # undocumented
def _get_action_name(argument: Action | None) -> str | None: ... def _get_action_name(argument: Action | None) -> str | None: ...

View file

@ -22,8 +22,7 @@ _T = TypeVar("_T", int, float, str)
typecodes: str typecodes: str
class array(MutableSequence[_T]): class array(MutableSequence[_T]):
""" """array(typecode [, initializer]) -> array
array(typecode [, initializer]) -> array
Return a new array whose items are restricted by typecode, and Return a new array whose items are restricted by typecode, and
initialized from the optional initializer value, which must be a list, initialized from the optional initializer value, which must be a list,
@ -83,15 +82,11 @@ class array(MutableSequence[_T]):
@property @property
def typecode(self) -> _TypeCode: def typecode(self) -> _TypeCode:
""" """the typecode character used to create the array"""
the typecode character used to create the array
"""
@property @property
def itemsize(self) -> int: def itemsize(self) -> int:
""" """the size, in bytes, of one array item"""
the size, in bytes, of one array item
"""
@overload @overload
def __new__( def __new__(
@ -110,54 +105,39 @@ class array(MutableSequence[_T]):
@overload @overload
def __new__(cls, typecode: str, initializer: bytes | bytearray = ..., /) -> Self: ... def __new__(cls, typecode: str, initializer: bytes | bytearray = ..., /) -> Self: ...
def append(self, v: _T, /) -> None: 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]: 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 length should be multiplied by the itemsize attribute to calculate
the buffer length in bytes. the buffer length in bytes.
""" """
def byteswap(self) -> None: 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 If the items in the array are not 1, 2, 4, or 8 bytes in size, RuntimeError is
raised. raised.
""" """
def count(self, v: _T, /) -> int: 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: 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: 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: 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: 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: 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. 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 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): if sys.version_info >= (3, 10):
def index(self, v: _T, start: int = 0, stop: int = sys.maxsize, /) -> int: 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. Raise ValueError if the value is not present.
""" """
else: else:
def index(self, v: _T, /) -> int: # type: ignore[override] 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. Raise ValueError if the value is not present.
""" """
def insert(self, i: int, v: _T, /) -> None: 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: 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. i defaults to -1.
""" """
def remove(self, v: _T, /) -> None: 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: 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: 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]: 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: 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; 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 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] __hash__: ClassVar[None] # type: ignore[assignment]
def __len__(self) -> int: def __len__(self) -> int:
""" """Return len(self)."""
Return len(self).
"""
@overload @overload
def __getitem__(self, key: SupportsIndex, /) -> _T: def __getitem__(self, key: SupportsIndex, /) -> _T:
""" """Return self[key]."""
Return self[key].
"""
@overload @overload
def __getitem__(self, key: slice, /) -> array[_T]: ... def __getitem__(self, key: slice, /) -> array[_T]: ...
@overload # type: ignore[override] @overload # type: ignore[override]
def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: def __setitem__(self, key: SupportsIndex, value: _T, /) -> None:
""" """Set self[key] to value."""
Set self[key] to value.
"""
@overload @overload
def __setitem__(self, key: slice, value: array[_T], /) -> None: ... def __setitem__(self, key: slice, value: array[_T], /) -> None: ...
def __delitem__(self, key: SupportsIndex | slice, /) -> None: def __delitem__(self, key: SupportsIndex | slice, /) -> None:
""" """Delete self[key]."""
Delete self[key].
"""
def __add__(self, value: array[_T], /) -> array[_T]: def __add__(self, value: array[_T], /) -> array[_T]:
""" """Return self+value."""
Return self+value.
"""
def __eq__(self, value: object, /) -> bool: ... def __eq__(self, value: object, /) -> bool: ...
def __ge__(self, value: array[_T], /) -> bool: ... def __ge__(self, value: array[_T], /) -> bool: ...
def __gt__(self, value: array[_T], /) -> bool: ... def __gt__(self, value: array[_T], /) -> bool: ...
def __iadd__(self, value: array[_T], /) -> Self: # type: ignore[override] def __iadd__(self, value: array[_T], /) -> Self: # type: ignore[override]
""" """Implement self+=value."""
Implement self+=value.
"""
def __imul__(self, value: int, /) -> Self: def __imul__(self, value: int, /) -> Self:
""" """Implement self*=value."""
Implement self*=value.
"""
def __le__(self, value: array[_T], /) -> bool: ... def __le__(self, value: array[_T], /) -> bool: ...
def __lt__(self, value: array[_T], /) -> bool: ... def __lt__(self, value: array[_T], /) -> bool: ...
def __mul__(self, value: int, /) -> array[_T]: def __mul__(self, value: int, /) -> array[_T]:
""" """Return self*value."""
Return self*value.
"""
def __rmul__(self, value: int, /) -> array[_T]: def __rmul__(self, value: int, /) -> array[_T]:
""" """Return value*self."""
Return value*self.
"""
def __copy__(self) -> array[_T]: def __copy__(self) -> array[_T]:
""" """Return a copy of the array."""
Return a copy of the array.
"""
def __deepcopy__(self, unused: Any, /) -> array[_T]: 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: 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: 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): if sys.version_info >= (3, 12):
def __class_getitem__(cls, item: Any, /) -> GenericAlias: def __class_getitem__(cls, item: Any, /) -> GenericAlias:
""" """See PEP 585"""
See PEP 585
"""
ArrayType = array ArrayType = array

File diff suppressed because it is too large Load diff

View file

@ -28,8 +28,7 @@ class simple_producer:
def more(self) -> bytes: ... def more(self) -> bytes: ...
class async_chat(asyncore.dispatcher): 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() the two methods collect_incoming_data() and found_terminator()
""" """
@ -40,8 +39,7 @@ class async_chat(asyncore.dispatcher):
@abstractmethod @abstractmethod
def found_terminator(self) -> None: ... def found_terminator(self) -> None: ...
def set_terminator(self, term: bytes | int | None) -> 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. 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(self, data: bytes) -> None: ...
def push_with_producer(self, producer: simple_producer) -> None: ... def push_with_producer(self, producer: simple_producer) -> None: ...
def close_when_done(self) -> 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 initiate_send(self) -> None: ...
def discard_buffers(self) -> None: ... def discard_buffers(self) -> None: ...

View file

@ -76,8 +76,7 @@ class Server(AbstractServer):
def sockets(self) -> tuple[socket, ...]: ... def sockets(self) -> tuple[socket, ...]: ...
def close(self) -> None: ... def close(self) -> None: ...
async def wait_closed(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 the server is not closed, wait.
- If it is closed, but there are still active connections, wait. - If it is closed, but there are still active connections, wait.
@ -96,13 +95,10 @@ class Server(AbstractServer):
class BaseEventLoop(AbstractEventLoop): class BaseEventLoop(AbstractEventLoop):
def run_forever(self) -> None: def run_forever(self) -> None:
""" """Run until stop() is called."""
Run until stop() is called.
"""
def run_until_complete(self, future: _AwaitableLike[_T]) -> _T: 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. If the argument is a coroutine, it is wrapped in a Task.
@ -114,26 +110,20 @@ class BaseEventLoop(AbstractEventLoop):
""" """
def stop(self) -> None: def stop(self) -> None:
""" """Stop running the event loop.
Stop running the event loop.
Every callback already scheduled will still run. This simply informs Every callback already scheduled will still run. This simply informs
run_forever to stop looping after a complete iteration. run_forever to stop looping after a complete iteration.
""" """
def is_running(self) -> bool: 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: 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: def close(self) -> None:
""" """Close the event loop.
Close the event loop.
This clears the queues and shuts down the executor, This clears the queues and shuts down the executor,
but does not wait for the executor to finish. but does not wait for the executor to finish.
@ -142,13 +132,10 @@ class BaseEventLoop(AbstractEventLoop):
""" """
async def shutdown_asyncgens(self) -> None: async def shutdown_asyncgens(self) -> None:
""" """Shutdown all active asynchronous generators."""
Shutdown all active asynchronous generators.
"""
# Methods scheduling callbacks. All these return Handles. # Methods scheduling callbacks. All these return Handles.
def call_soon(self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None) -> Handle: 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 This operates as a FIFO queue: callbacks are called in the
order in which they are registered. Each callback will be order in which they are registered. Each callback will be
@ -161,8 +148,7 @@ class BaseEventLoop(AbstractEventLoop):
def call_later( def call_later(
self, delay: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None self, delay: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None
) -> TimerHandle: ) -> 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 Return a Handle: an opaque object with a cancel() method that
can be used to cancel the call. can be used to cancel the call.
@ -181,15 +167,13 @@ class BaseEventLoop(AbstractEventLoop):
def call_at( def call_at(
self, when: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None self, when: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None
) -> TimerHandle: ) -> 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. Absolute time corresponds to the event loop's time() method.
""" """
def time(self) -> float: 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 This is a float expressed in seconds since an epoch, but the
epoch, precision, accuracy and drift are unspecified and may epoch, precision, accuracy and drift are unspecified and may
@ -197,28 +181,23 @@ class BaseEventLoop(AbstractEventLoop):
""" """
# Future methods # Future methods
def create_future(self) -> Future[Any]: def create_future(self) -> Future[Any]:
""" """Create a Future object attached to the loop."""
Create a Future object attached to the loop.
"""
# Tasks methods # Tasks methods
if sys.version_info >= (3, 11): if sys.version_info >= (3, 11):
def create_task(self, coro: _CoroutineLike[_T], *, name: object = None, context: Context | None = None) -> Task[_T]: 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. Return a task object.
""" """
else: else:
def create_task(self, coro: _CoroutineLike[_T], *, name: object = None) -> Task[_T]: 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. Return a task object.
""" """
def set_task_factory(self, factory: _TaskFactory | None) -> None: 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. 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: 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 # Methods for interacting with threads
def call_soon_threadsafe( def call_soon_threadsafe(
self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None
) -> Handle: ) -> 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 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] def set_default_executor(self, executor: ThreadPoolExecutor) -> None: ... # type: ignore[override]
@ -276,8 +251,7 @@ class BaseEventLoop(AbstractEventLoop):
interleave: int | None = None, interleave: int | None = None,
all_errors: bool = False, all_errors: bool = False,
) -> tuple[Transport, _ProtocolT]: ) -> tuple[Transport, _ProtocolT]:
""" """Connect to a TCP server.
Connect to a TCP server.
Create a streaming transport connection to a given internet host and Create a streaming transport connection to a given internet host and
port: socket family AF_INET or socket.AF_INET6 depending on host (or 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, happy_eyeballs_delay: float | None = None,
interleave: int | None = None, interleave: int | None = None,
) -> tuple[Transport, _ProtocolT]: ) -> tuple[Transport, _ProtocolT]:
""" """Connect to a TCP server.
Connect to a TCP server.
Create a streaming transport connection to a given internet host and Create a streaming transport connection to a given internet host and
port: socket family AF_INET or socket.AF_INET6 depending on host (or 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, happy_eyeballs_delay: float | None = None,
interleave: int | None = None, interleave: int | None = None,
) -> tuple[Transport, _ProtocolT]: ) -> tuple[Transport, _ProtocolT]:
""" """Connect to a TCP server.
Connect to a TCP server.
Create a streaming transport connection to a given internet host and Create a streaming transport connection to a given internet host and
port: socket family AF_INET or socket.AF_INET6 depending on host (or 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, ssl_shutdown_timeout: float | None = None,
start_serving: bool = True, start_serving: bool = True,
) -> Server: ) -> Server:
""" """Create a TCP server.
Create a TCP server.
The host parameter can be a string, in that case the TCP server is The host parameter can be a string, in that case the TCP server is
bound to host and port. bound to host and port.
@ -488,8 +459,7 @@ class BaseEventLoop(AbstractEventLoop):
ssl_shutdown_timeout: float | None = None, ssl_shutdown_timeout: float | None = None,
start_serving: bool = True, start_serving: bool = True,
) -> Server: ) -> Server:
""" """Create a TCP server.
Create a TCP server.
The host parameter can be a string, in that case the TCP server is The host parameter can be a string, in that case the TCP server is
bound to host and port. bound to host and port.
@ -541,8 +511,7 @@ class BaseEventLoop(AbstractEventLoop):
ssl_handshake_timeout: float | None = None, ssl_handshake_timeout: float | None = None,
start_serving: bool = True, start_serving: bool = True,
) -> Server: ) -> Server:
""" """Create a TCP server.
Create a TCP server.
The host parameter can be a string, in that case the TCP server is The host parameter can be a string, in that case the TCP server is
bound to host and port. bound to host and port.
@ -588,8 +557,7 @@ class BaseEventLoop(AbstractEventLoop):
ssl_handshake_timeout: float | None = None, ssl_handshake_timeout: float | None = None,
ssl_shutdown_timeout: float | None = None, ssl_shutdown_timeout: float | None = None,
) -> Transport | None: ) -> Transport | None:
""" """Upgrade transport to TLS.
Upgrade transport to TLS.
Return a new transport that *protocol* should start using Return a new transport that *protocol* should start using
immediately. immediately.
@ -604,8 +572,7 @@ class BaseEventLoop(AbstractEventLoop):
ssl_handshake_timeout: float | None = None, ssl_handshake_timeout: float | None = None,
ssl_shutdown_timeout: float | None = None, ssl_shutdown_timeout: float | None = None,
) -> tuple[Transport, _ProtocolT]: ) -> tuple[Transport, _ProtocolT]:
""" """Handle an accepted connection.
Handle an accepted connection.
This is used by servers that accept connections outside of This is used by servers that accept connections outside of
asyncio but that use asyncio to handle connections. asyncio but that use asyncio to handle connections.
@ -624,8 +591,7 @@ class BaseEventLoop(AbstractEventLoop):
server_hostname: str | None = None, server_hostname: str | None = None,
ssl_handshake_timeout: float | None = None, ssl_handshake_timeout: float | None = None,
) -> Transport | None: ) -> Transport | None:
""" """Upgrade transport to TLS.
Upgrade transport to TLS.
Return a new transport that *protocol* should start using Return a new transport that *protocol* should start using
immediately. immediately.
@ -639,8 +605,7 @@ class BaseEventLoop(AbstractEventLoop):
ssl: _SSLContext = None, ssl: _SSLContext = None,
ssl_handshake_timeout: float | None = None, ssl_handshake_timeout: float | None = None,
) -> tuple[Transport, _ProtocolT]: ) -> tuple[Transport, _ProtocolT]:
""" """Handle an accepted connection.
Handle an accepted connection.
This is used by servers that accept connections outside of This is used by servers that accept connections outside of
asyncio but that use asyncio to handle connections. asyncio but that use asyncio to handle connections.
@ -655,8 +620,7 @@ class BaseEventLoop(AbstractEventLoop):
async def sendfile( async def sendfile(
self, transport: WriteTransport, file: IO[bytes], offset: int = 0, count: int | None = None, *, fallback: bool = True self, transport: WriteTransport, file: IO[bytes], offset: int = 0, count: int | None = None, *, fallback: bool = True
) -> int: ) -> int:
""" """Send a file to transport.
Send a file to transport.
Return the total number of bytes which were sent. Return the total number of bytes which were sent.
@ -692,9 +656,7 @@ class BaseEventLoop(AbstractEventLoop):
allow_broadcast: bool | None = None, allow_broadcast: bool | None = None,
sock: socket | None = None, sock: socket | None = None,
) -> tuple[DatagramTransport, _ProtocolT]: ) -> tuple[DatagramTransport, _ProtocolT]:
""" """Create datagram connection."""
Create datagram connection.
"""
else: else:
async def create_datagram_endpoint( async def create_datagram_endpoint(
self, self,
@ -710,9 +672,7 @@ class BaseEventLoop(AbstractEventLoop):
allow_broadcast: bool | None = None, allow_broadcast: bool | None = None,
sock: socket | None = None, sock: socket | None = None,
) -> tuple[DatagramTransport, _ProtocolT]: ) -> tuple[DatagramTransport, _ProtocolT]:
""" """Create datagram connection."""
Create datagram connection.
"""
# Pipes and subprocesses. # Pipes and subprocesses.
async def connect_read_pipe( async def connect_read_pipe(
self, protocol_factory: Callable[[], _ProtocolT], pipe: Any self, protocol_factory: Callable[[], _ProtocolT], pipe: Any
@ -772,8 +732,7 @@ class BaseEventLoop(AbstractEventLoop):
def remove_signal_handler(self, sig: int) -> bool: ... def remove_signal_handler(self, sig: int) -> bool: ...
# Error handlers. # Error handlers.
def set_exception_handler(self, handler: _ExceptionHandler | None) -> None: 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 If handler is None, the default exception handler will
be set. be set.
@ -786,13 +745,10 @@ class BaseEventLoop(AbstractEventLoop):
""" """
def get_exception_handler(self) -> _ExceptionHandler | None: 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: def default_exception_handler(self, context: _Context) -> None:
""" """Default exception handler.
Default exception handler.
This is called when an exception occurs and no exception This is called when an exception occurs and no exception
handler is set, and can be called by a custom 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: 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: The context argument is a dict containing the following keys:
@ -837,8 +792,7 @@ class BaseEventLoop(AbstractEventLoop):
def set_debug(self, enabled: bool) -> None: ... def set_debug(self, enabled: bool) -> None: ...
if sys.version_info >= (3, 12): if sys.version_info >= (3, 12):
async def shutdown_default_executor(self, timeout: float | None = None) -> None: 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 The timeout parameter specifies the amount of time the executor will
be given to finish joining. The default value is None, which means be given to finish joining. The default value is None, which means
@ -846,8 +800,7 @@ class BaseEventLoop(AbstractEventLoop):
""" """
else: else:
async def shutdown_default_executor(self) -> None: 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 The timeout parameter specifies the amount of time the executor will
be given to finish joining. The default value is None, which means be given to finish joining. The default value is None, which means

View file

@ -16,11 +16,7 @@ _CANCELLED: Final = "CANCELLED" # undocumented
_FINISHED: Final = "FINISHED" # undocumented _FINISHED: Final = "FINISHED" # undocumented
def _format_callbacks(cb: Sequence[tuple[Callable[[futures.Future[Any]], None], Context]]) -> str: # 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 def _future_repr_info(future: futures.Future[Any]) -> list[str]: # undocumented
""" """helper function for Future.__repr__"""
helper function for Future.__repr__
"""

View file

@ -53,8 +53,7 @@ class BaseSubprocessTransport(transports.SubprocessTransport):
def _pipe_data_received(self, fd: int, data: bytes) -> None: ... # undocumented def _pipe_data_received(self, fd: int, data: bytes) -> None: ... # undocumented
def _process_exited(self, returncode: int) -> None: ... # undocumented def _process_exited(self, returncode: int) -> None: ... # undocumented
async def _wait(self) -> int: # 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. This method is a coroutine.
""" """

View file

@ -15,9 +15,7 @@ if sys.version_info >= (3, 12):
THREAD_JOIN_TIMEOUT: Final = 300 THREAD_JOIN_TIMEOUT: Final = 300
class _SendfileMode(enum.Enum): class _SendfileMode(enum.Enum):
""" """An enumeration."""
An enumeration.
"""
UNSUPPORTED = 1 UNSUPPORTED = 1
TRY_NATIVE = 2 TRY_NATIVE = 2

View file

@ -15,8 +15,7 @@ _P = ParamSpec("_P")
if sys.version_info < (3, 11): if sys.version_info < (3, 11):
def coroutine(func: _FunctionT) -> _FunctionT: def coroutine(func: _FunctionT) -> _FunctionT:
""" """Decorator to mark coroutines.
Decorator to mark coroutines.
If the coroutine is not yielded from before it is destroyed, If the coroutine is not yielded from before it is destroyed,
an error message is logged. an error message is logged.
@ -24,9 +23,7 @@ if sys.version_info < (3, 11):
@overload @overload
def iscoroutinefunction(func: Callable[..., Coroutine[Any, Any, Any]]) -> bool: 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 @overload
def iscoroutinefunction(func: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, _T]]]: ... 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 @overload
def iscoroutinefunction(func: object) -> TypeGuard[Callable[..., Coroutine[Any, Any, Any]]]: ... def iscoroutinefunction(func: object) -> TypeGuard[Callable[..., Coroutine[Any, Any, Any]]]: ...
def iscoroutine(obj: object) -> TypeIs[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.
"""

View file

@ -79,9 +79,7 @@ class _TaskFactory(Protocol):
def __call__(self, loop: AbstractEventLoop, factory: _CoroutineLike[_T], /) -> Future[_T]: ... def __call__(self, loop: AbstractEventLoop, factory: _CoroutineLike[_T], /) -> Future[_T]: ...
class Handle: class Handle:
""" """Object returned by callback registration methods."""
Object returned by callback registration methods.
"""
_cancelled: bool _cancelled: bool
_args: Sequence[Any] _args: Sequence[Any]
@ -95,9 +93,7 @@ class Handle:
def get_context(self) -> Context: ... def get_context(self) -> Context: ...
class TimerHandle(Handle): class TimerHandle(Handle):
""" """Object returned by timed callback registration methods."""
Object returned by timed callback registration methods.
"""
def __init__( def __init__(
self, self,
@ -109,8 +105,7 @@ class TimerHandle(Handle):
) -> None: ... ) -> None: ...
def __hash__(self) -> int: ... def __hash__(self) -> int: ...
def when(self) -> float: def when(self) -> float:
""" """Return a scheduled callback time.
Return a scheduled callback time.
The time is an absolute timestamp, using the same time The time is an absolute timestamp, using the same time
reference as loop.time(). reference as loop.time().
@ -123,46 +118,33 @@ class TimerHandle(Handle):
def __eq__(self, other: object) -> bool: ... def __eq__(self, other: object) -> bool: ...
class AbstractServer: class AbstractServer:
""" """Abstract server returned by create_server()."""
Abstract server returned by create_server().
"""
@abstractmethod @abstractmethod
def close(self) -> None: def close(self) -> None:
""" """Stop serving. This leaves existing connections open."""
Stop serving. This leaves existing connections open.
"""
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
@abstractmethod @abstractmethod
def close_clients(self) -> None: def close_clients(self) -> None:
""" """Close all active connections."""
Close all active connections.
"""
@abstractmethod @abstractmethod
def abort_clients(self) -> None: def abort_clients(self) -> None:
""" """Close all active connections immediately."""
Close all active connections immediately.
"""
async def __aenter__(self) -> Self: ... async def __aenter__(self) -> Self: ...
async def __aexit__(self, *exc: Unused) -> None: ... async def __aexit__(self, *exc: Unused) -> None: ...
@abstractmethod @abstractmethod
def get_loop(self) -> AbstractEventLoop: 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 @abstractmethod
def is_serving(self) -> bool: def is_serving(self) -> bool:
""" """Return True if the server is accepting connections."""
Return True if the server is accepting connections.
"""
@abstractmethod @abstractmethod
async def start_serving(self) -> None: async def start_serving(self) -> None:
""" """Start accepting connections.
Start accepting connections.
This method is idempotent, so it can be called when This method is idempotent, so it can be called when
the server is already being serving. the server is already being serving.
@ -170,42 +152,33 @@ class AbstractServer:
@abstractmethod @abstractmethod
async def serve_forever(self) -> None: 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. The server is closed when the coroutine is cancelled.
""" """
@abstractmethod @abstractmethod
async def wait_closed(self) -> None: async def wait_closed(self) -> None:
""" """Coroutine to wait until service is closed."""
Coroutine to wait until service is closed.
"""
class AbstractEventLoop: class AbstractEventLoop:
""" """Abstract event loop."""
Abstract event loop.
"""
slow_callback_duration: float slow_callback_duration: float
@abstractmethod @abstractmethod
def run_forever(self) -> None: def run_forever(self) -> None:
""" """Run the event loop until stop() is called."""
Run the event loop until stop() is called.
"""
@abstractmethod @abstractmethod
def run_until_complete(self, future: _AwaitableLike[_T]) -> _T: 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. Return the Future's result, or raise its exception.
""" """
@abstractmethod @abstractmethod
def stop(self) -> None: 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 Exactly how soon that is may depend on the implementation, but
no more I/O callbacks should be scheduled. no more I/O callbacks should be scheduled.
@ -213,20 +186,15 @@ class AbstractEventLoop:
@abstractmethod @abstractmethod
def is_running(self) -> bool: def is_running(self) -> bool:
""" """Return whether the event loop is currently running."""
Return whether the event loop is currently running.
"""
@abstractmethod @abstractmethod
def is_closed(self) -> bool: def is_closed(self) -> bool:
""" """Returns True if the event loop was closed."""
Returns True if the event loop was closed.
"""
@abstractmethod @abstractmethod
def close(self) -> None: def close(self) -> None:
""" """Close the loop.
Close the loop.
The loop should not be running. The loop should not be running.
@ -237,9 +205,7 @@ class AbstractEventLoop:
@abstractmethod @abstractmethod
async def shutdown_asyncgens(self) -> None: async def shutdown_asyncgens(self) -> None:
""" """Shutdown all active asynchronous generators."""
Shutdown all active asynchronous generators.
"""
# Methods scheduling callbacks. All these return Handles. # Methods scheduling callbacks. All these return Handles.
# "context" added in 3.9.10/3.10.2 for call_* # "context" added in 3.9.10/3.10.2 for call_*
@abstractmethod @abstractmethod
@ -400,8 +366,7 @@ class AbstractEventLoop:
ssl_shutdown_timeout: float | None = None, ssl_shutdown_timeout: float | None = None,
start_serving: bool = True, start_serving: bool = True,
) -> Server: ) -> 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 return value is a Server object which can be used to stop
the service. the service.
@ -493,8 +458,7 @@ class AbstractEventLoop:
ssl_shutdown_timeout: float | None = None, ssl_shutdown_timeout: float | None = None,
start_serving: bool = True, start_serving: bool = True,
) -> Server: ) -> 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 return value is a Server object which can be used to stop
the service. the service.
@ -584,8 +548,7 @@ class AbstractEventLoop:
ssl_handshake_timeout: float | None = None, ssl_handshake_timeout: float | None = None,
start_serving: bool = True, start_serving: bool = True,
) -> Server: ) -> 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 return value is a Server object which can be used to stop
the service. the service.
@ -669,8 +632,7 @@ class AbstractEventLoop:
ssl_handshake_timeout: float | None = None, ssl_handshake_timeout: float | None = None,
ssl_shutdown_timeout: float | None = None, ssl_shutdown_timeout: float | None = None,
) -> Transport | None: ) -> Transport | None:
""" """Upgrade a transport to TLS.
Upgrade a transport to TLS.
Return a new transport that *protocol* should start using Return a new transport that *protocol* should start using
immediately. immediately.
@ -688,8 +650,7 @@ class AbstractEventLoop:
ssl_shutdown_timeout: float | None = None, ssl_shutdown_timeout: float | None = None,
start_serving: bool = True, start_serving: bool = True,
) -> Server: ) -> 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 return value is a Server object, which can be used to stop
the service. the service.
@ -729,8 +690,7 @@ class AbstractEventLoop:
server_hostname: str | None = None, server_hostname: str | None = None,
ssl_handshake_timeout: float | None = None, ssl_handshake_timeout: float | None = None,
) -> Transport | None: ) -> Transport | None:
""" """Upgrade a transport to TLS.
Upgrade a transport to TLS.
Return a new transport that *protocol* should start using Return a new transport that *protocol* should start using
immediately. immediately.
@ -747,8 +707,7 @@ class AbstractEventLoop:
ssl_handshake_timeout: float | None = None, ssl_handshake_timeout: float | None = None,
start_serving: bool = True, start_serving: bool = True,
) -> Server: ) -> 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 return value is a Server object, which can be used to stop
the service. the service.
@ -786,8 +745,7 @@ class AbstractEventLoop:
ssl_handshake_timeout: float | None = None, ssl_handshake_timeout: float | None = None,
ssl_shutdown_timeout: float | None = None, ssl_shutdown_timeout: float | None = None,
) -> tuple[Transport, _ProtocolT]: ) -> tuple[Transport, _ProtocolT]:
""" """Handle an accepted connection.
Handle an accepted connection.
This is used by servers that accept connections outside of This is used by servers that accept connections outside of
asyncio, but use asyncio to handle connections. asyncio, but use asyncio to handle connections.
@ -804,8 +762,7 @@ class AbstractEventLoop:
ssl: _SSLContext = None, ssl: _SSLContext = None,
ssl_handshake_timeout: float | None = None, ssl_handshake_timeout: float | None = None,
) -> tuple[Transport, _ProtocolT]: ) -> tuple[Transport, _ProtocolT]:
""" """Handle an accepted connection.
Handle an accepted connection.
This is used by servers that accept connections outside of This is used by servers that accept connections outside of
asyncio, but use asyncio to handle connections. asyncio, but use asyncio to handle connections.
@ -845,8 +802,7 @@ class AbstractEventLoop:
async def sendfile( async def sendfile(
self, transport: WriteTransport, file: IO[bytes], offset: int = 0, count: int | None = None, *, fallback: bool = True self, transport: WriteTransport, file: IO[bytes], offset: int = 0, count: int | None = None, *, fallback: bool = True
) -> int: ) -> int:
""" """Send a file through a transport.
Send a file through a transport.
Return an amount of sent bytes. Return an amount of sent bytes.
""" """
@ -866,8 +822,7 @@ class AbstractEventLoop:
allow_broadcast: bool | None = None, allow_broadcast: bool | None = None,
sock: socket | None = None, sock: socket | None = None,
) -> tuple[DatagramTransport, _ProtocolT]: ) -> 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. This method will try to establish the endpoint in the background.
When successful, the coroutine returns a (transport, protocol) pair. When successful, the coroutine returns a (transport, protocol) pair.
@ -898,8 +853,7 @@ class AbstractEventLoop:
# Pipes and subprocesses. # Pipes and subprocesses.
@abstractmethod @abstractmethod
async def connect_read_pipe(self, protocol_factory: Callable[[], _ProtocolT], pipe: Any) -> tuple[ReadTransport, _ProtocolT]: 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. protocol_factory should instantiate object with Protocol interface.
pipe is a file-like object. pipe is a file-like object.
@ -911,8 +865,7 @@ class AbstractEventLoop:
async def connect_write_pipe( async def connect_write_pipe(
self, protocol_factory: Callable[[], _ProtocolT], pipe: Any self, protocol_factory: Callable[[], _ProtocolT], pipe: Any
) -> tuple[WriteTransport, _ProtocolT]: ) -> tuple[WriteTransport, _ProtocolT]:
""" """Register write pipe in event loop.
Register write pipe in event loop.
protocol_factory should instantiate object with BaseProtocol interface. protocol_factory should instantiate object with BaseProtocol interface.
Pipe is file-like object already switched to nonblocking. Pipe is file-like object already switched to nonblocking.
@ -999,19 +952,14 @@ class AbstractEventLoop:
def set_debug(self, enabled: bool) -> None: ... def set_debug(self, enabled: bool) -> None: ...
@abstractmethod @abstractmethod
async def shutdown_default_executor(self) -> None: async def shutdown_default_executor(self) -> None:
""" """Schedule the shutdown of the default executor."""
Schedule the shutdown of the default executor.
"""
class _AbstractEventLoopPolicy: class _AbstractEventLoopPolicy:
""" """Abstract policy for accessing the event loop."""
Abstract policy for accessing the event loop.
"""
@abstractmethod @abstractmethod
def get_event_loop(self) -> AbstractEventLoop: 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, Returns an event loop object implementing the AbstractEventLoop interface,
or raises an exception in case no event loop has been set for the or raises an exception in case no event loop has been set for the
@ -1022,14 +970,11 @@ class _AbstractEventLoopPolicy:
@abstractmethod @abstractmethod
def set_event_loop(self, loop: AbstractEventLoop | None) -> None: 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 @abstractmethod
def new_event_loop(self) -> AbstractEventLoop: 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 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. 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): if sys.version_info >= (3, 14):
class _BaseDefaultEventLoopPolicy(_AbstractEventLoopPolicy, metaclass=ABCMeta): 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 In this policy, each thread has its own event loop. However, we
only automatically create an event loop by default for the main 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: 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. Returns an instance of EventLoop or raises an exception.
""" """
def set_event_loop(self, loop: AbstractEventLoop | None) -> None: def set_event_loop(self, loop: AbstractEventLoop | None) -> None:
""" """Set the event loop."""
Set the event loop.
"""
def new_event_loop(self) -> AbstractEventLoop: 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 You must call set_event_loop() to make this the current event
loop. loop.
@ -1088,8 +1028,7 @@ if sys.version_info >= (3, 14):
else: else:
class BaseDefaultEventLoopPolicy(_AbstractEventLoopPolicy, metaclass=ABCMeta): 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 In this policy, each thread has its own event loop. However, we
only automatically create an event loop by default for the main only automatically create an event loop by default for the main
@ -1102,20 +1041,16 @@ else:
""" """
def get_event_loop(self) -> AbstractEventLoop: 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. Returns an instance of EventLoop or raises an exception.
""" """
def set_event_loop(self, loop: AbstractEventLoop | None) -> None: def set_event_loop(self, loop: AbstractEventLoop | None) -> None:
""" """Set the event loop."""
Set the event loop.
"""
def new_event_loop(self) -> AbstractEventLoop: 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 You must call set_event_loop() to make this the current event
loop. loop.
@ -1123,13 +1058,10 @@ else:
if sys.version_info >= (3, 14): if sys.version_info >= (3, 14):
def _get_event_loop_policy() -> _AbstractEventLoopPolicy: 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: 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. If policy is None, the default policy is restored.
""" """
@ -1141,49 +1073,36 @@ if sys.version_info >= (3, 14):
else: else:
def get_event_loop_policy() -> _AbstractEventLoopPolicy: 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: 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. If policy is None, the default policy is restored.
""" """
def set_event_loop(loop: AbstractEventLoop | None) -> None: 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: 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, 14):
if sys.version_info >= (3, 12): if sys.version_info >= (3, 12):
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
def get_child_watcher() -> AbstractChildWatcher: 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") @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
def set_child_watcher(watcher: AbstractChildWatcher) -> None: def set_child_watcher(watcher: AbstractChildWatcher) -> None:
""" """Equivalent to calling
Equivalent to calling
get_event_loop_policy().set_child_watcher(watcher). get_event_loop_policy().set_child_watcher(watcher).
""" """
else: else:
def get_child_watcher() -> AbstractChildWatcher: 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: def set_child_watcher(watcher: AbstractChildWatcher) -> None:
""" """Equivalent to calling
Equivalent to calling
get_event_loop_policy().set_child_watcher(watcher). get_event_loop_policy().set_child_watcher(watcher).
""" """

View file

@ -26,34 +26,26 @@ else:
) )
class CancelledError(BaseException): class CancelledError(BaseException):
""" """The Future or Task was cancelled."""
The Future or Task was cancelled.
"""
if sys.version_info >= (3, 11): if sys.version_info >= (3, 11):
from builtins import TimeoutError as TimeoutError from builtins import TimeoutError as TimeoutError
else: else:
class TimeoutError(Exception): class TimeoutError(Exception):
""" """The operation exceeded the given deadline."""
The operation exceeded the given deadline.
"""
class InvalidStateError(Exception): class InvalidStateError(Exception):
""" """The operation is not allowed in this state."""
The operation is not allowed in this state.
"""
class SendfileNotAvailableError(RuntimeError): 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 Raised if OS does not support sendfile syscall for given socket or
file type. file type.
""" """
class IncompleteReadError(EOFError): class IncompleteReadError(EOFError):
""" """Incomplete read error. Attributes:
Incomplete read error. Attributes:
- partial: read bytes string before the end of stream was reached - partial: read bytes string before the end of stream was reached
- expected: total number of expected bytes (or None if unknown) - 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: ... def __init__(self, partial: bytes, expected: int | None) -> None: ...
class LimitOverrunError(Exception): class LimitOverrunError(Exception):
""" """Reached the buffer limit while looking for a separator.
Reached the buffer limit while looking for a separator.
Attributes: Attributes:
- consumed: total number of to be consumed bytes. - consumed: total number of to be consumed bytes.
@ -76,6 +67,4 @@ class LimitOverrunError(Exception):
if sys.version_info >= (3, 11): if sys.version_info >= (3, 11):
class BrokenBarrierError(RuntimeError): class BrokenBarrierError(RuntimeError):
""" """Barrier is broken by barrier.abort() call."""
Barrier is broken by barrier.abort() call.
"""

View file

@ -19,8 +19,7 @@ def _get_function_source(func: object) -> tuple[str, int] | None: ...
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
def _format_callback_source(func: object, args: Iterable[Any], *, debug: bool = False) -> str: ... 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: 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'). Special case for a single parameter: ('hello',) is formatted as ('hello').
@ -36,8 +35,7 @@ if sys.version_info >= (3, 13):
else: else:
def _format_callback_source(func: object, args: Iterable[Any]) -> str: ... def _format_callback_source(func: object, args: Iterable[Any]) -> str: ...
def _format_args_and_kwargs(args: Iterable[Any], kwargs: dict[str, 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'). 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 _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: 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. necessary work for asyncio debug mode.
""" """

View file

@ -24,8 +24,7 @@ _T = TypeVar("_T")
# but it leads to circular import error in pytype tool. # but it leads to circular import error in pytype tool.
# That's why the import order is reversed. # That's why the import order is reversed.
def isfuture(obj: object) -> TypeIs[Future[Any]]: 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 This returns True when obj is a Future instance or is advertising
itself as duck-type compatible by setting _asyncio_future_blocking. 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]: def wrap_future(future: _ConcurrentFuture[_T] | Future[_T], *, loop: AbstractEventLoop | None = None) -> Future[_T]:
""" """Wrap concurrent.futures.Future object."""
Wrap concurrent.futures.Future object.
"""

View file

@ -12,17 +12,13 @@ __all__ = ("capture_call_graph", "format_call_graph", "print_call_graph", "Frame
@dataclass(frozen=True) @dataclass(frozen=True)
class FrameCallGraphEntry: class FrameCallGraphEntry:
""" """FrameCallGraphEntry(frame: frame)"""
FrameCallGraphEntry(frame: frame)
"""
frame: FrameType frame: FrameType
@dataclass(frozen=True) @dataclass(frozen=True)
class FutureCallGraph: 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] future: Future[Any]
call_stack: tuple[FrameCallGraphEntry, ...] call_stack: tuple[FrameCallGraphEntry, ...]
@ -30,8 +26,7 @@ class FutureCallGraph:
@overload @overload
def capture_call_graph(future: None = None, /, *, depth: int = 1, limit: int | None = None) -> FutureCallGraph | None: 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: 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 @overload
def capture_call_graph(future: Future[Any], /, *, depth: int = 1, limit: int | None = None) -> FutureCallGraph | None: ... 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: 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. 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( def print_call_graph(
future: Future[Any] | None = None, /, *, file: SupportsWrite[str] | None = None, depth: int = 1, limit: int | None = None future: Future[Any] | None = None, /, *, file: SupportsWrite[str] | None = None, depth: int = 1, limit: int | None = 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.
"""

View file

@ -34,8 +34,7 @@ class _ContextManagerMixin:
) -> None: ... ) -> None: ...
class Lock(_ContextManagerMixin, _LoopBoundMixin): class Lock(_ContextManagerMixin, _LoopBoundMixin):
""" """Primitive lock objects.
Primitive lock objects.
A primitive lock is a synchronization primitive that is not owned A primitive lock is a synchronization primitive that is not owned
by a particular task when locked. A primitive lock is in one 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 __init__(self, *, loop: AbstractEventLoop | None = None) -> None: ...
def locked(self) -> bool: def locked(self) -> bool:
""" """Return True if lock is acquired."""
Return True if lock is acquired.
"""
async def acquire(self) -> Literal[True]: async def acquire(self) -> Literal[True]:
""" """Acquire a lock.
Acquire a lock.
This method blocks until the lock is unlocked, then sets it to This method blocks until the lock is unlocked, then sets it to
locked and returns True. locked and returns True.
""" """
def release(self) -> None: def release(self) -> None:
""" """Release a lock.
Release a lock.
When the lock is locked, reset it to unlocked, and return. When the lock is locked, reset it to unlocked, and return.
If any other tasks are blocked waiting for the lock to become If any other tasks are blocked waiting for the lock to become
@ -118,8 +113,7 @@ class Lock(_ContextManagerMixin, _LoopBoundMixin):
""" """
class Event(_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 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. 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 __init__(self, *, loop: AbstractEventLoop | None = None) -> None: ...
def is_set(self) -> bool: 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: 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 become true are awakened. Tasks that call wait() once the flag is
true will not block at all. true will not block at all.
""" """
def clear(self) -> None: 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 wait() will block until set() is called to set the internal flag
to true again. to true again.
""" """
async def wait(self) -> Literal[True]: 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 If the internal flag is true on entry, return True
immediately. Otherwise, block until another task calls immediately. Otherwise, block until another task calls
@ -162,8 +151,7 @@ class Event(_LoopBoundMixin):
""" """
class Condition(_ContextManagerMixin, _LoopBoundMixin): class Condition(_ContextManagerMixin, _LoopBoundMixin):
""" """Asynchronous equivalent to threading.Condition.
Asynchronous equivalent to threading.Condition.
This class implements condition variable objects. A condition variable This class implements condition variable objects. A condition variable
allows one or more tasks to wait until they are notified by another 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]: ... async def acquire(self) -> Literal[True]: ...
def release(self) -> None: ... def release(self) -> None: ...
async def wait(self) -> Literal[True]: async def wait(self) -> Literal[True]:
""" """Wait until notified.
Wait until notified.
If the calling task has not acquired the lock when this If the calling task has not acquired the lock when this
method is called, a RuntimeError is raised. method is called, a RuntimeError is raised.
@ -199,8 +186,7 @@ class Condition(_ContextManagerMixin, _LoopBoundMixin):
""" """
async def wait_for(self, predicate: Callable[[], _T]) -> _T: 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 The predicate should be a callable whose result will be
interpreted as a boolean value. The method will repeatedly interpreted as a boolean value. The method will repeatedly
@ -209,8 +195,7 @@ class Condition(_ContextManagerMixin, _LoopBoundMixin):
""" """
def notify(self, n: int = 1) -> None: 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 If the calling task has not acquired the lock when this method
is called, a RuntimeError is raised. is called, a RuntimeError is raised.
@ -223,16 +208,14 @@ class Condition(_ContextManagerMixin, _LoopBoundMixin):
""" """
def notify_all(self) -> None: 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 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, calling task has not acquired the lock when this method is called,
a RuntimeError is raised. a RuntimeError is raised.
""" """
class Semaphore(_ContextManagerMixin, _LoopBoundMixin): class Semaphore(_ContextManagerMixin, _LoopBoundMixin):
""" """A Semaphore implementation.
A Semaphore implementation.
A semaphore manages an internal counter which is decremented by each A semaphore manages an internal counter which is decremented by each
acquire() call and incremented by each release() call. The counter 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 __init__(self, value: int = 1, *, loop: AbstractEventLoop | None = None) -> None: ...
def locked(self) -> bool: 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]: async def acquire(self) -> Literal[True]:
""" """Acquire a semaphore.
Acquire a semaphore.
If the internal counter is larger than zero on entry, If the internal counter is larger than zero on entry,
decrement it by one and return True immediately. If it is decrement it by one and return True immediately. If it is
@ -270,21 +250,17 @@ class Semaphore(_ContextManagerMixin, _LoopBoundMixin):
""" """
def release(self) -> None: 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 When it was zero on entry and another task is waiting for it to
become larger than zero again, wake up that task. become larger than zero again, wake up that task.
""" """
def _wake_up_next(self) -> None: 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): class BoundedSemaphore(Semaphore):
""" """A bounded semaphore implementation.
A bounded semaphore implementation.
This raises ValueError in release() if it would increase the value This raises ValueError in release() if it would increase the value
above the initial value. above the initial value.
@ -298,8 +274,7 @@ if sys.version_info >= (3, 11):
BROKEN = "broken" BROKEN = "broken"
class Barrier(_LoopBoundMixin): class Barrier(_LoopBoundMixin):
""" """Asyncio equivalent to threading.Barrier
Asyncio equivalent to threading.Barrier
Implements a Barrier primitive. Implements a Barrier primitive.
Useful for synchronizing a fixed number of tasks at known synchronization 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: 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 __aenter__(self) -> Self: ...
async def __aexit__(self, *args: Unused) -> None: ... async def __aexit__(self, *args: Unused) -> None: ...
async def wait(self) -> int: 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 When the specified number of tasks have started waiting, they are all
simultaneously awoken. simultaneously awoken.
@ -324,16 +296,14 @@ if sys.version_info >= (3, 11):
""" """
async def abort(self) -> None: 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 Useful in case of error. Any currently waiting tasks and tasks
attempting to 'wait()' will have BrokenBarrierError raised. attempting to 'wait()' will have BrokenBarrierError raised.
""" """
async def reset(self) -> None: 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 Any tasks currently waiting will get the BrokenBarrier exception
raised. raised.
@ -341,18 +311,12 @@ if sys.version_info >= (3, 11):
@property @property
def parties(self) -> int: 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 @property
def n_waiting(self) -> int: 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 @property
def broken(self) -> bool: def broken(self) -> bool:
""" """Return True if the barrier is in a broken state."""
Return True if the barrier is in a broken state.
"""

View file

@ -15,9 +15,7 @@ from . import base_events, constants, events, futures, streams, transports
__all__ = ("BaseProactorEventLoop",) __all__ = ("BaseProactorEventLoop",)
class _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTransport): class _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTransport):
""" """Base class for pipe and socket transports."""
Base class for pipe and socket transports.
"""
def __init__( def __init__(
self, self,
@ -31,9 +29,7 @@ class _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTr
def __del__(self) -> None: ... def __del__(self) -> None: ...
class _ProactorReadPipeTransport(_ProactorBasePipeTransport, transports.ReadTransport): class _ProactorReadPipeTransport(_ProactorBasePipeTransport, transports.ReadTransport):
""" """Transport for read pipes."""
Transport for read pipes.
"""
if sys.version_info >= (3, 10): if sys.version_info >= (3, 10):
def __init__( def __init__(
@ -58,21 +54,15 @@ class _ProactorReadPipeTransport(_ProactorBasePipeTransport, transports.ReadTran
) -> None: ... ) -> None: ...
class _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport, transports.WriteTransport): class _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport, transports.WriteTransport):
""" """Transport for write pipes."""
Transport for write pipes.
"""
class _ProactorWritePipeTransport(_ProactorBaseWritePipeTransport): ... class _ProactorWritePipeTransport(_ProactorBaseWritePipeTransport): ...
class _ProactorDuplexPipeTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport): class _ProactorDuplexPipeTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport):
""" """Transport for duplex pipes."""
Transport for duplex pipes.
"""
class _ProactorSocketTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport): class _ProactorSocketTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport):
""" """Transport for connected sockets."""
Transport for connected sockets.
"""
_sendfile_compatible: ClassVar[constants._SendfileMode] _sendfile_compatible: ClassVar[constants._SendfileMode]
def __init__( def __init__(

View file

@ -10,8 +10,7 @@ from typing import Any
__all__ = ("BaseProtocol", "Protocol", "DatagramProtocol", "SubprocessProtocol", "BufferedProtocol") __all__ = ("BaseProtocol", "Protocol", "DatagramProtocol", "SubprocessProtocol", "BufferedProtocol")
class BaseProtocol: class BaseProtocol:
""" """Common base class for protocol interfaces.
Common base class for protocol interfaces.
Usually user implements protocols that derived from BaseProtocol Usually user implements protocols that derived from BaseProtocol
like Protocol or ProcessProtocol. like Protocol or ProcessProtocol.
@ -21,8 +20,7 @@ class BaseProtocol:
""" """
def connection_made(self, transport: transports.BaseTransport) -> None: 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. The argument is the transport representing the pipe connection.
To receive data, wait for data_received() calls. To receive data, wait for data_received() calls.
@ -30,8 +28,7 @@ class BaseProtocol:
""" """
def connection_lost(self, exc: Exception | None) -> None: 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 The argument is an exception object or None (the latter
meaning a regular EOF is received or the connection was meaning a regular EOF is received or the connection was
@ -39,8 +36,7 @@ class BaseProtocol:
""" """
def pause_writing(self) -> None: 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 Pause and resume calls are paired -- pause_writing() is called
once when the buffer goes strictly over the high-water mark once when the buffer goes strictly over the high-water mark
@ -62,15 +58,13 @@ class BaseProtocol:
""" """
def resume_writing(self) -> None: 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. See pause_writing() for details.
""" """
class Protocol(BaseProtocol): class Protocol(BaseProtocol):
""" """Interface for stream protocol.
Interface for stream protocol.
The user should implement this interface. They can inherit from The user should implement this interface. They can inherit from
this class but don't need to. The implementations here do 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: 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. The argument is a bytes object.
""" """
def eof_received(self) -> bool | None: 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 If this returns a false value (including None), the transport
will close itself. If it returns a true value, closing the will close itself. If it returns a true value, closing the
@ -112,8 +104,7 @@ class Protocol(BaseProtocol):
""" """
class BufferedProtocol(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`, Event methods, such as `create_server` and `create_connection`,
accept factories that return protocols that implement this interface. accept factories that return protocols that implement this interface.
@ -137,8 +128,7 @@ class BufferedProtocol(BaseProtocol):
""" """
def get_buffer(self, sizehint: int) -> ReadableBuffer: 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 *sizehint* is a recommended minimal size for the returned
buffer. When set to -1, the buffer size can be arbitrary. 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: 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 *nbytes* is the total number of bytes that were written to
the buffer. the buffer.
""" """
def eof_received(self) -> bool | None: 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 If this returns a false value (including None), the transport
will close itself. If it returns a true value, closing the will close itself. If it returns a true value, closing the
@ -166,13 +154,10 @@ class BufferedProtocol(BaseProtocol):
""" """
class DatagramProtocol(BaseProtocol): class DatagramProtocol(BaseProtocol):
""" """Interface for datagram protocol."""
Interface for datagram protocol.
"""
def connection_made(self, transport: transports.DatagramTransport) -> None: # type: ignore[override] 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. The argument is the transport representing the pipe connection.
To receive data, wait for data_received() calls. 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. # 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 # See https://github.com/python/typing/issues/566
def datagram_received(self, data: bytes, addr: tuple[str | Any, int]) -> None: 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: 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.) (Other than BlockingIOError or InterruptedError.)
""" """
class SubprocessProtocol(BaseProtocol): 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: 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. fd is int file descriptor.
data is bytes object. data is bytes object.
""" """
def pipe_connection_lost(self, fd: int, exc: Exception | None) -> None: 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. closed.
fd is the int file descriptor that was closed. fd is the int file descriptor that was closed.
""" """
def process_exited(self) -> None: def process_exited(self) -> None:
""" """Called when subprocess has exited."""
Called when subprocess has exited.
"""

View file

@ -9,14 +9,10 @@ else:
_LoopBoundMixin = object _LoopBoundMixin = object
class QueueEmpty(Exception): 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): 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 # Keep asyncio.__all__ updated with any changes to __all__ here
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
@ -29,15 +25,12 @@ _T = TypeVar("_T")
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
class QueueShutDown(Exception): 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. # If Generic[_T] is last and _LoopBoundMixin is object, pyright is unhappy.
# We can remove the noqa pragma when dropping 3.9 support. # We can remove the noqa pragma when dropping 3.9 support.
class Queue(Generic[_T], _LoopBoundMixin): # noqa: Y059 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 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 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 _put(self, item: _T) -> None: ...
def _format(self) -> str: ... def _format(self) -> str: ...
def qsize(self) -> int: def qsize(self) -> int:
""" """Number of items in the queue."""
Number of items in the queue.
"""
@property @property
def maxsize(self) -> int: def maxsize(self) -> int:
""" """Number of items allowed in the queue."""
Number of items allowed in the queue.
"""
def empty(self) -> bool: 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: 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), Note: if the Queue was initialized with maxsize=0 (the default),
then full() is never True. then full() is never True.
""" """
async def put(self, item: _T) -> None: 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 Put an item into the queue. If the queue is full, wait until a free
slot is available before adding item. slot is available before adding item.
@ -92,8 +77,7 @@ class Queue(Generic[_T], _LoopBoundMixin): # noqa: Y059
""" """
def put_nowait(self, item: _T) -> None: 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. 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: 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. 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: 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. 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: 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 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 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: 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, Used by queue consumers. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing 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: 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,). E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
""" """
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
def shutdown(self, immediate: bool = False) -> None: 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 By default, gets will only raise once the queue is empty. Set
'immediate' to True to make gets raise immediately instead. 'immediate' to True to make gets raise immediately instead.
@ -169,13 +147,10 @@ class Queue(Generic[_T], _LoopBoundMixin): # noqa: Y059
""" """
class PriorityQueue(Queue[_T]): 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). Entries are typically tuples of the form: (priority number, data).
""" """
class LifoQueue(Queue[_T]): 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.
"""

View file

@ -17,8 +17,7 @@ _T = TypeVar("_T")
if sys.version_info >= (3, 11): if sys.version_info >= (3, 11):
@final @final
class Runner: 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, The context manager always creates a new event loop,
allows to run async functions inside it, allows to run async functions inside it,
@ -46,26 +45,19 @@ if sys.version_info >= (3, 11):
def __enter__(self) -> Self: ... def __enter__(self) -> Self: ...
def __exit__(self, exc_type: Unused, exc_val: Unused, exc_tb: Unused) -> None: ... def __exit__(self, exc_type: Unused, exc_val: Unused, exc_tb: Unused) -> None: ...
def close(self) -> None: def close(self) -> None:
""" """Shutdown and close event loop."""
Shutdown and close event loop.
"""
def get_loop(self) -> AbstractEventLoop: 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: 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): if sys.version_info >= (3, 12):
def run( def run(
main: Coroutine[Any, Any, _T], *, debug: bool | None = ..., loop_factory: Callable[[], AbstractEventLoop] | None = ... main: Coroutine[Any, Any, _T], *, debug: bool | None = ..., loop_factory: Callable[[], AbstractEventLoop] | None = ...
) -> _T: ) -> _T:
""" """Execute the coroutine and return the result.
Execute the coroutine and return the result.
This function runs the passed coroutine, taking care of This function runs the passed coroutine, taking care of
managing the asyncio event loop, finalizing asynchronous managing the asyncio event loop, finalizing asynchronous
@ -96,8 +88,7 @@ if sys.version_info >= (3, 12):
else: else:
def run(main: Coroutine[Any, Any, _T], *, debug: bool | None = None) -> _T: 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 This function runs the passed coroutine, taking care of
managing the asyncio event loop and finalizing asynchronous managing the asyncio event loop and finalizing asynchronous

View file

@ -13,16 +13,14 @@ from . import base_events
__all__ = ("BaseSelectorEventLoop",) __all__ = ("BaseSelectorEventLoop",)
class BaseSelectorEventLoop(base_events.BaseEventLoop): class BaseSelectorEventLoop(base_events.BaseEventLoop):
""" """Selector event loop.
Selector event loop.
See events.EventLoop for API specification. See events.EventLoop for API specification.
""" """
def __init__(self, selector: selectors.BaseSelector | None = None) -> None: ... def __init__(self, selector: selectors.BaseSelector | None = None) -> None: ...
async def sock_recv(self, sock: socket, n: int) -> bytes: 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 return value is a bytes object representing the data received.
The maximum amount of data to be received at once is specified by The maximum amount of data to be received at once is specified by

View file

@ -36,8 +36,7 @@ else:
if sys.version_info < (3, 11): if sys.version_info < (3, 11):
class _SSLPipe: class _SSLPipe:
""" """An SSL "Pipe".
An SSL "Pipe".
An SSL pipe allows you to communicate with an SSL/TLS protocol instance 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 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 _handshake_cb: Callable[[BaseException | None], None] | None
_shutdown_cb: Callable[[], None] | None _shutdown_cb: Callable[[], None] | None
def __init__(self, context: ssl.SSLContext, server_side: bool, server_hostname: str | None = 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 The *server_side* argument indicates whether this is a server side or
client side transport. client side transport.
@ -80,36 +78,30 @@ if sys.version_info < (3, 11):
@property @property
def context(self) -> ssl.SSLContext: def context(self) -> ssl.SSLContext:
""" """The SSL context passed to the constructor."""
The SSL context passed to the constructor.
"""
@property @property
def ssl_object(self) -> ssl.SSLObject | None: 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. Return None if the pipe is not wrapped.
""" """
@property @property
def need_ssldata(self) -> bool: 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. that is currently in progress.
""" """
@property @property
def wrapped(self) -> bool: def wrapped(self) -> bool:
""" """Whether a security layer is currently in effect.
Whether a security layer is currently in effect.
Return False during handshake. Return False during handshake.
""" """
def do_handshake(self, callback: Callable[[BaseException | None], object] | None = None) -> list[bytes]: 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 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]: 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 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: 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 This method will raise an SSL_ERROR_EOF exception if the EOF is
unexpected. unexpected.
""" """
def feed_ssldata(self, data: bytes, only_handshake: bool = False) -> tuple[list[bytes], list[bytes]]: 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 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 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]: 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 Return an (ssldata, offset) tuple. The ssldata element is a list of
buffers containing record level data that needs to be sent to the buffers containing record level data that needs to be sent to the
@ -182,36 +170,29 @@ class _SSLProtocolTransport(transports._FlowControlMixin, transports.Transport):
_closed: bool _closed: bool
def __init__(self, loop: events.AbstractEventLoop, ssl_protocol: SSLProtocol) -> None: ... def __init__(self, loop: events.AbstractEventLoop, ssl_protocol: SSLProtocol) -> None: ...
def get_extra_info(self, name: str, default: Any | None = None) -> dict[str, Any]: def get_extra_info(self, name: str, default: Any | None = None) -> dict[str, Any]:
""" """Get optional transport information."""
Get optional transport information.
"""
@property @property
def _protocol_paused(self) -> bool: ... def _protocol_paused(self) -> bool: ...
def write(self, data: bytes | bytearray | memoryview[Any]) -> None: # any memoryview format or shape 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 This does not block; it buffers the data and arranges for it
to be sent out asynchronously. to be sent out asynchronously.
""" """
def can_write_eof(self) -> Literal[False]: 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): if sys.version_info >= (3, 11):
def get_write_buffer_limits(self) -> tuple[int, int]: 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 Return a tuple (low, high) where low and high are
positive number of bytes. positive number of bytes.
""" """
def get_read_buffer_limits(self) -> tuple[int, int]: ... def get_read_buffer_limits(self) -> tuple[int, int]: ...
def set_read_buffer_limits(self, high: int | None = None, low: int | None = None) -> None: 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 These two values control when to call the upstream transport's
pause_reading() and resume_reading() methods. If specified, 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: 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: ... def __del__(self) -> None: ...
@ -243,8 +222,7 @@ else:
_SSLProtocolBase: TypeAlias = protocols.Protocol _SSLProtocolBase: TypeAlias = protocols.Protocol
class SSLProtocol(_SSLProtocolBase): class SSLProtocol(_SSLProtocolBase):
""" """SSL protocol.
SSL protocol.
Implementation of SSL on top of a socket using incoming and outgoing Implementation of SSL on top of a socket using incoming and outgoing
buffers which are ssl.MemoryBIO objects. buffers which are ssl.MemoryBIO objects.
@ -302,8 +280,7 @@ class SSLProtocol(_SSLProtocolBase):
def _set_app_protocol(self, app_protocol: protocols.BaseProtocol) -> None: ... def _set_app_protocol(self, app_protocol: protocols.BaseProtocol) -> None: ...
def _wakeup_waiter(self, exc: BaseException | None = None) -> None: ... def _wakeup_waiter(self, exc: BaseException | None = None) -> None: ...
def connection_lost(self, exc: BaseException | 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 The argument is an exception object or None (the latter
meaning a regular EOF is received or the connection was meaning a regular EOF is received or the connection was
@ -311,8 +288,7 @@ class SSLProtocol(_SSLProtocolBase):
""" """
def eof_received(self) -> None: 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. is half-closed.
If this returns a false value (including None), the transport If this returns a false value (including None), the transport

View file

@ -12,8 +12,7 @@ __all__ = ("staggered_race",)
async def staggered_race( async def staggered_race(
coro_fns: Iterable[Callable[[], Awaitable[Any]]], delay: float | None, *, loop: events.AbstractEventLoop | None = None coro_fns: Iterable[Callable[[], Awaitable[Any]]], delay: float | None, *, loop: events.AbstractEventLoop | None = None
) -> tuple[Any, int | None, list[Exception | 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 This method takes an iterable of coroutine functions. The first one is
started immediately. From then on, whenever the immediately preceding one started immediately. From then on, whenever the immediately preceding one

View file

@ -36,8 +36,7 @@ if sys.version_info >= (3, 10):
ssl_handshake_timeout: float | None = ..., ssl_handshake_timeout: float | None = ...,
**kwds: Any, **kwds: Any,
) -> tuple[StreamReader, StreamWriter]: ) -> 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 The reader returned is a StreamReader instance; the writer is a
StreamWriter instance. StreamWriter instance.
@ -64,8 +63,7 @@ if sys.version_info >= (3, 10):
ssl_handshake_timeout: float | None = ..., ssl_handshake_timeout: float | None = ...,
**kwds: Any, **kwds: Any,
) -> Server: ) -> 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: The first parameter, `client_connected_cb`, takes two parameters:
client_reader, client_writer. client_reader is a StreamReader client_reader, client_writer. client_reader is a StreamReader
@ -96,8 +94,7 @@ else:
ssl_handshake_timeout: float | None = ..., ssl_handshake_timeout: float | None = ...,
**kwds: Any, **kwds: Any,
) -> tuple[StreamReader, StreamWriter]: ) -> 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 The reader returned is a StreamReader instance; the writer is a
StreamWriter instance. StreamWriter instance.
@ -125,8 +122,7 @@ else:
ssl_handshake_timeout: float | None = ..., ssl_handshake_timeout: float | None = ...,
**kwds: Any, **kwds: Any,
) -> Server: ) -> 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: The first parameter, `client_connected_cb`, takes two parameters:
client_reader, client_writer. client_reader is a StreamReader client_reader, client_writer. client_reader is a StreamReader
@ -153,23 +149,17 @@ if sys.platform != "win32":
async def open_unix_connection( async def open_unix_connection(
path: StrPath | None = None, *, limit: int = 65536, **kwds: Any path: StrPath | None = None, *, limit: int = 65536, **kwds: Any
) -> tuple[StreamReader, StreamWriter]: ) -> 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( async def start_unix_server(
client_connected_cb: _ClientConnectedCallback, path: StrPath | None = None, *, limit: int = 65536, **kwds: Any client_connected_cb: _ClientConnectedCallback, path: StrPath | None = None, *, limit: int = 65536, **kwds: Any
) -> Server: ) -> Server:
""" """Similar to `start_server` but works with UNIX Domain Sockets."""
Similar to `start_server` but works with UNIX Domain Sockets.
"""
else: else:
async def open_unix_connection( async def open_unix_connection(
path: StrPath | None = None, *, loop: events.AbstractEventLoop | None = None, limit: int = 65536, **kwds: Any path: StrPath | None = None, *, loop: events.AbstractEventLoop | None = None, limit: int = 65536, **kwds: Any
) -> tuple[StreamReader, StreamWriter]: ) -> 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( async def start_unix_server(
client_connected_cb: _ClientConnectedCallback, client_connected_cb: _ClientConnectedCallback,
@ -179,13 +169,10 @@ if sys.platform != "win32":
limit: int = 65536, limit: int = 65536,
**kwds: Any, **kwds: Any,
) -> Server: ) -> 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): 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(), This implements the protocol methods pause_writing(),
resume_writing() and connection_lost(). If the subclass overrides 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: ... def __init__(self, loop: events.AbstractEventLoop | None = None) -> None: ...
class StreamReaderProtocol(FlowControlMixin, protocols.Protocol): 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 (This is a helper class instead of making StreamReader itself a
Protocol subclass, because the StreamReader has other potential Protocol subclass, because the StreamReader has other potential
@ -215,8 +201,7 @@ class StreamReaderProtocol(FlowControlMixin, protocols.Protocol):
def __del__(self) -> None: ... def __del__(self) -> None: ...
class StreamWriter: class StreamWriter:
""" """Wraps a Transport.
Wraps a Transport.
This exposes write(), writelines(), [can_]write_eof(), This exposes write(), writelines(), [can_]write_eof(),
get_extra_info() and close(). It adds drain() which returns an get_extra_info() and close(). It adds drain() which returns an
@ -243,8 +228,7 @@ class StreamWriter:
async def wait_closed(self) -> None: ... async def wait_closed(self) -> None: ...
def get_extra_info(self, name: str, default: Any = None) -> Any: ... def get_extra_info(self, name: str, default: Any = None) -> Any: ...
async def drain(self) -> None: async def drain(self) -> None:
""" """Flush the write buffer.
Flush the write buffer.
The intended use is to write The intended use is to write
@ -260,16 +244,12 @@ class StreamWriter:
ssl_handshake_timeout: float | None = None, ssl_handshake_timeout: float | None = None,
ssl_shutdown_timeout: float | None = None, ssl_shutdown_timeout: float | None = 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): elif sys.version_info >= (3, 11):
async def start_tls( async def start_tls(
self, sslcontext: ssl.SSLContext, *, server_hostname: str | None = None, ssl_handshake_timeout: float | None = None self, sslcontext: ssl.SSLContext, *, server_hostname: str | None = None, ssl_handshake_timeout: float | None = 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): if sys.version_info >= (3, 13):
def __del__(self, warnings: ModuleType = ...) -> None: ... def __del__(self, warnings: ModuleType = ...) -> None: ...
elif sys.version_info >= (3, 11): elif sys.version_info >= (3, 11):
@ -282,14 +262,11 @@ class StreamReader:
def set_transport(self, transport: transports.BaseTransport) -> None: ... def set_transport(self, transport: transports.BaseTransport) -> None: ...
def feed_eof(self) -> None: ... def feed_eof(self) -> None: ...
def at_eof(self) -> bool: 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: ... def feed_data(self, data: Iterable[SupportsIndex]) -> None: ...
async def readline(self) -> bytes: 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. ') is found.
On success, return chunk that ends with newline. If only partial On success, return chunk that ends with newline. If only partial
@ -307,8 +284,7 @@ class StreamReader:
""" """
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
async def readuntil(self, separator: _ReaduntilBuffer | tuple[_ReaduntilBuffer, ...] = b"\n") -> bytes: 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 On success, the data and separator will be removed from the
internal buffer (consumed). Returned data will include the internal buffer (consumed). Returned data will include the
@ -335,8 +311,7 @@ class StreamReader:
""" """
else: else:
async def readuntil(self, separator: _ReaduntilBuffer = b"\n") -> bytes: 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 On success, the data and separator will be removed from the
internal buffer (consumed). Returned data will include the internal buffer (consumed). Returned data will include the
@ -363,8 +338,7 @@ class StreamReader:
""" """
async def read(self, n: int = -1) -> bytes: 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, If `n` is not provided or set to -1,
read until EOF, then return all read bytes. read until EOF, then return all read bytes.
@ -386,8 +360,7 @@ class StreamReader:
""" """
async def readexactly(self, n: int) -> bytes: 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 Raise an IncompleteReadError if EOF is reached before `n` bytes can be
read. The IncompleteReadError.partial attribute of the exception will read. The IncompleteReadError.partial attribute of the exception will

View file

@ -13,9 +13,7 @@ STDOUT: int
DEVNULL: int DEVNULL: int
class SubprocessStreamProtocol(streams.FlowControlMixin, protocols.SubprocessProtocol): class SubprocessStreamProtocol(streams.FlowControlMixin, protocols.SubprocessProtocol):
""" """Like StreamReaderProtocol, but for a subprocess."""
Like StreamReaderProtocol, but for a subprocess.
"""
stdin: streams.StreamWriter | None stdin: streams.StreamWriter | None
stdout: streams.StreamReader | None stdout: streams.StreamReader | None
@ -34,9 +32,7 @@ class Process:
@property @property
def returncode(self) -> int | None: ... def returncode(self) -> int | None: ...
async def wait(self) -> int: 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 send_signal(self, signal: int) -> None: ...
def terminate(self) -> None: ... def terminate(self) -> None: ...

View file

@ -17,8 +17,7 @@ else:
_T = TypeVar("_T") _T = TypeVar("_T")
class TaskGroup: class TaskGroup:
""" """Asynchronous context manager for managing groups of tasks.
Asynchronous context manager for managing groups of tasks.
Example use: Example use:
@ -40,8 +39,7 @@ class TaskGroup:
async def __aenter__(self) -> Self: ... async def __aenter__(self) -> Self: ...
async def __aexit__(self, et: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... 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]: 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`. Similar to `asyncio.create_task`.
""" """

View file

@ -94,8 +94,7 @@ if sys.version_info >= (3, 13):
class _SyncAndAsyncIterator(Iterator[_T_co], AsyncIterator[_T_co], Protocol[_T_co]): ... 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]]: 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 Run the supplied awaitables concurrently. The returned object can be
iterated to obtain the results of the awaitables as they finish. 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): elif sys.version_info >= (3, 10):
def as_completed(fs: Iterable[_FutureLike[_T]], *, timeout: float | None = None) -> Iterator[Future[_T]]: 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 When waiting for the yielded coroutines you'll get the results (or
exceptions!) of the original Futures (or coroutines), in the order exceptions!) of the original Futures (or coroutines), in the order
@ -166,8 +164,7 @@ else:
def as_completed( def as_completed(
fs: Iterable[_FutureLike[_T]], *, loop: AbstractEventLoop | None = None, timeout: float | None = None fs: Iterable[_FutureLike[_T]], *, loop: AbstractEventLoop | None = None, timeout: float | None = None
) -> Iterator[Future[_T]]: ) -> 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 When waiting for the yielded coroutines you'll get the results (or
exceptions!) of the original Futures (or coroutines), in the order exceptions!) of the original Futures (or coroutines), in the order
@ -187,8 +184,7 @@ else:
@overload @overload
def ensure_future(coro_or_future: _FT, *, loop: AbstractEventLoop | None = None) -> _FT: # type: ignore[overload-overlap] 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. 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): if sys.version_info >= (3, 10):
@overload @overload
def gather(coro_or_future1: _FutureLike[_T1], /, *, return_exceptions: Literal[False] = False) -> Future[tuple[_T1]]: # type: ignore[overload-overlap] 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 Coroutines will be wrapped in a future and scheduled in the event
loop. They will not necessarily be scheduled in the same order as loop. They will not necessarily be scheduled in the same order as
@ -351,8 +346,7 @@ else:
def gather( # type: ignore[overload-overlap] def gather( # type: ignore[overload-overlap]
coro_or_future1: _FutureLike[_T1], /, *, loop: AbstractEventLoop | None = None, return_exceptions: Literal[False] = False coro_or_future1: _FutureLike[_T1], /, *, loop: AbstractEventLoop | None = None, return_exceptions: Literal[False] = False
) -> Future[tuple[_T1]]: ) -> 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 Coroutines will be wrapped in a future and scheduled in the event
loop. They will not necessarily be scheduled in the same order as 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. # 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]: 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. Return a concurrent.futures.Future to access the result.
""" """
if sys.version_info >= (3, 10): if sys.version_info >= (3, 10):
def shield(arg: _FutureLike[_T]) -> Future[_T]: 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 The statement
@ -548,15 +540,12 @@ if sys.version_info >= (3, 10):
@overload @overload
async def sleep(delay: float) -> None: 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 @overload
async def sleep(delay: float, result: _T) -> _T: ... async def sleep(delay: float, result: _T) -> _T: ...
async def wait_for(fut: _FutureLike[_T], timeout: float | None) -> _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. Coroutine will be wrapped in Task.
@ -574,8 +563,7 @@ if sys.version_info >= (3, 10):
else: else:
def shield(arg: _FutureLike[_T], *, loop: AbstractEventLoop | None = None) -> Future[_T]: 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 The statement
@ -603,15 +591,12 @@ else:
@overload @overload
async def sleep(delay: float, *, loop: AbstractEventLoop | None = None) -> None: 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 @overload
async def sleep(delay: float, result: _T, *, loop: AbstractEventLoop | None = None) -> _T: ... 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: 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. Coroutine will be wrapped in Task.
@ -629,8 +614,7 @@ if sys.version_info >= (3, 11):
async def wait( async def wait(
fs: Iterable[_FT], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED" fs: Iterable[_FT], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED"
) -> tuple[set[_FT], set[_FT]]: ) -> 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. The fs iterable must not be empty.
@ -654,8 +638,7 @@ elif sys.version_info >= (3, 10):
async def wait( # type: ignore[overload-overlap] async def wait( # type: ignore[overload-overlap]
fs: Iterable[_FT], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED" fs: Iterable[_FT], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED"
) -> tuple[set[_FT], set[_FT]]: ) -> 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. The fs iterable must not be empty.
@ -685,8 +668,7 @@ else:
timeout: float | None = None, timeout: float | None = None,
return_when: str = "ALL_COMPLETED", return_when: str = "ALL_COMPLETED",
) -> tuple[set[_FT], set[_FT]]: ) -> 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. The fs iterable must not be empty.
@ -717,22 +699,18 @@ else:
_TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Coroutine[Any, Any, _T_co] _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Coroutine[Any, Any, _T_co]
def all_tasks(loop: AbstractEventLoop | None = None) -> set[Task[Any]]: 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): if sys.version_info >= (3, 11):
def create_task(coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None) -> Task[_T]: 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. Return a Task object.
""" """
else: else:
def create_task(coro: _CoroutineLike[_T], *, name: str | None = None) -> Task[_T]: 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. Return a Task object.
""" """
@ -741,9 +719,7 @@ if sys.version_info >= (3, 12):
from _asyncio import current_task as current_task from _asyncio import current_task as current_task
else: else:
def current_task(loop: AbstractEventLoop | None = None) -> Task[Any] | None: 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): if sys.version_info >= (3, 14):
def eager_task_factory( def eager_task_factory(
@ -790,8 +766,7 @@ if sys.version_info >= (3, 12):
) -> _TaskT_co: ... ) -> _TaskT_co: ...
def create_eager_task_factory(custom_task_constructor: _CustomTaskConstructor[_TaskT_co]) -> _EagerTaskFactoryType[_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: Example usage:

View file

@ -12,8 +12,7 @@ _P = ParamSpec("_P")
_R = TypeVar("_R") _R = TypeVar("_R")
async def to_thread(func: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> _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 Any *args and **kwargs supplied for this function are directly passed
to *func*. Also, the current :class:`contextvars.Context` is propagated, to *func*. Also, the current :class:`contextvars.Context` is propagated,

View file

@ -7,15 +7,13 @@ __all__ = ("Timeout", "timeout", "timeout_at")
@final @final
class Timeout: 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. Use `timeout()` or `timeout_at()` rather than instantiating this class directly.
""" """
def __init__(self, when: float | None) -> None: 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` is `None`, the timeout will never trigger.
- If `when < loop.time()`, the timeout will trigger on the next - If `when < loop.time()`, the timeout will trigger on the next
@ -23,19 +21,13 @@ class Timeout:
""" """
def when(self) -> float | None: def when(self) -> float | None:
""" """Return the current deadline."""
Return the current deadline.
"""
def reschedule(self, when: float | None) -> None: def reschedule(self, when: float | None) -> None:
""" """Reschedule the timeout."""
Reschedule the timeout.
"""
def expired(self) -> bool: def expired(self) -> bool:
""" """Is timeout expired during execution?"""
Is timeout expired during execution?
"""
async def __aenter__(self) -> Self: ... async def __aenter__(self) -> Self: ...
async def __aexit__( async def __aexit__(
@ -43,8 +35,7 @@ class Timeout:
) -> None: ... ) -> None: ...
def timeout(delay: float | None) -> Timeout: 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 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: 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: 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 Like timeout() but argument gives absolute time in the same clock system
as loop.time(). as loop.time().

View file

@ -34,9 +34,7 @@ class NodeType(Enum):
TASK = 2 TASK = 2
class CycleFoundException(Exception): 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]] cycles: list[list[int]]
id2name: dict[int, str] id2name: dict[int, str]
@ -44,8 +42,7 @@ class CycleFoundException(Exception):
def get_all_awaited_by(pid: SupportsIndex) -> list[_AwaitedInfo]: ... 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]]: 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 The call tree is produced by `get_all_async_stacks()`, prefixing tasks
with `task_emoji` and coroutine frames with `cor_emoji`. 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 build_task_table(result: Iterable[_AwaitedInfo]) -> list[list[int | str]]: ...
def display_awaited_by_tasks_table(pid: SupportsIndex) -> None: 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: 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`.
"""

View file

@ -12,24 +12,17 @@ from typing import Any
__all__ = ("BaseTransport", "ReadTransport", "WriteTransport", "Transport", "DatagramTransport", "SubprocessTransport") __all__ = ("BaseTransport", "ReadTransport", "WriteTransport", "Transport", "DatagramTransport", "SubprocessTransport")
class BaseTransport: class BaseTransport:
""" """Base class for transports."""
Base class for transports.
"""
def __init__(self, extra: Mapping[str, Any] | None = None) -> None: ... def __init__(self, extra: Mapping[str, Any] | None = None) -> None: ...
def get_extra_info(self, name: str, default: Any = None) -> Any: def get_extra_info(self, name: str, default: Any = None) -> Any:
""" """Get optional transport information."""
Get optional transport information.
"""
def is_closing(self) -> bool: 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: def close(self) -> None:
""" """Close the transport.
Close the transport.
Buffered data will be flushed asynchronously. No more data Buffered data will be flushed asynchronously. No more data
will be received. After all buffered data is flushed, the will be received. After all buffered data is flushed, the
@ -38,49 +31,36 @@ class BaseTransport:
""" """
def set_protocol(self, protocol: BaseProtocol) -> None: def set_protocol(self, protocol: BaseProtocol) -> None:
""" """Set a new protocol."""
Set a new protocol.
"""
def get_protocol(self) -> BaseProtocol: def get_protocol(self) -> BaseProtocol:
""" """Return the current protocol."""
Return the current protocol.
"""
class ReadTransport(BaseTransport): class ReadTransport(BaseTransport):
""" """Interface for read-only transports."""
Interface for read-only transports.
"""
def is_reading(self) -> bool: def is_reading(self) -> bool:
""" """Return True if the transport is receiving."""
Return True if the transport is receiving.
"""
def pause_reading(self) -> None: def pause_reading(self) -> None:
""" """Pause the receiving end.
Pause the receiving end.
No data will be passed to the protocol's data_received() No data will be passed to the protocol's data_received()
method until resume_reading() is called. method until resume_reading() is called.
""" """
def resume_reading(self) -> None: 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 will once again be passed to the protocol's
data_received() method. data_received() method.
""" """
class WriteTransport(BaseTransport): 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: 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 These two values control when to call the protocol's
pause_writing() and resume_writing() methods. If specified, pause_writing() and resume_writing() methods. If specified,
@ -100,36 +80,30 @@ class WriteTransport(BaseTransport):
""" """
def get_write_buffer_size(self) -> int: 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]: 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 Return a tuple (low, high) where low and high are
positive number of bytes. positive number of bytes.
""" """
def write(self, data: bytes | bytearray | memoryview[Any]) -> None: # any memoryview format or shape 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 This does not block; it buffers the data and arranges for it
to be sent out asynchronously. to be sent out asynchronously.
""" """
def writelines(self, list_of_data: Iterable[bytes | bytearray | memoryview[Any]]) -> None: # any memoryview format or shape 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 The default implementation concatenates the arguments and
calls write() on the result. calls write() on the result.
""" """
def write_eof(self) -> None: 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.) (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: 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: def abort(self) -> None:
""" """Close the transport immediately.
Close the transport immediately.
Buffered data will be lost. No more data will be received. Buffered data will be lost. No more data will be received.
The protocol's connection_lost() method will (eventually) be The protocol's connection_lost() method will (eventually) be
@ -151,8 +122,7 @@ class WriteTransport(BaseTransport):
""" """
class Transport(ReadTransport, WriteTransport): class Transport(ReadTransport, WriteTransport):
""" """Interface representing a bidirectional transport.
Interface representing a bidirectional transport.
There may be several implementations, but typically, the user does There may be several implementations, but typically, the user does
not implement new transports; rather, the platform provides some not implement new transports; rather, the platform provides some
@ -173,13 +143,10 @@ class Transport(ReadTransport, WriteTransport):
""" """
class DatagramTransport(BaseTransport): 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: 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 This does not block; it buffers the data and arranges for it
to be sent out asynchronously. to be sent out asynchronously.
@ -190,8 +157,7 @@ class DatagramTransport(BaseTransport):
""" """
def abort(self) -> None: def abort(self) -> None:
""" """Close the transport immediately.
Close the transport immediately.
Buffered data will be lost. No more data will be received. Buffered data will be lost. No more data will be received.
The protocol's connection_lost() method will (eventually) be The protocol's connection_lost() method will (eventually) be
@ -200,34 +166,27 @@ class DatagramTransport(BaseTransport):
class SubprocessTransport(BaseTransport): class SubprocessTransport(BaseTransport):
def get_pid(self) -> int: def get_pid(self) -> int:
""" """Get subprocess id."""
Get subprocess id.
"""
def get_returncode(self) -> int | None: def get_returncode(self) -> int | None:
""" """Get subprocess returncode.
Get subprocess returncode.
See also See also
http://docs.python.org/3/library/subprocess#subprocess.Popen.returncode http://docs.python.org/3/library/subprocess#subprocess.Popen.returncode
""" """
def get_pipe_transport(self, fd: int) -> BaseTransport | None: 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: def send_signal(self, signal: int) -> None:
""" """Send signal to subprocess.
Send signal to subprocess.
See also: See also:
docs.python.org/3/library/subprocess#subprocess.Popen.send_signal docs.python.org/3/library/subprocess#subprocess.Popen.send_signal
""" """
def terminate(self) -> None: def terminate(self) -> None:
""" """Stop the subprocess.
Stop the subprocess.
Alias for close() method. Alias for close() method.
@ -240,8 +199,7 @@ class SubprocessTransport(BaseTransport):
""" """
def kill(self) -> None: def kill(self) -> None:
""" """Kill the subprocess.
Kill the subprocess.
On Posix OSs the function sends SIGKILL to the subprocess. On Posix OSs the function sends SIGKILL to the subprocess.
On Windows kill() is an alias for terminate(). On Windows kill() is an alias for terminate().
@ -251,8 +209,7 @@ class SubprocessTransport(BaseTransport):
""" """
class _FlowControlMixin(Transport): 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 The subclass must implement get_write_buffer_size(). It must call
_maybe_pause_protocol() whenever the write buffer size increases, _maybe_pause_protocol() whenever the write buffer size increases,

View file

@ -14,8 +14,7 @@ _WriteBuffer: TypeAlias = bytearray | memoryview
_CMSG: TypeAlias = tuple[int, int, bytes] _CMSG: TypeAlias = tuple[int, int, bytes]
class TransportSocket: 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 These objects can be safely returned by APIs like
`transport.get_extra_info('socket')`. All potentially disruptive `transport.get_extra_info('socket')`. All potentially disruptive

View file

@ -54,8 +54,7 @@ if sys.version_info < (3, 14):
if sys.version_info >= (3, 12): if sys.version_info >= (3, 12):
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
class AbstractChildWatcher: 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 Objects derived from this class monitor a collection of subprocesses and
report their termination or interruption by a signal. report their termination or interruption by a signal.
@ -81,8 +80,7 @@ if sys.version_info < (3, 14):
def add_child_handler( def add_child_handler(
self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts]
) -> None: ) -> None:
""" """Register a new child handler.
Register a new child handler.
Arrange for callback(pid, returncode, *args) to be called when Arrange for callback(pid, returncode, *args) to be called when
process 'pid' terminates. Specifying another callback for the same process 'pid' terminates. Specifying another callback for the same
@ -93,8 +91,7 @@ if sys.version_info < (3, 14):
@abstractmethod @abstractmethod
def remove_child_handler(self, pid: int) -> bool: 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, The function returns True if the handler was successfully removed,
False if there was nothing to remove. False if there was nothing to remove.
@ -102,8 +99,7 @@ if sys.version_info < (3, 14):
@abstractmethod @abstractmethod
def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: 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 If the watcher was previously attached to an event loop, then it is
first detached before attaching to the new loop. first detached before attaching to the new loop.
@ -113,16 +109,14 @@ if sys.version_info < (3, 14):
@abstractmethod @abstractmethod
def close(self) -> None: def close(self) -> None:
""" """Close the watcher.
Close the watcher.
This must be called to make sure that any underlying resource is freed. This must be called to make sure that any underlying resource is freed.
""" """
@abstractmethod @abstractmethod
def __enter__(self) -> Self: 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 This function must return self
""" """
@ -131,14 +125,11 @@ if sys.version_info < (3, 14):
def __exit__( def __exit__(
self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None
) -> None: ) -> None:
""" """Exit the watcher's context"""
Exit the watcher's context
"""
@abstractmethod @abstractmethod
def is_active(self) -> bool: 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 Return True if the watcher is installed and ready to handle process exit
notifications. notifications.
@ -146,8 +137,7 @@ if sys.version_info < (3, 14):
else: else:
class AbstractChildWatcher: 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 Objects derived from this class monitor a collection of subprocesses and
report their termination or interruption by a signal. report their termination or interruption by a signal.
@ -173,8 +163,7 @@ if sys.version_info < (3, 14):
def add_child_handler( def add_child_handler(
self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts]
) -> None: ) -> None:
""" """Register a new child handler.
Register a new child handler.
Arrange for callback(pid, returncode, *args) to be called when Arrange for callback(pid, returncode, *args) to be called when
process 'pid' terminates. Specifying another callback for the same process 'pid' terminates. Specifying another callback for the same
@ -185,8 +174,7 @@ if sys.version_info < (3, 14):
@abstractmethod @abstractmethod
def remove_child_handler(self, pid: int) -> bool: 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, The function returns True if the handler was successfully removed,
False if there was nothing to remove. False if there was nothing to remove.
@ -194,8 +182,7 @@ if sys.version_info < (3, 14):
@abstractmethod @abstractmethod
def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: 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 If the watcher was previously attached to an event loop, then it is
first detached before attaching to the new loop. first detached before attaching to the new loop.
@ -205,16 +192,14 @@ if sys.version_info < (3, 14):
@abstractmethod @abstractmethod
def close(self) -> None: def close(self) -> None:
""" """Close the watcher.
Close the watcher.
This must be called to make sure that any underlying resource is freed. This must be called to make sure that any underlying resource is freed.
""" """
@abstractmethod @abstractmethod
def __enter__(self) -> Self: 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 This function must return self
""" """
@ -223,14 +208,11 @@ if sys.version_info < (3, 14):
def __exit__( def __exit__(
self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None
) -> None: ) -> None:
""" """Exit the watcher's context"""
Exit the watcher's context
"""
@abstractmethod @abstractmethod
def is_active(self) -> bool: 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 Return True if the watcher is installed and ready to handle process exit
notifications. notifications.
@ -248,8 +230,7 @@ if sys.platform != "win32":
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
class SafeChildWatcher(BaseChildWatcher): class SafeChildWatcher(BaseChildWatcher):
""" """'Safe' child watcher implementation.
'Safe' child watcher implementation.
This implementation avoids disrupting other code spawning processes by This implementation avoids disrupting other code spawning processes by
polling explicitly each process in the SIGCHLD handler instead of calling 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") @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
class FastChildWatcher(BaseChildWatcher): class FastChildWatcher(BaseChildWatcher):
""" """'Fast' child watcher implementation.
'Fast' child watcher implementation.
This implementation reaps every terminated processes by calling This implementation reaps every terminated processes by calling
os.waitpid(-1) directly, possibly breaking other code spawning processes 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: ... def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ...
class SafeChildWatcher(BaseChildWatcher): class SafeChildWatcher(BaseChildWatcher):
""" """'Safe' child watcher implementation.
'Safe' child watcher implementation.
This implementation avoids disrupting other code spawning processes by This implementation avoids disrupting other code spawning processes by
polling explicitly each process in the SIGCHLD handler instead of calling 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: ... def remove_child_handler(self, pid: int) -> bool: ...
class FastChildWatcher(BaseChildWatcher): class FastChildWatcher(BaseChildWatcher):
""" """'Fast' child watcher implementation.
'Fast' child watcher implementation.
This implementation reaps every terminated processes by calling This implementation reaps every terminated processes by calling
os.waitpid(-1) directly, possibly breaking other code spawning processes 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: ... def remove_child_handler(self, pid: int) -> bool: ...
class _UnixSelectorEventLoop(BaseSelectorEventLoop): class _UnixSelectorEventLoop(BaseSelectorEventLoop):
""" """Unix event loop.
Unix event loop.
Adds signal handling and UNIX Domain Socket support to SelectorEventLoop. Adds signal handling and UNIX Domain Socket support to SelectorEventLoop.
""" """
@ -364,42 +341,32 @@ if sys.platform != "win32":
if sys.version_info >= (3, 14): if sys.version_info >= (3, 14):
class _UnixDefaultEventLoopPolicy(events._BaseDefaultEventLoopPolicy): class _UnixDefaultEventLoopPolicy(events._BaseDefaultEventLoopPolicy):
""" """UNIX event loop policy"""
UNIX event loop policy
"""
else: else:
class _UnixDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy): 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): if sys.version_info >= (3, 12):
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
def get_child_watcher(self) -> AbstractChildWatcher: 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. If not yet set, a ThreadedChildWatcher object is automatically created.
""" """
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None:
""" """Set the watcher for child processes."""
Set the watcher for child processes.
"""
else: else:
def get_child_watcher(self) -> AbstractChildWatcher: 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. If not yet set, a ThreadedChildWatcher object is automatically created.
""" """
def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None:
""" """Set the watcher for child processes."""
Set the watcher for child processes.
"""
SelectorEventLoop = _UnixSelectorEventLoop SelectorEventLoop = _UnixSelectorEventLoop
@ -415,8 +382,7 @@ if sys.platform != "win32":
if sys.version_info >= (3, 12): if sys.version_info >= (3, 12):
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
class MultiLoopChildWatcher(AbstractChildWatcher): 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 This implementation registers a SIGCHLD signal handler on
instantiation (which may conflict with other code that instantiation (which may conflict with other code that
@ -441,8 +407,7 @@ if sys.platform != "win32":
else: else:
class MultiLoopChildWatcher(AbstractChildWatcher): 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 This implementation registers a SIGCHLD signal handler on
instantiation (which may conflict with other code that instantiation (which may conflict with other code that
@ -467,8 +432,7 @@ if sys.platform != "win32":
if sys.version_info < (3, 14): if sys.version_info < (3, 14):
class ThreadedChildWatcher(AbstractChildWatcher): class ThreadedChildWatcher(AbstractChildWatcher):
""" """Threaded child watcher implementation.
Threaded child watcher implementation.
The watcher uses a thread per process The watcher uses a thread per process
for waiting for the process finish. for waiting for the process finish.
@ -494,8 +458,7 @@ if sys.platform != "win32":
def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ...
class PidfdChildWatcher(AbstractChildWatcher): 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 This child watcher polls process file descriptors (pidfds) to await child
process termination. In some respects, PidfdChildWatcher is a "Goldilocks" process termination. In some respects, PidfdChildWatcher is a "Goldilocks"

View file

@ -1,3 +1,7 @@
"""
Selector and proactor event loops for Windows.
"""
import socket import socket
import sys import sys
from _typeshed import Incomplete, ReadableBuffer, WriteableBuffer from _typeshed import Incomplete, ReadableBuffer, WriteableBuffer
@ -47,14 +51,22 @@ if sys.platform == "win32":
CONNECT_PIPE_MAX_DELAY: float CONNECT_PIPE_MAX_DELAY: float
class PipeServer: class PipeServer:
"""Class representing a pipe server.
This is much like a bound, listening socket.
"""
def __init__(self, address: str) -> None: ... def __init__(self, address: str) -> None: ...
def __del__(self) -> None: ... def __del__(self) -> None: ...
def closed(self) -> bool: ... def closed(self) -> bool: ...
def close(self) -> None: ... 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): class ProactorEventLoop(proactor_events.BaseProactorEventLoop):
"""Windows version of proactor event loop using IOCP."""
def __init__(self, proactor: IocpProactor | None = None) -> None: ... def __init__(self, proactor: IocpProactor | None = None) -> None: ...
async def create_pipe_connection( async def create_pipe_connection(
self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str
@ -64,6 +76,8 @@ if sys.platform == "win32":
) -> list[PipeServer]: ... ) -> list[PipeServer]: ...
class IocpProactor: class IocpProactor:
"""Proactor implementation using IOCP."""
def __init__(self, concurrency: int = 0xFFFFFFFF) -> None: ... def __init__(self, concurrency: int = 0xFFFFFFFF) -> None: ...
def __del__(self) -> None: ... def __del__(self) -> None: ...
def set_loop(self, loop: events.AbstractEventLoop) -> 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 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]: ... def accept_pipe(self, pipe: socket.socket) -> futures.Future[Any]: ...
async def connect_pipe(self, address: str) -> windows_utils.PipeHandle: ... 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: ... def close(self) -> None: ...
if sys.version_info >= (3, 11): if sys.version_info >= (3, 11):
def recvfrom_into( def recvfrom_into(
@ -105,13 +125,19 @@ if sys.platform == "win32":
else: else:
class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
_loop_factory: ClassVar[type[SelectorEventLoop]] _loop_factory: ClassVar[type[SelectorEventLoop]]
def get_child_watcher(self) -> NoReturn: ... def get_child_watcher(self) -> NoReturn:
def set_child_watcher(self, watcher: Any) -> 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): class WindowsProactorEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
_loop_factory: ClassVar[type[ProactorEventLoop]] _loop_factory: ClassVar[type[ProactorEventLoop]]
def get_child_watcher(self) -> NoReturn: ... def get_child_watcher(self) -> NoReturn:
def set_child_watcher(self, watcher: Any) -> 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): if sys.version_info >= (3, 14):
_DefaultEventLoopPolicy = _WindowsProactorEventLoopPolicy _DefaultEventLoopPolicy = _WindowsProactorEventLoopPolicy

View file

@ -1,3 +1,7 @@
"""
Various Windows specific bits and pieces.
"""
import subprocess import subprocess
import sys import sys
from collections.abc import Callable from collections.abc import Callable
@ -11,9 +15,15 @@ if sys.platform == "win32":
BUFSIZE: Final = 8192 BUFSIZE: Final = 8192
PIPE = subprocess.PIPE PIPE = subprocess.PIPE
STDOUT = subprocess.STDOUT 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: 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 __init__(self, handle: int) -> None: ...
def __del__(self) -> None: ... def __del__(self) -> None: ...
def __enter__(self) -> Self: ... def __enter__(self) -> Self: ...
@ -24,6 +34,11 @@ if sys.platform == "win32":
def close(self, *, CloseHandle: Callable[[int], object] = ...) -> None: ... def close(self, *, CloseHandle: Callable[[int], object] = ...) -> None: ...
class Popen(subprocess.Popen[AnyStr]): 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] stdin: PipeHandle | None # type: ignore[assignment]
stdout: PipeHandle | None # type: ignore[assignment] stdout: PipeHandle | None # type: ignore[assignment]
stderr: PipeHandle | None # type: ignore[assignment] stderr: PipeHandle | None # type: ignore[assignment]

View file

@ -13,25 +13,19 @@ _T = TypeVar("_T")
_P = ParamSpec("_P") _P = ParamSpec("_P")
def _clear() -> None: def _clear() -> None:
""" """Clear the list of previously registered exit functions."""
Clear the list of previously registered exit functions.
"""
def _ncallbacks() -> int: def _ncallbacks() -> int:
""" """Return the number of registered exit functions."""
Return the number of registered exit functions.
"""
def _run_exitfuncs() -> None: 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. 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]: 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 func - function to be called at exit
args - optional arguments to pass to func 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: 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 atexit.register
func - function to be unregistered func - function to be unregistered

View file

@ -6,104 +6,64 @@ _RatecvState: TypeAlias = tuple[int, tuple[tuple[int, int], ...]]
class error(Exception): ... class error(Exception): ...
def add(fragment1: Buffer, fragment2: Buffer, width: int, /) -> bytes: 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]: 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: 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: 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: 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: 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: 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: 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: 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]: 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: 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: 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]: 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: 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: 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: 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: 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: 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]: 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: 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( def ratecv(
fragment: Buffer, fragment: Buffer,
@ -116,31 +76,19 @@ def ratecv(
weightB: int = 0, weightB: int = 0,
/, /,
) -> tuple[bytes, _RatecvState]: ) -> 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: 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: 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: 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: 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: 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.
"""

View file

@ -33,8 +33,7 @@ if sys.version_info >= (3, 13):
__all__ += ["z85decode", "z85encode"] __all__ += ["z85decode", "z85encode"]
def b64encode(s: ReadableBuffer, altchars: ReadableBuffer | None = None) -> bytes: 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 Optional altchars should be a byte string of length 2 which specifies an
alternative alphabet for the '+' and '/' characters. This allows 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: 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 Optional altchars must be a bytes-like object or ASCII string of length 2
which specifies the alternative alphabet used instead of the '+' and '/' 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: 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. The result is returned as a bytes object.
""" """
def standard_b64decode(s: str | ReadableBuffer) -> bytes: 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 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 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: 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 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 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: 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 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 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: 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: 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 Optional casefold is a flag specifying whether a lowercase alphabet is
acceptable as input. For security purposes, the default is False. 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: 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: 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 Optional casefold is a flag specifying whether a lowercase alphabet is
acceptable as input. For security purposes, the default is False. 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): if sys.version_info >= (3, 10):
def b32hexencode(s: ReadableBuffer) -> bytes: 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: 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 Optional casefold is a flag specifying whether a lowercase alphabet is
acceptable as input. For security purposes, the default is False. 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: 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' foldspaces is an optional flag that uses the special short sequence 'y'
instead of 4 consecutive spaces (ASCII 0x20) as supported by 'btoa'. This 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( def a85decode(
b: str | ReadableBuffer, *, foldspaces: bool = False, adobe: bool = False, ignorechars: bytearray | bytes = b" \t\n\r\x0b" b: str | ReadableBuffer, *, foldspaces: bool = False, adobe: bool = False, ignorechars: bytearray | bytes = b" \t\n\r\x0b"
) -> bytes: ) -> 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 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 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: 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 If pad is true, the input is padded with b'\\0' so its length is a multiple of
4 bytes before encoding. 4 bytes before encoding.
""" """
def b85decode(b: str | ReadableBuffer) -> bytes: 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. The result is returned as a bytes object.
""" """
def decode(input: IO[bytes], output: IO[bytes]) -> None: 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: 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: 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. of base-64 data.
""" """
def decodebytes(s: ReadableBuffer) -> bytes: 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): if sys.version_info >= (3, 13):
def z85encode(s: ReadableBuffer) -> bytes: 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: 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. The result is returned as a bytes object.
""" """

View file

@ -22,13 +22,10 @@ _Backend: TypeAlias = Literal["settrace", "monitoring"]
GENERATOR_AND_COROUTINE_FLAGS: Final[int] GENERATOR_AND_COROUTINE_FLAGS: Final[int]
class BdbQuit(Exception): class BdbQuit(Exception):
""" """Exception to give up completely."""
Exception to give up completely.
"""
class Bdb: class Bdb:
""" """Generic Python debugger base class.
Generic Python debugger base class.
This class takes care of details of the trace facility; This class takes care of details of the trace facility;
a derived class should implement user interaction. a derived class should implement user interaction.
@ -57,8 +54,7 @@ class Bdb:
def __init__(self, skip: Iterable[str] | None = None) -> None: ... def __init__(self, skip: Iterable[str] | None = None) -> None: ...
def canonic(self, filename: str) -> str: 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 For real filenames, the canonical form is a case-normalized (on
case insensitive filesystems) absolute path. 'Filenames' with case insensitive filesystems) absolute path. 'Filenames' with
@ -67,16 +63,13 @@ class Bdb:
""" """
def reset(self) -> None: 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): if sys.version_info >= (3, 12):
@contextmanager @contextmanager
def set_enterframe(self, frame: FrameType) -> Iterator[None]: ... def set_enterframe(self, frame: FrameType) -> Iterator[None]: ...
def trace_dispatch(self, frame: FrameType, event: str, arg: Any) -> TraceFunction: 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 This function is installed as the trace function for debugged
frames. Its return value is the new trace function, which is frames. Its return value is the new trace function, which is
@ -101,8 +94,7 @@ class Bdb:
""" """
def dispatch_line(self, frame: FrameType) -> TraceFunction: 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 If the debugger stops on the current line, invoke
self.user_line(). Raise BdbQuit if self.quitting is set. 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: 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 If the debugger stops on this function call, invoke
self.user_call(). Raise BdbQuit if self.quitting is set. 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: 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 If the debugger stops on this function return, invoke
self.user_return(). Raise BdbQuit if self.quitting is set. 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: 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 If the debugger stops on this exception, invoke
self.user_exception(). Raise BdbQuit if self.quitting is set. self.user_exception(). Raise BdbQuit if self.quitting is set.
@ -137,8 +126,7 @@ class Bdb:
""" """
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
def dispatch_opcode(self, frame: FrameType, arg: Unused) -> Callable[[FrameType, str, Any], TraceFunction]: 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 If the debugger stops on the current opcode, invoke
self.user_opcode(). Raise BdbQuit if self.quitting is set. self.user_opcode(). Raise BdbQuit if self.quitting is set.
Return self.trace_dispatch to continue tracing in this scope. 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: 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: 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: 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. Check for line or function breakpoint and if in effect.
Delete temporary breakpoints if effective() says to. Delete temporary breakpoints if effective() says to.
""" """
def do_clear(self, arg: Any) -> bool | None: def do_clear(self, arg: Any) -> bool | None:
""" """Remove temporary breakpoint.
Remove temporary breakpoint.
Must implement in derived classes or get NotImplementedError. Must implement in derived classes or get NotImplementedError.
""" """
def break_anywhere(self, frame: FrameType) -> bool: 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: 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: 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: 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: 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: 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. reached or when returning from current frame.
""" """
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
def user_opcode(self, frame: FrameType) -> None: # undocumented 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: def set_step(self) -> None:
""" """Stop after one line of code."""
Stop after one line of code.
"""
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
def set_stepinstr(self) -> None: # undocumented def set_stepinstr(self) -> None: # undocumented
""" """Stop before the next instruction."""
Stop before the next instruction.
"""
def set_next(self, frame: FrameType) -> None: 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: 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: 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. If frame is not specified, debugging starts from caller's frame.
""" """
def set_continue(self) -> None: 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. If there are no breakpoints, set the system trace function to None.
""" """
def set_quit(self) -> 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. Raises BdbQuit exception in the next call to a dispatch_*() method.
""" """
@ -253,84 +211,70 @@ class Bdb:
def set_break( def set_break(
self, filename: str, lineno: int, temporary: bool = False, cond: str | None = None, funcname: str | None = None self, filename: str, lineno: int, temporary: bool = False, cond: str | None = None, funcname: str | None = None
) -> str | 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. If lineno doesn't exist for the filename, return an error message.
The filename should be in canonical form. The filename should be in canonical form.
""" """
def clear_break(self, filename: str, lineno: int) -> str | None: 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. If no breakpoints were set, return an error message.
""" """
def clear_bpbynumber(self, arg: SupportsInt) -> str | None: 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. If arg is invalid, return an error message.
""" """
def clear_all_file_breaks(self, filename: str) -> str | None: 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. If none were set, return an error message.
""" """
def clear_all_breaks(self) -> str | None: def clear_all_breaks(self) -> str | None:
""" """Delete all existing breakpoints.
Delete all existing breakpoints.
If none were set, return an error message. If none were set, return an error message.
""" """
def get_bpbynumber(self, arg: SupportsInt) -> Breakpoint: 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, For invalid arg values or if the breakpoint doesn't exist,
raise a ValueError. raise a ValueError.
""" """
def get_break(self, filename: str, lineno: int) -> bool: 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]: 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. If no breakpoints are set, return an empty list.
""" """
def get_file_breaks(self, filename: str) -> list[Breakpoint]: 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. If no breakpoints are set, return an empty list.
""" """
def get_all_breaks(self) -> list[Breakpoint]: 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]: 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. List starts with original calling frame, if there is one.
Size may be number of frames above or below f. Size may be number of frames above or below f.
""" """
def format_stack_entry(self, frame_lineno: tuple[FrameType, int], lprefix: str = ": ") -> str: 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 The stack entry frame_lineno is a (frame, lineno) tuple. The
return string contains the canonical filename, the function name 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: 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. 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: 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. 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: 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: 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. Return the result of the function call.
""" """
@ -367,18 +306,13 @@ class Bdb:
def start_trace(self) -> None: ... def start_trace(self) -> None: ...
def stop_trace(self) -> None: ... def stop_trace(self) -> None: ...
def disable_current_event(self) -> None: def disable_current_event(self) -> None:
""" """Disable the current event."""
Disable the current event.
"""
def restart_events(self) -> None: def restart_events(self) -> None:
""" """Restart all events."""
Restart all events.
"""
class Breakpoint: class Breakpoint:
""" """Breakpoint class.
Breakpoint class.
Implements temporary breakpoints, ignore counts, disabling and Implements temporary breakpoints, ignore counts, disabling and
(re)-enabling, and conditionals. (re)-enabling, and conditionals.
@ -417,34 +351,27 @@ class Breakpoint:
def clearBreakpoints() -> None: ... def clearBreakpoints() -> None: ...
def deleteMe(self) -> 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 If it is the last breakpoint in that position, it also deletes
the entry for the file:line. the entry for the file:line.
""" """
def enable(self) -> None: def enable(self) -> None:
""" """Mark the breakpoint as enabled."""
Mark the breakpoint as enabled.
"""
def disable(self) -> None: def disable(self) -> None:
""" """Mark the breakpoint as disabled."""
Mark the breakpoint as disabled.
"""
def bpprint(self, out: IO[str] | None = None) -> None: 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 The optional out argument directs where the output is sent
and defaults to standard output. and defaults to standard output.
""" """
def bpformat(self) -> str: 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 The information includes the breakpoint number, temporary
status, file:line position, break condition, number of times to status, file:line position, break condition, number of times to
@ -452,8 +379,7 @@ class Breakpoint:
""" """
def checkfuncname(b: Breakpoint, frame: FrameType) -> bool: 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) 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 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]: 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. breakpoint to act upon.
The "active breakpoint" is the first entry in bplist[line, file] (which 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: 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.
"""

View file

@ -11,19 +11,14 @@ from typing_extensions import TypeAlias
_AsciiBuffer: TypeAlias = str | ReadableBuffer _AsciiBuffer: TypeAlias = str | ReadableBuffer
def a2b_uu(data: _AsciiBuffer, /) -> bytes: 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: def b2a_uu(data: ReadableBuffer, /, *, backtick: bool = False) -> bytes:
""" """Uuencode line of data."""
Uuencode line of data.
"""
if sys.version_info >= (3, 11): if sys.version_info >= (3, 11):
def a2b_base64(data: _AsciiBuffer, /, *, strict_mode: bool = False) -> bytes: def a2b_base64(data: _AsciiBuffer, /, *, strict_mode: bool = False) -> bytes:
""" """Decode a line of base64 data.
Decode a line of base64 data.
strict_mode strict_mode
When set to True, bytes that are not part of the base64 standard are not allowed. 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: else:
def a2b_base64(data: _AsciiBuffer, /) -> bytes: 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: 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: 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: 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 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) 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): if sys.version_info < (3, 11):
def a2b_hqx(data: _AsciiBuffer, /) -> bytes: def a2b_hqx(data: _AsciiBuffer, /) -> bytes:
""" """Decode .hqx coding."""
Decode .hqx coding.
"""
def rledecode_hqx(data: ReadableBuffer, /) -> bytes: def rledecode_hqx(data: ReadableBuffer, /) -> bytes:
""" """Decode hexbin RLE-coded string."""
Decode hexbin RLE-coded string.
"""
def rlecode_hqx(data: ReadableBuffer, /) -> bytes: def rlecode_hqx(data: ReadableBuffer, /) -> bytes:
""" """Binhex RLE-code binary data."""
Binhex RLE-code binary data.
"""
def b2a_hqx(data: ReadableBuffer, /) -> bytes: def b2a_hqx(data: ReadableBuffer, /) -> bytes:
""" """Encode .hqx data."""
Encode .hqx data.
"""
def crc_hqx(data: ReadableBuffer, crc: int, /) -> int: def crc_hqx(data: ReadableBuffer, crc: int, /) -> int:
""" """Compute CRC-CCITT incrementally."""
Compute CRC-CCITT incrementally.
"""
def crc32(data: ReadableBuffer, crc: int = 0, /) -> int: 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: def b2a_hex(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = ...) -> bytes:
""" """Hexadecimal representation of binary data.
Hexadecimal representation of binary data.
sep sep
An optional single character or byte to separate hex bytes. 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: def hexlify(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = ...) -> bytes:
""" """Hexadecimal representation of binary data.
Hexadecimal representation of binary data.
sep sep
An optional single character or byte to separate hex bytes. 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: 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). hexstr must contain an even number of hex digits (upper or lower case).
This function is also available as "unhexlify()". This function is also available as "unhexlify()".
""" """
def unhexlify(hexstr: _AsciiBuffer, /) -> bytes: 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). hexstr must contain an even number of hex digits (upper or lower case).
""" """

View file

@ -42,9 +42,7 @@ class BinHex:
def close(self) -> None: ... def close(self) -> None: ...
def binhex(inp: str, out: str) -> 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: class HexBin:
def __init__(self, ifp: _FileHandleUnion) -> None: ... def __init__(self, ifp: _FileHandleUnion) -> None: ...
@ -54,6 +52,4 @@ class HexBin:
def close(self) -> None: ... def close(self) -> None: ...
def hexbin(inp: str, out: str) -> None: def hexbin(inp: str, out: str) -> None:
""" """hexbin(infilename, outfilename) - Decode binhexed file"""
hexbin(infilename, outfilename) - Decode binhexed file
"""

File diff suppressed because it is too large Load diff

View file

@ -32,8 +32,7 @@ class _WritableFileobj(Protocol):
# def close(self) -> object: ... # def close(self) -> object: ...
def compress(data: ReadableBuffer, compresslevel: int = 9) -> bytes: 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. 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: def decompress(data: ReadableBuffer) -> bytes:
""" """Decompress a block of data.
Decompress a block of data.
For incremental decompression, use a BZ2Decompressor object instead. For incremental decompression, use a BZ2Decompressor object instead.
""" """
@ -61,8 +59,7 @@ def open(
errors: None = None, errors: None = None,
newline: None = None, newline: None = None,
) -> BZ2File: ) -> 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 The filename argument can be an actual filename (a str, bytes, or
PathLike object), or an existing file object to read from or write PathLike object), or an existing file object to read from or write
@ -137,8 +134,7 @@ def open(
) -> BZ2File | TextIOWrapper: ... ) -> BZ2File | TextIOWrapper: ...
class BZ2File(BaseStream, IO[bytes]): 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 A BZ2File can act as a wrapper for an existing file object, or refer
directly to a named file on disk. directly to a named file on disk.
@ -150,8 +146,7 @@ class BZ2File(BaseStream, IO[bytes]):
def __enter__(self) -> Self: ... def __enter__(self) -> Self: ...
@overload @overload
def __init__(self, filename: _WritableFileobj, mode: _WriteBinaryMode, *, compresslevel: int = 9) -> None: 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 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 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 self, filename: StrOrBytesPath, mode: _ReadBinaryMode | _WriteBinaryMode = "r", *, compresslevel: int = 9
) -> None: ... ) -> None: ...
def read(self, size: int | None = -1) -> bytes: 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. If size is negative or omitted, read until EOF is reached.
Returns b'' if the file is already at EOF. Returns b'' if the file is already at EOF.
""" """
def read1(self, size: int = -1) -> bytes: 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 making multiple reads from the underlying stream. Reads up to a
buffer's worth of data if size is negative. 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] 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 The terminating newline (if present) is retained. If size is
non-negative, no more than size bytes will be read (in which 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: def readinto(self, b: WriteableBuffer) -> int:
""" """Read bytes into b.
Read bytes into b.
Returns the number of bytes read (0 for EOF). Returns the number of bytes read (0 for EOF).
""" """
def readlines(self, size: SupportsIndex = -1) -> list[bytes]: 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 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 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: 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. Always returns at least one byte of data, unless at EOF.
The exact number of bytes returned is unspecified. The exact number of bytes returned is unspecified.
""" """
def seek(self, offset: int, whence: int = 0) -> int: 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 The new position is specified by offset, relative to the
position indicated by whence. Values for whence are: position indicated by whence. Values for whence are:
@ -243,8 +231,7 @@ class BZ2File(BaseStream, IO[bytes]):
""" """
def write(self, data: ReadableBuffer) -> int: 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 Returns the number of uncompressed bytes written, which is
always the length of data in bytes. Note that due to buffering, 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: 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. Returns the number of uncompressed bytes written.
seq can be any iterable yielding byte strings. seq can be any iterable yielding byte strings.

Some files were not shown because too many files have changed in this diff Show more