← Back to Pull requests

rewrite asyncio howto doc #21

Open
kumaraditya303 opened this pull request with 1367 lines diff across 5 files
View on GitHub
kumaraditya303 kumaraditya303 commented on Nov 29, 2026 14:04 UTC
Author

<!--
Thanks for your contribution!
Please read this comment in its entirety. It's quite important.

Pull Request title

It should be in the following format:

gh-NNNNNN: Summary of the changes made

Where: gh-NNNNNN refers to the GitHub issue number.

Most PRs will require an issue number. Trivial changes, like fixing a typo, do not need an issue.

Backport Pull Request title

If this is a backport PR (PR made against branches other than main),
please ensure that the PR title is in the following format:

[X.Y] <title from the original PR> (GH-NNNNNN)

Where: [X.Y] is the branch name, for example: [3.13].

GH-NNNNNN refers to the PR number from main.

-->

Diff: 1367 lines (+744 / -623) across 5 files Reviewer: willingc Review duration: 4661m
All Vouch review confidence checks passed
Residual risk 0.05 = Change Risk (0.49) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.49 · 1367 lines diff across 5 files
0.49
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.89 · 4 substantive comment(s)
0.89
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
89%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Real PR Conversation Timeline
6 items
willingc willingc commented on code on Nov 30, 2026 15:51 UTC
Code Review
Doc/howto/asyncio.rst:1
@@ -0,0 +1,738 @@
+.. currentmodule:: asyncio
+
+.. _asyncio-howto:
+
+*************************
+How :mod:`!asyncio` works
+*************************
+
+The :mod:`asyncio` module facilitates writing high-performance concurrent
+code. By leveraging the :keyword:`async`/:keyword:`await` syntax, it
+provides a high-level API for creating and managing event loops,
+coroutines and tasks, and for performing asynchronous I/O operations. It
+is used as a foundation for Python asynchronous frameworks that provide
+high-performance network and web servers, database connection libraries,
+distributed task queues, etc.
+
+In this :ref:`HOWTO <how-tos>`, we will explore how asyncio works
+internally: how the event loop schedules tasks, how coroutines, futures
+and tasks relate to each other, and what happens when a coroutine awaits
+on something. It is not an introduction to writing asyncio programs, for
+that see :ref:`coroutine` and the rest of the :mod:`asyncio`
+documentation.
+
+.. seealso::
+
+   `Scaling asyncio on Free-Threaded Python
+   <https://labs.quansight.org/blog/scaling-asyncio-on-free-threaded-python>`__,
+   a blog post by Kumar Aditya which explains the state asyncio keeps
+   for each thread running an event loop and the changes that allow
+   asyncio to scale across multiple threads.
+
+   `500 Lines or Less: A Web Crawler With asyncio Coroutines
+   <https://aosabook.org/en/500L/a-web-crawler-with-asyncio-coroutines.html>`__
+   by A. Jesse Jiryu Davis and Guido van Rossum, which builds an event
+   loop and coroutines from scratch.
+
+
+The event loop
+==============
+
+asyncio uses an event loop as a scheduler to enable highly efficient
+I/O-bound concurrency by switching between tasks during non-blocking I/O
+operations. All the tasks of an event loop run in a single thread. When
+the running task has to wait for something, such as a response from the
+network, the event loop switches to another task which is ready to run.
+
+The following program simulates downloading three pages. Each download
+spends most of its time waiting, which is simulated here using
+:func:`asyncio.sleep`::
+
+   import asyncio
+   import time
+
+   async def fetch(name, delay):

Perhaps add a one line docstring that explicitly mentions the delay

