Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 12 additions & 15 deletions Doc/library/asyncio-dev.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Debug Mode
==========

By default asyncio runs in production mode. In order to ease
the development asyncio has a *debug mode*.
development, asyncio has a *debug mode*.

There are several ways to enable asyncio debug mode:

Expand All @@ -31,11 +31,11 @@ There are several ways to enable asyncio debug mode:

* Calling :meth:`loop.set_debug`.

In addition to enabling the debug mode, consider also:
In addition to enabling debug mode, consider also:

* setting the log level of the :ref:`asyncio logger <asyncio-logger>` to
:py:const:`logging.DEBUG`, for example the following snippet of code
can be run at startup of the application::
:py:const:`logging.DEBUG`, such as by running the following snippet of
code at startup of the application::

logging.basicConfig(level=logging.DEBUG)

Expand All @@ -44,7 +44,7 @@ In addition to enabling the debug mode, consider also:
using the :option:`-W` ``default`` command line option.


When the debug mode is enabled:
When debug mode is enabled:

* Many non-threadsafe asyncio APIs (such as :meth:`loop.call_soon` and
:meth:`loop.call_at` methods) raise an exception if they are called
Expand Down Expand Up @@ -95,7 +95,7 @@ To schedule a coroutine object from a different OS thread, the
# Wait for the result:
result = future.result()

To handle signals the event loop must be
To handle signals, the event loop must be
run in the main thread.

The :meth:`loop.run_in_executor` method can be used with a
Expand Down Expand Up @@ -126,10 +126,9 @@ all concurrent asyncio Tasks and IO operations would be delayed
by 1 second.

An executor can be used to run a task in a different thread,
including in a different interpreter, or even in
a different process to avoid blocking the OS thread with the
event loop. See the :meth:`loop.run_in_executor` method for more
details.
a different interpreter, or even a different process to avoid
blocking the OS thread with the event loop. See the
:meth:`loop.run_in_executor` method for more details.


.. _asyncio-logger:
Expand Down Expand Up @@ -260,13 +259,12 @@ This section outlines essential best practices that can save you hours of debugg
Close asynchronous generators explicitly
----------------------------------------

It is recommended to manually close the
It is recommended to manually close an
:term:`asynchronous generator <asynchronous generator iterator>`. If a generator
exits early - for example, due to an exception raised in the body of
an ``async for`` loop - its asynchronous cleanup code may run in an
unexpected context. This can occur after the tasks it depends on have completed,
or during the event loop shutdown when the async-generator's garbage collection
hook is called.
or during the event loop shutdown when the its garbage collection hook is called.

To avoid this, explicitly close the generator by calling its
:meth:`~agen.aclose` method, or use the :func:`contextlib.aclosing`
Expand Down Expand Up @@ -423,8 +421,7 @@ Avoid concurrent iteration and closure of the same generator

Async generators may be reentered while another
:meth:`~agen.__anext__` / :meth:`~agen.athrow` / :meth:`~agen.aclose` call is in
progress. This may lead to an inconsistent state of the async generator and can
cause errors.
progress. This may lead to inconsistent state and can cause errors.

Let's consider the following example::

Expand Down
38 changes: 20 additions & 18 deletions Doc/library/asyncio-queue.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ asyncio queues are designed to be similar to classes of the
they are designed to be used specifically in async/await code.

Note that methods of asyncio queues don't have a *timeout* parameter;
use :func:`asyncio.wait_for` function to do queue operations with a
timeout.
use :func:`asyncio.wait_for` function to perform queue operations with
timeouts.

See also the `Examples`_ section below.
Also see the `Examples`_ section below.

Queue
=====
Expand All @@ -28,7 +28,7 @@ Queue
A first in, first out (FIFO) queue.

If *maxsize* is less than or equal to zero, the queue size is
infinite. If it is an integer greater than ``0``, then
infinite. If it is an integer greater than ``0``, then
``await put()`` blocks when the queue reaches *maxsize*
until an item is removed by :meth:`get`.

Expand All @@ -54,8 +54,9 @@ Queue

Return ``True`` if there are :attr:`maxsize` items in the queue.

If the queue was initialized with ``maxsize=0`` (the default),
then :meth:`full` never returns ``True``.
If the queue was initialized with ``maxsize=0`` (the default)
or a negative ``maxsize``, then :meth:`full` never returns
``True``.

.. method:: get()
:async:
Expand All @@ -77,7 +78,7 @@ Queue
Block until all items in the queue have been received and processed.

