asyncio Basics
Overview
asyncio is the modern standard for writing highly concurrent Python architecture. Unlike Threading (where the OS preemptively switches between threads, causing heavy memory overhead), asyncio uses a single-threaded Event Loop and Cooperative multitasking. You explicitly mark functions with async def and use await to voluntarily yield control back to the event loop while waiting for I/O. This makes it possible to handle tens of thousands of simultaneous network connections (like WebSockets or API endpoints) on a single CPU core.
Syntax
import asyncio
# 'async def' creates a coroutine
async def fetch_data(id):
print(f"Task {id} starting...")
# 'await' explicitly yields control to the Event Loop.
# While this waits, the Event Loop runs other tasks!
await asyncio.sleep(2)
print(f"Task {id} done!")
return id
async def main():
# asyncio.gather runs multiple coroutines concurrently
results = await asyncio.gather(
fetch_data(1),
fetch_data(2)
)
print("All tasks finished:", results)
# Start the Event Loop
asyncio.run(main())Common Pitfalls
- Using synchronous, blocking functions (like
time.sleepor standardrequests.get) inside anasyncfunction. This is catastrophic. Because it is single-threaded, a blocking call freezes the entire Event Loop, stopping all other tasks. You MUST use async-compatible libraries (likeaiohttpinstead ofrequests). - Forgetting to
awaita coroutine. Callingfetch_data(1)simply returns a coroutine object; it does not execute the function until youawaitit.
Interview Questions
Threading is 'preemptive' (the OS aggressively forces thread switching, causing context overhead). asyncio is 'cooperative' (your code cleanly yields control using await). asyncio consumes vastly less memory per task.
Real-World Example
Modern high-performance web frameworks like FastAPI are built natively on asyncio to handle massive traffic loads.
# A typical FastAPI endpoint
@app.get("/users/{user_id}")
async def get_user(user_id: int):
# While waiting for the database query to return,
# the server can process hundreds of other users' requests!
user = await database.fetch(user_id)
return userCheck Your Knowledge
Test your understanding of asyncio Basics with these quick questions.