willingc willingc commented on code on Nov 30, 2026 15:56 UTC
Code Review
Doc/howto/asyncio.rst:1
@@ -0,0 +1,738 @@
+.. currentmodule:: asyncio
+
+.. _asyncio-howto:
+
+*************************
+How :mod:`!asyncio` works
+*************************
+
+The :mod:`asyncio` module facilitates writing high-performance concurrent
+code. By leveraging the :keyword:`async`/:keyword:`await` syntax, it
+provides a high-level API for creating and managing event loops,
+coroutines and tasks, and for performing asynchronous I/O operations. It
+is used as a foundation for Python asynchronous frameworks that provide
+high-performance network and web servers, database connection libraries,
+distributed task queues, etc.
+
+In this :ref:`HOWTO <how-tos>`, we will explore how asyncio works
+internally: how the event loop schedules tasks, how coroutines, futures
+and tasks relate to each other, and what happens when a coroutine awaits
+on something. It is not an introduction to writing asyncio programs, for
+that see :ref:`coroutine` and the rest of the :mod:`asyncio`
+documentation.
+
+.. seealso::
+
+   `Scaling asyncio on Free-Threaded Python
+   <https://labs.quansight.org/blog/scaling-asyncio-on-free-threaded-python>`__,
+   a blog post by Kumar Aditya which explains the state asyncio keeps
+   for each thread running an event loop and the changes that allow
+   asyncio to scale across multiple threads.
+
+   `500 Lines or Less: A Web Crawler With asyncio Coroutines
+   <https://aosabook.org/en/500L/a-web-crawler-with-asyncio-coroutines.html>`__
+   by A. Jesse Jiryu Davis and Guido van Rossum, which builds an event
+   loop and coroutines from scratch.
+
+
+The event loop
+==============
+
+asyncio uses an event loop as a scheduler to enable highly efficient
+I/O-bound concurrency by switching between tasks during non-blocking I/O
+operations. All the tasks of an event loop run in a single thread. When
+the running task has to wait for something, such as a response from the
+network, the event loop switches to another task which is ready to run.
+
+The following program simulates downloading three pages. Each download
+spends most of its time waiting, which is simulated here using
+:func:`asyncio.sleep`::
+
+   import asyncio
+   import time
+
+   async def fetch(name, delay):
+       print(f"{name}: request sent")
+       await asyncio.sleep(delay)  # Stand-in for waiting on the network.
+       print(f"{name}: response received")
+       return f"<page {name}>"
+
+   async def main():
+       start = time.perf_counter()
+       pages = await asyncio.gather(
+           fetch("a", 2),
+           fetch("b", 1),
+           fetch("c", 3),
+       )
+       print(pages)
+       print(f"took {time.perf_counter() - start:.1f} seconds")
+
+   asyncio.run(main())
+
+.. code-block:: none
+
+   a: request sent
+   b: request sent
+   c: request sent
+   b: response received
+   a: response received
+   c: response received
+   ['<page a>', '<page b>', '<page c>']
+   took 3.0 seconds
+
+The three downloads took 3 seconds in total, which is the time taken by

It may make sense to explicitly explain all three fetches. Then, when the delay ends for fetch("b", 1) it returns its response after 1 second. Then a after 2 seconds and c after 3 seconds. gather collects all the results into the pages list. The list is printed and the total run duration.

