Async / Await & asyncio
Write non-blocking code with async/await, asyncio.gather, asyncio.Queue, async context managers, and async generators.
Part 1: What You Will Learn
- Define coroutines with
async def. - Pause without blocking by using
await. - Run independent tasks concurrently with
asyncio.gather(). - Coordinate producers and consumers with
asyncio.Queue.
Part 2: Key Concepts
Asynchronous programming is most useful for I/O-bound work such as network requests, database calls, and waiting for files. While one coroutine waits, the event loop can run another coroutine on the same thread.
Part 3: Topic-Specific Code Example
import asyncio
async def fetch_order(order_id: int) -> dict[str, object]:
print(f"Fetching order {order_id}...")
await asyncio.sleep(1) # Simulates a non-blocking I/O wait
return {"id": order_id, "total": order_id * 25.50}
async def producer(queue: asyncio.Queue[int | None]) -> None:
for order_id in range(1, 4):
await queue.put(order_id)
await queue.put(None)
async def consumer(queue: asyncio.Queue[int | None]) -> None:
while True:
order_id = await queue.get()
try:
if order_id is None:
return
order = await fetch_order(order_id)
print("Processed:", order)
finally:
queue.task_done()
async def main() -> None:
print("Concurrent gather:")
orders = await asyncio.gather(
fetch_order(10), fetch_order(11), fetch_order(12)
)
print(orders)
print("\nQueue pipeline:")
queue: asyncio.Queue[int | None] = asyncio.Queue()
await asyncio.gather(producer(queue), consumer(queue))
if __name__ == "__main__":
asyncio.run(main())Part 4: How the Example Works
await asyncio.sleep() represents a non-blocking wait. gather() starts several independent coroutines and waits for all results. The queue example shows a common producer/consumer pattern in which one coroutine creates work and another processes it.
Part 5: Hands-On Practice
Mini project โ Concurrent Student Lookup. Simulate five remote student-record lookups with different asyncio.sleep() delays. Compare sequential await calls with asyncio.gather() and measure the total time with time.perf_counter().
Part 6: Next Steps
Run and modify the examples in Visual Studio 2026, then continue to Lesson 17. Return to Python Tutorial Home to review the complete curriculum.