Chapter 21. Asynchronous Programming
The problem with normal approaches to asynchronous programming is that they’re all-or-nothing propositions. You rewrite all your code so none of it blocks or you’re just wasting your time.
Alvaro Videla and Jason J. W. Williams, RabbitMQ in Action1
This chapter addresses three major topics that are closely related:
-
Python’s
async def
,await
,async with
, andasync for
constructs -
Objects supporting those constructs: native coroutines and asynchronous variants of context managers, iterables, generators, and comprehensions
-
asyncio and other asynchronous libraries
This chapter builds on the ideas of iterables and generators (Chapter 17, in particular “Classic Coroutines”), context managers (Chapter 18), and general concepts of concurrent programming (Chapter 19).
We’ll study concurrent HTTP clients similar to the ones we saw in Chapter 20, rewritten with native coroutines and asynchronous context managers, using the same HTTPX library as before, but now through its asynchronous API. We’ll also see how to avoid blocking the event loop by delegating slow operations to a thread or process executor.
After the HTTP client examples, we’ll see two simple asynchronous server-side applications,
one of them using the increasingly popular FastAPI framework.
Then
we’ll cover other language constructs enabled by the async/await
keywords:
asynchronous generator functions, asynchronous comprehensions, and asynchronous generator expressions. To emphasize ...
Get Fluent Python, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.