willingc willingc commented on code on Nov 30, 2026 15:58 UTC
Code Review
Doc/howto/asyncio.rst:1
@@ -0,0 +1,738 @@
+.. currentmodule:: asyncio
+
+.. _asyncio-howto:
+
+*************************
+How :mod:`!asyncio` works
+*************************
+
+The :mod:`asyncio` module facilitates writing high-performance concurrent
+code. By leveraging the :keyword:`async`/:keyword:`await` syntax, it
+provides a high-level API for creating and managing event loops,
+coroutines and tasks, and for performing asynchronous I/O operations. It
+is used as a foundation for Python asynchronous frameworks that provide
+high-performance network and web servers, database connection libraries,
+distributed task queues, etc.
+
+In this :ref:`HOWTO <how-tos>`, we will explore how asyncio works
+internally: how the event loop schedules tasks, how coroutines, futures
+and tasks relate to each other, and what happens when a coroutine awaits
+on something. It is not an introduction to writing asyncio programs, for
+that see :ref:`coroutine` and the rest of the :mod:`asyncio`
+documentation.
+
+.. seealso::
+
+   `Scaling asyncio on Free-Threaded Python
+   <https://labs.quansight.org/blog/scaling-asyncio-on-free-threaded-python>`__,
+   a blog post by Kumar Aditya which explains the state asyncio keeps
+   for each thread running an event loop and the changes that allow
+   asyncio to scale across multiple threads.
+
+   `500 Lines or Less: A Web Crawler With asyncio Coroutines
+   <https://aosabook.org/en/500L/a-web-crawler-with-asyncio-coroutines.html>`__
+   by A. Jesse Jiryu Davis and Guido van Rossum, which builds an event
+   loop and coroutines from scratch.
+
+
+The event loop
+==============
+
+asyncio uses an event loop as a scheduler to enable highly efficient
+I/O-bound concurrency by switching between tasks during non-blocking I/O
+operations. All the tasks of an event loop run in a single thread. When
+the running task has to wait for something, such as a response from the
+network, the event loop switches to another task which is ready to run.
+
+The following program simulates downloading three pages. Each download
+spends most of its time waiting, which is simulated here using
+:func:`asyncio.sleep`::
+
+   import asyncio
+   import time
+
+   async def fetch(name, delay):
+       print(f"{name}: request sent")
+       await asyncio.sleep(delay)  # Stand-in for waiting on the network.
+       print(f"{name}: response received")
+       return f"<page {name}>"
+
+   async def main():
+       start = time.perf_counter()
+       pages = await asyncio.gather(
+           fetch("a", 2),
+           fetch("b", 1),
+           fetch("c", 3),
+       )
+       print(pages)
+       print(f"took {time.perf_counter() - start:.1f} seconds")
+
+   asyncio.run(main())
+
+.. code-block:: none
+
+   a: request sent
+   b: request sent
+   c: request sent
+   b: response received
+   a: response received
+   c: response received
+   ['<page a>', '<page b>', '<page c>']
+   took 3.0 seconds
+
+The three downloads took 3 seconds in total, which is the time taken by
+the slowest one, instead of the 6 seconds it would take to run them one
+after another. When ``fetch("a", 2)`` reached its ``await``, the event
+loop switched to ``fetch("b", 1)`` and so on.
+
+It is important to understand that the event loop is a *cooperative*
+scheduler. The operating system can interrupt a thread at any point to
+run another one, however the event loop never interrupts a running task.
+A task runs until it suspends by awaiting on something, and only then
+the event loop gets to run the next task.
+
+For scheduling, the event loop primarily stores three pieces of state:
+
+1. **Ready queue**: The callbacks which are ready to be executed.
+
+2. **Timers**: The callbacks which are scheduled to be executed at a
+   later time, ordered by the time at which they are due.
+
+3. **I/O**: The file descriptors, mostly sockets, which the event loop
+   is monitoring, along with the callbacks to be executed when they
+   become readable or writable.
+
+When the event loop is running, it repeats the following steps:
+
+1. Compute the timeout for waiting on I/O. If there are callbacks in the
+   ready queue then the timeout is zero, otherwise it is the time
+   remaining until the earliest timer is due.

   ready queue then the timeout is zero. Otherwise, the timeout is the time
   remaining until the earliest timer is due.

