Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-124668: Update asyncio doc landing page with examples #125594

Closed
wants to merge 2 commits into from
Closed
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
46 changes: 46 additions & 0 deletions Doc/library/asyncio.rst
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,52 @@ Additionally, there are **low-level** APIs for

.. include:: ../includes/wasm-notavail.rst

.. _asyncio-intro:

As the **Hello World!** example shows, you can start an asynchronous program by
defining a ``async`` function and execute it with :func:`asyncio.run`.


Alternatively, you can start currently asynchronous tasks with
:class:`asyncio.TaskGroup`::

import asyncio

async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)

async def main():
async with asyncio.TaskGroup() as tg:
task1 = tg.create_task(
say_after(1, 'hello'))

task2 = tg.create_task(
say_after(2, 'world'))

asyncio.run(main())

In this case, the asynchronous function ``main`` will invoke another two
*current* tasks via :func:`TaskGroup.create_task`.
All the tasks are awaited before the context manager ``tg`` exits.

``asyncio`` schedules the asynchronous tasks in the :ref:`asyncio-event-loop`.
You can explicitly create one and append tasks into it::

import asyncio

loop = asyncio.get_event_loop()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

-1 on covering low level API and especially the fragile get_event_loop() on the landing page.

Also -1 on using create_task -- we have asyncio.TaskGroup for this.

tasks = [
loop.create_task(say_after(1, "hello")),
loop.create_task(say_after(2, "world"))
]
loop.run_until_complete(asyncio.gather(*tasks))
loop.close()

Here, we use :func:`get_event_loop` to obtain the event loop for cunrret thread.
After appending two asynchronous tasks into the loop, we make the loop wait
until both tasks finish.

.. _asyncio-cli:

.. rubric:: asyncio REPL
Expand Down
Loading