async-patterns
Installation
SKILL.md
Python Async/Await Patterns
Overview
Use asynchronous programming for I/O-bound work: network requests, database queries, file operations, and inter-process communication. These operations spend most of their time waiting, and asyncio allows other work to proceed during that wait.
Use synchronous (or multiprocessing-based) code for CPU-bound work: image processing, cryptographic hashing, data compression, and heavy computation. The Python GIL prevents true parallel execution of Python bytecode in threads, so CPU-bound work does not benefit from asyncio.
A useful heuristic: if the bottleneck is waiting, go async. If the bottleneck is computing, use multiprocessing or a task queue.
Core Concepts
Three building blocks underpin all async Python code:
- Coroutine -- a function declared with
async def. Calling it returns a coroutine object that must be awaited or scheduled. - Event loop -- the scheduler that runs coroutines, handles I/O callbacks, and manages timers.
asyncio.run()creates and manages the loop. - Awaitable -- anything that can appear after
await: coroutines,Taskobjects, andFutureobjects.