Share E-Book
Scan to open this page

Scan with your phone to open this page

Author: Hattingh, Caleb

Rating No ratings yet

If you're among the Python developers put off by asyncio's complexity, it's time to take another look. Asyncio is complicated because it aims to solve problems in concurrent network programming for both framework and end-user developers. The features you need to consider are a small subset of the whole asyncio API, but picking out the right features is the tricky part. That's where this practical book comes in. Veteran Python developer Caleb Hattingh helps you gain a basic understanding of asyncio's building blocks--enough to get started writing simple event-based programs. You'll learn why asyncio offers a safer alternative to preemptive multitasking (threading) and how this API provides a simpleway to support thousands of simultaneous socket connections. Get a critical comparison of asyncio and threading for concurrent network programming Take an asyncio walk-through, including a quickstart guidefor hitting the ground looping with event-based programming Learn the difference between asyncio features for end-user developers and those for framework developers Understand asyncio's new async/await language syntax, including coroutines and task and future APIs Get detailed case studies (with code) of some popular asyncio-compatible third-party libraries

AI Reading Assistant

Whole-book reading guide from stratified index samples; jump to passages in the text

AI guide
【One-Line Pitch】 A practical, opinionated guide to Python's asyncio for developers who have been intimidated by its sprawling API. If you write networked Python and want to understand when async beats threading—and which small subset of the API actually matters—this book is for you. 【Book Arc】 - **Opening (~0%–10%)**: Frames the core problem—why asyncio exists, why it feels complex, and why it's worth revisiting. Distinguishes end-user developer features from framework designer features. - **Early (~10%–35%)**: A deep dive into threading as the baseline: its benefits, its drawbacks (race conditions, resource cost, reasoning difficulty), and a memorable restaurant "ThreadBot" case study that demonstrates why shared-memory preemptive concurrency is unsafe. - **Middle (~35%–55%)**: The asyncio walk-through. Covers the quickstart (`asyncio.run()`), the "Hello-ish World" that reveals what `run()` does under the hood, the event loop lifecycle, coroutines, `async def`/`await`, tasks and futures, async context managers, async iterators, async generators, and graceful startup/shutdown. - **Late (~55%–80%)**: The "Tower of Asyncio"—a tiered hierarchy of the API from coroutines (Tier 1) up through event loop, futures, tasks, subprocesses/threads, queues, transports, protocols, and streams (Tier 9). Helps readers pick out only the tiers they need. - **Ending (~80%–100%)**: Case studies with code of popular asyncio-compatible third-party libraries, showing how framework designers build on the lower tiers and how end users consume them. 【Key Takeaways】 - **Asyncio solves two specific problems for I/O-bound network workloads** (Early): it offers a safer alternative to preemptive multitasking (threading) by eliminating race conditions, and it supports thousands of simultaneous socket connections with far fewer resources. If your workload isn't I/O-bound network programming, the trade-offs may not favor asyncio. - **Threading's core flaw is non-determinism** (Early): race conditions in threaded programs are the hardest bugs to fix, and the model is intrinsically intractable for nontrivial programs. The cutlery case study shows how even "correct" code produces wrong results under concurrency. - **The asyncio API is a hierarchy, not a flat list** (Middle): the author's "Tower of Asyncio" arranges features into tiers—coroutines at the base, then event loop, futures, tasks, subprocesses/threads, queues, transports, protocols, and streams. End-user developers need only a small subset; framework designers need the hook points. - **`asyncio.run()` handles the boilerplate you'd otherwise write manually** (Middle): it creates the event loop, runs the main coroutine, cancels and gathers pending tasks, and closes the loop. Understanding what it does matters for designing larger applications. - **Coroutines, tasks, and futures are distinct concepts** (Middle): coroutines are the fundamental building block; tasks wrap coroutines for scheduling on the loop; futures represent a result that will arrive later. The book emphasizes understanding the difference rather than memorizing the API. - **Async context managers and async iterators extend familiar Python patterns** (Middle): `async with` and `async for` let you use resource management and iteration in async code, with `contextlib` providing a simpler way to write them. - **Graceful startup and shutdown require explicit handling** (Middle): gathering pending tasks, cancelling them, and waiting for completion is the standard idiom—`asyncio.run()` does this for you, but complex applications may need manual control. - **Real-world asyncio libraries demonstrate the framework designer's perspective** (Ending): case studies with code show how third-party libraries build on asyncio's lower tiers, bridging the gap between the API hierarchy and practical usage. 【Reading Tips】 - **Skim the threading chapters if you already know threading well**, but read the restaurant case study carefully—it's the book's conceptual anchor for why asyncio exists. - **Deep-read the "Tower of Asyncio" section** (Middle): it's the roadmap that makes the rest of the API navigable. Use it to decide which tiers you actually need. - **Type out the interactive coroutine examples yourself** rather than just reading them. The book explicitly urges this, and the low-level interactions become much clearer when you observe the output. - **Don't try to learn the entire asyncio API.** The book's central promise is that you only need a small subset. Focus on coroutines, tasks, the event loop, and the async syntax first; treat transports, protocols, and streams as reference material. - **Pay attention to the end-user vs. framework designer distinction** throughout. It will save you from over-engineering and help you recognize which documentation sections are relevant to your work. 【Coverage Limits】 The excerpts cover the book's structure, core arguments, and the asyncio walk-through in detail, but do not include the full code of the third-party library case studies or the complete text of every chapter. Specific implementation details of later chapters are only partially represented.
Excerpt 1
tions Editor: Jessica Haberman Indexer: Ellen Troutman-Zaig Developmental Editor: Corbin Collins Interior Designer: David Futato Production Editor: Beth Kell...
View in text
Page 15
fully utilized. The moment passes, but not the realization. On Sunday, you add a data collection module to your ThreadBots. For each ThreadBot, you’re measur...
View in text
Excerpt 3
dBot(threading.Thread): def __init__(self): super().__init__(target=self.manage_table) self.cutlery = Cutlery(knives=0, forks=0) self.tasks = Queue() def man...
View in text
Excerpt 4
is means that the asyncio API can appear somewhat sprawling. I hope that this section has provided enough of a road map to help you pick out the parts you ne...
View in text
Excerpt 5
, exactly as set out in “Quickstart” on page 22. The Future class is actually a superclass of Task, and it provides all of the functionality for inter‐ actio...
View in text
Excerpt 6
continue, it will be best if you can convince yourself that • Coroutines and generators are completely different concepts. • Async generators behave much lik...
View in text
Excerpt 7
r process. The remainder of the code is the same as before. Here’s the output: $ python shell_signal02.py <Your app is running> <Your app is running> <Your a...
View in text
Excerpt 8
channel name they’re subscribing to. A deque will hold all the subscribers for a particular channel. The client() coroutine function will produce a long-live...
View in text
Tags
AI categories
PythonProgramming LanguageBackend
ISBN: 1492075337
Publisher: O'Reilly Media
Publish Year: 2020
Language: English
Pages: 163
File Format: PDF
File Size: 5.8 MB
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Generating text preview…