The count of unfinished tasks goes up whenever an item is added
to the queue. The count goes down whenever a consumer coroutine calls
to the queue. The count goes down whenever a consumer calls
:meth:`task_done` to indicate that the item was retrieved and all
work on it is complete. When the count of unfinished tasks drops
to zero, :meth:`join` unblocks.
Expand Down Expand Up @@ -109,27 +110,28 @@ Queue
Currently blocked callers of :meth:`~Queue.put` will be unblocked
and will raise :exc:`QueueShutDown` in the formerly awaiting task.

If *immediate* is false (the default), the queue can be wound
If *immediate* is ``False`` (the default), the queue can be wound
down normally with :meth:`~Queue.get` calls to extract tasks
that have already been loaded.

And if :meth:`~Queue.task_done` is called for each remaining task, a
pending :meth:`~Queue.join` will be unblocked normally.
In this case, if :meth:`~Queue.task_done` is called for each
remaining task, a pending :meth:`~Queue.join` will be unblocked
normally.

Once the queue is empty, future calls to :meth:`~Queue.get` will
raise :exc:`QueueShutDown`.

If *immediate* is true, the queue is terminated immediately.
If *immediate* is ``True``, the queue is terminated immediately.
The queue is drained to be completely empty and the count
of unfinished tasks is reduced by the number of tasks drained.
If unfinished tasks is zero, callers of :meth:`~Queue.join`
are unblocked. Also, blocked callers of :meth:`~Queue.get`
are unblocked and will raise :exc:`QueueShutDown` because the
If the count reaches zero, callers of :meth:`~Queue.join` are
unblocked. Also, blocked callers of :meth:`~Queue.get` are
unblocked and will raise :exc:`QueueShutDown` because the
queue is empty.

Use caution when using :meth:`~Queue.join` with *immediate* set
to true. This unblocks the join even when no work has been done
on the tasks, violating the usual invariant for joining a queue.
Exercise caution when using :meth:`~Queue.join` in the above case.
The join may be unblocked even when no work has been done on the
tasks, violating the usual invariant for joining a queue.

.. versionadded:: 3.13

Expand Down Expand Up @@ -212,7 +214,7 @@ concurrent tasks::
# Get a "work item" out of the queue.
sleep_for = await queue.get()

# Sleep for the "sleep_for" seconds.
# Sleep "sleep_for" seconds.
await asyncio.sleep(sleep_for)

# Notify the queue that the "work item" has been processed.
Expand Down
55 changes: 27 additions & 28 deletions Doc/library/asyncio-task.rst
Original file line number Diff line number Diff line change
Expand Up @@ -649,7 +649,7 @@ Eager task factory
Shielding from cancellation
===========================

.. awaitablefunction:: shield(aw)
.. awaitablefunction:: shield(arg)

Protect an :ref:`awaitable object <asyncio-awaitables>`
from being :meth:`cancelled <Task.cancel>`.
Expand Down Expand Up @@ -686,7 +686,7 @@ Shielding from cancellation

.. important::

Save a reference to tasks passed to this function, to avoid
Save a reference to tasks passed to this function to avoid
a task disappearing mid-execution. The event loop only keeps
weak references to tasks. A task that isn't referenced elsewhere
may get garbage collected at any time, even before it's done.
Expand All @@ -708,10 +708,10 @@ Timeouts
that can be used to limit the amount of time spent waiting on
something.

*delay* can either be ``None``, or a float/int number of
seconds to wait. If *delay* is ``None``, no time limit will
be applied; this can be useful if the delay is unknown when
the context manager is created.
*delay* can either be ``None``, or a float/int representing
the number of seconds to wait. If *delay* is ``None``, no time
limit will be applied; this can be useful if the delay is
unknown when the context manager is created.

In either case, the context manager can be rescheduled after
creation using :meth:`Timeout.reschedule`.
Expand Down Expand Up @@ -826,9 +826,9 @@ Timeouts

If *aw* is a coroutine it is automatically scheduled as a Task.

*timeout* can either be ``None`` or a float or int number of seconds
to wait for. If *timeout* is ``None``, block until the future
completes.
*timeout* can either be ``None`` or a float or int representing
the number of seconds to wait for. If *timeout* is ``None``,
block until the future completes.

If a timeout occurs, it cancels the task and raises
:exc:`TimeoutError`.
Expand Down Expand Up @@ -879,14 +879,14 @@ Timeouts
Waiting primitives
==================

.. function:: wait(aws, *, timeout=None, return_when=ALL_COMPLETED)
.. function:: wait(fs, *, timeout=None, return_when=ALL_COMPLETED)
:async:

