课程 · 12 · 08 / 12
Async/Await Fundamentals: Non-Blocking Python
Understand event loops and coroutines. Write async code with asyncio, handle concurrent I/O, and build async patterns for production.
TIPLearning Objectives: After this lesson, you'll understand event loops and coroutines, write async code with asyncio, handle concurrent I/O operations, and build async patterns for production applications.
Understanding Async Programming
Async programming allows handling many I/O operations concurrently without threads. Let's visualize the event loop:
The event loop runs coroutines one at a time. When one hits await, it pauses and another can run. This is cooperative multitasking.
The Problem with Blocking I/O
Async Solution Preview
Coroutines and async def
await Keyword
Concurrent Execution
asyncio.gather - Run Multiple Coroutines
asyncio.create_task - Background Tasks
asyncio.wait - Advanced Control
asyncio.as_completed - Process as They Finish
Error Handling
Timeouts and Cancellation
Async Context Managers and Iterators
Async Generators
Practical Patterns
Semaphore - Rate Limiting
Queue-based Worker Pool
Async HTTP Requests (aiohttp pattern)
Practice Exercises
Exercise 1: Async Retry with Backoff
Exercise 2: Async Resource Pool
Key Takeaways
| Concept | Description |
|---|---|
| Coroutine | Function defined with async def |
| await | Pause and wait for async operation |
| Event Loop | Manages all async operations |
| Task | Scheduled coroutine for concurrent execution |
| gather | Run multiple coroutines concurrently |
| Semaphore | Limit concurrent operations |
| Queue | Async producer-consumer pattern |
When to Use Async
| Scenario | Use Async? |
|---|---|
| Many network requests | Yes |
| Database queries | Yes (with async driver) |
| File I/O | Maybe (use aiofiles) |
| CPU-heavy work | No (use multiprocessing) |
| Real-time events | Yes |
| Simple scripts | Usually overkill |
Next Steps
In the next lesson, we'll explore Testing Best Practices—master pytest with fixtures, parametrization, and mocking, learn TDD, and write maintainable tests.
Ready to write bulletproof code? Testing awaits!
Further Reading
Required Reading
asyncio— official Python docs — start here.- Real Python — Async IO in Python — the canonical full walkthrough.
- FastAPI — Concurrency and async/await — the clearest practical explanation of when to use
async. Required reading before you write your first async API.
Foundational Talks & Articles
- David Beazley — Build Your Own Async — builds an async framework from scratch on stage. Best way to understand event loops.
- Nathaniel Smith — Notes on structured concurrency — the article that inspired Python's
TaskGroup(3.11+) and thetriolibrary. - Łukasz Langa — Async Pitfalls — what to avoid in production async code.
Modern Async Stack
asyncio.TaskGroup— Python 3.11's structured concurrency primitive. Use this instead of baregather.trio— alternative async framework with first-class structured concurrency.anyio— write code that runs on bothasyncioandtrio. The async library library.httpx— sync + async HTTP. The modernrequests.aiohttp— battle-tested async HTTP server + client.asyncpg— fastest async PostgreSQL driver in any language.
Books
- Book: Fluent Python (2nd ed.) — Chapters 19 ("Concurrency Models") and 21 ("Asynchronous Programming"). Best treatment in print.
- Book: Python Concurrency with asyncio — Matthew Fowler. Whole book on the topic.