willingc willingc commented on code on Nov 30, 2026 16:02 UTC
Code Review
Doc/howto/asyncio.rst:1
@@ -0,0 +1,738 @@
+.. currentmodule:: asyncio
+
+.. _asyncio-howto:
+
+*************************
+How :mod:`!asyncio` works
+*************************
+
+The :mod:`asyncio` module facilitates writing high-performance concurrent
+code. By leveraging the :keyword:`async`/:keyword:`await` syntax, it
+provides a high-level API for creating and managing event loops,
+coroutines and tasks, and for performing asynchronous I/O operations. It
+is used as a foundation for Python asynchronous frameworks that provide
+high-performance network and web servers, database connection libraries,
+distributed task queues, etc.
+
+In this :ref:`HOWTO <how-tos>`, we will explore how asyncio works
+internally: how the event loop schedules tasks, how coroutines, futures
+and tasks relate to each other, and what happens when a coroutine awaits
+on something. It is not an introduction to writing asyncio programs, for
+that see :ref:`coroutine` and the rest of the :mod:`asyncio`
+documentation.
+
+.. seealso::
+
+   `Scaling asyncio on Free-Threaded Python
+   <https://labs.quansight.org/blog/scaling-asyncio-on-free-threaded-python>`__,
+   a blog post by Kumar Aditya which explains the state asyncio keeps
+   for each thread running an event loop and the changes that allow
+   asyncio to scale across multiple threads.
+
+   `500 Lines or Less: A Web Crawler With asyncio Coroutines
+   <https://aosabook.org/en/500L/a-web-crawler-with-asyncio-coroutines.html>`__
+   by A. Jesse Jiryu Davis and Guido van Rossum, which builds an event
+   loop and coroutines from scratch.
+
+
+The event loop
+==============
+
+asyncio uses an event loop as a scheduler to enable highly efficient
+I/O-bound concurrency by switching between tasks during non-blocking I/O
+operations. All the tasks of an event loop run in a single thread. When
+the running task has to wait for something, such as a response from the
+network, the event loop switches to another task which is ready to run.
+
+The following program simulates downloading three pages. Each download
+spends most of its time waiting, which is simulated here using
+:func:`asyncio.sleep`::
+
+   import asyncio
+   import time
+
+   async def fetch(name, delay):
+       print(f"{name}: request sent")
+       await asyncio.sleep(delay)  # Stand-in for waiting on the network.
+       print(f"{name}: response received")
+       return f"<page {name}>"
+
+   async def main():
+       start = time.perf_counter()
+       pages = await asyncio.gather(
+           fetch("a", 2),
+           fetch("b", 1),
+           fetch("c", 3),
+       )
+       print(pages)
+       print(f"took {time.perf_counter() - start:.1f} seconds")
+
+   asyncio.run(main())
+
+.. code-block:: none
+
+   a: request sent
+   b: request sent
+   c: request sent
+   b: response received
+   a: response received
+   c: response received
+   ['<page a>', '<page b>', '<page c>']
+   took 3.0 seconds
+
+The three downloads took 3 seconds in total, which is the time taken by
+the slowest one, instead of the 6 seconds it would take to run them one
+after another. When ``fetch("a", 2)`` reached its ``await``, the event
+loop switched to ``fetch("b", 1)`` and so on.
+
+It is important to understand that the event loop is a *cooperative*
+scheduler. The operating system can interrupt a thread at any point to
+run another one, however the event loop never interrupts a running task.
+A task runs until it suspends by awaiting on something, and only then
+the event loop gets to run the next task.
+
+For scheduling, the event loop primarily stores three pieces of state:
+
+1. **Ready queue**: The callbacks which are ready to be executed.
+
+2. **Timers**: The callbacks which are scheduled to be executed at a
+   later time, ordered by the time at which they are due.
+
+3. **I/O**: The file descriptors, mostly sockets, which the event loop
+   is monitoring, along with the callbacks to be executed when they
+   become readable or writable.
+
+When the event loop is running, it repeats the following steps:
+
+1. Compute the timeout for waiting on I/O. If there are callbacks in the
+   ready queue then the timeout is zero, otherwise it is the time
+   remaining until the earliest timer is due.
+
+2. Wait for the monitored sockets to become ready, for at most the
+   computed timeout. The event loop leverages platform-specific support
+   for asynchronous I/O, such as ``epoll`` on Linux, ``kqueue`` on macOS,
+   and ``IOCP`` on Windows, to perform this efficiently. This is the only
+   place where the event loop blocks, so when there is nothing to do the
+   thread sleeps here without using any CPU time.
+
+3. Add the callbacks of the sockets which are ready and of the timers
+   which are due to the ready queue.
+
+4. Execute the callbacks in the ready queue one by one. Callbacks which
+   get scheduled while this step is running are executed in the next
+   iteration.
+
+Callbacks can be scheduled directly using :meth:`loop.call_soon` and
+:meth:`loop.call_later`::
+
+   import asyncio
+
+   loop = asyncio.new_event_loop()
+   loop.call_later(0.2, print, "third (timer)")
+   loop.call_soon(print, "first")
+   loop.call_soon(print, "second")
+   loop.call_later(0.3, loop.stop)
+   loop.run_forever()
+   loop.close()
+
+.. code-block:: none
+
+   first
+   second
+   third (timer)
+
+Note that the event loop only executes callbacks, which are regular
+functions, and it has no knowledge of coroutines.
+
+The event loop is rarely created manually as in the example above.

In practice, the event loop is rarely created manually as in the example above.

willingc willingc commented on Nov 30, 2026 16:04 UTC
Reviewer

@kumaraditya303 This looks fantastic. I've reviewed the first section up until Coroutines. I will review the rest later today. Clear and accurate. Thanks!

Reviewers
Assignees
kumaraditya303 kumaraditya303
Labels
risk: low confidence: 89.1% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 48.9% (MEDIUM) · Higher = larger blast radius
48.9%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 89.1% · Lower = rushed or shallow review
89.1%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 5.3% · Safe to merge
5.3%