Run :class:`~asyncio.Future` and :class:`~asyncio.Task` instances in the *aws*
Run :class:`~asyncio.Future` and :class:`~asyncio.Task` instances in the *fs*
iterable concurrently and block until the condition specified
by *return_when*.
by *return_when* is satisfied.

The *aws* iterable must not be empty.
The *fs* iterable must not be empty.

Returns two sets of Tasks/Futures: ``(done, pending)``.

Expand Down Expand Up @@ -928,19 +928,19 @@ Waiting primitives
Removed the *loop* parameter.

.. versionchanged:: 3.11
Passing coroutine objects to ``wait()`` directly is forbidden.
Forbade passing coroutine objects to ``wait()`` directly.

.. versionchanged:: 3.12
Added support for generators yielding tasks.


.. function:: as_completed(aws, *, timeout=None)
.. function:: as_completed(fs, *, timeout=None)

Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws* iterable
Run :ref:`awaitable objects <asyncio-awaitables>` in the *fs* iterable
concurrently. The returned object can be iterated to obtain the results
of the awaitables as they finish.

The object returned by ``as_completed()`` can be iterated as an
The object returned by ``as_completed()`` can be iterated over as an
:term:`asynchronous iterator` or a plain :term:`iterator`. When asynchronous
iteration is used, the originally-supplied awaitables are yielded if they
are tasks or futures. This makes it easy to correlate previously-scheduled
Expand Down Expand Up @@ -985,7 +985,7 @@ Waiting primitives
Removed the *loop* parameter.

.. deprecated:: 3.10
Deprecation warning is emitted if not all awaitable objects in the *aws*
Deprecation warning is emitted if not all awaitable objects in the *fs*
iterable are Future-like objects and there is no running event loop.

.. versionchanged:: 3.12
Expand All @@ -1011,7 +1011,7 @@ Running in threads

Return a coroutine that can be awaited to get the eventual result of *func*.

This coroutine function is primarily intended to be used for executing
This coroutine function is primarily intended to be used to execute
IO-bound functions/methods that would otherwise block the event loop if
they were run in the main thread. For example::

Expand Down Expand Up @@ -1061,13 +1061,13 @@ Scheduling from other threads

.. function:: run_coroutine_threadsafe(coro, loop)

Submit a coroutine to the given event loop. Thread-safe.
Submit a coroutine to the given event loop. Thread-safe.

Return a :class:`concurrent.futures.Future` to wait for the result
from another OS thread.

This function is meant to be called from a different OS thread
than the one where the event loop is running. Example::
than the one where the event loop is running. Example::

def in_thread(loop: asyncio.AbstractEventLoop) -> None:
# Run some blocking IO
Expand All @@ -1089,7 +1089,7 @@ Scheduling from other threads
# Run something in a thread
await asyncio.to_thread(in_thread, loop)

It's also possible to run the other way around. Example::
It's also possible to run the other way around. Example::

@contextlib.contextmanager
def loop_in_thread() -> Generator[asyncio.AbstractEventLoop]:
Expand Down Expand Up @@ -1140,7 +1140,7 @@ Scheduling from other threads
See the :ref:`concurrency and multithreading <asyncio-multithreading>`
section of the documentation.

Unlike other asyncio functions this function requires the *loop*
Unlike other asyncio functions, this function requires the *loop*
argument to be passed explicitly.

.. versionadded:: 3.5.1
Expand Down Expand Up @@ -1225,10 +1225,10 @@ Task object

An optional keyword-only *eager_start* argument allows eagerly starting
the execution of the :class:`asyncio.Task` at task creation time.
If set to ``True`` and the event loop is running, the task will start
If set to ``True`` with the event loop running, the task will start
executing the coroutine immediately, until the first time the coroutine
blocks. If the coroutine returns or raises without blocking, the task
will be finished eagerly and will skip scheduling to the event loop.
will be finished eagerly and the event loop scheduling step is skipped.

.. versionchanged:: 3.7
Added support for the :mod:`contextvars` module.
Expand Down Expand Up @@ -1359,8 +1359,7 @@ Task object
Return the name of the Task.

If no name has been explicitly assigned to the Task, the default
asyncio Task implementation generates a default name during
instantiation.
implementation generates a default name during instantiation.

.. versionadded:: 3.8

Expand Down Expand Up @@ -1514,6 +1513,6 @@ Task object
cancellation requests go down to zero.

This method is used by asyncio's internals and isn't expected to be
used by end-user code. See :meth:`uncancel` for more details.
used by end-user code. See :meth:`uncancel` for more details.

.. versionadded:: 3.11
Loading