asyncio is Python’s standard library for asynchronous code. It lets you execute multiple tasks “simultaneously” within a single thread.
Analogy
Synchronous chef: puts the steak on → stands and waits → done → chops the vegetables.
Asynchronous chef: puts the steak on → while it cooks — chops vegetables → puts water on to boil → comes back to the steak.
One thread, multiple things happening at once.
async / await
import asyncio
async def fetch_data(url: str) -> str:
await asyncio.sleep(1) # simulating an HTTP request
return f"Data from {url}"
async def main():
result = await fetch_data("https://api.example.com")
print(result)
asyncio.run(main())
async def— declares a coroutineawait— pauses execution and yields control to the event loopasyncio.run()— starts the event loop
asyncio.gather() — parallel tasks
import asyncio
async def task(name: str, delay: float) -> str:
await asyncio.sleep(delay)
return f"{name} done"
async def main():
# Run three tasks in parallel
results = await asyncio.gather(
task("A", 1.0),
task("B", 0.5),
task("C", 1.5),
)
print(results) # ['A done', 'B done', 'C done']
# Completes in 1.5 sec, not 3.0!
asyncio.run(main())
AsyncAnthropic — example with Claude
import asyncio
import anthropic
client = anthropic.AsyncAnthropic()
async def ask_claude(question: str) -> str:
response = await client.messages.create(
model="claude-sonnet-4-6",
max_tokens=512,
messages=[{"role": "user", "content": question}]
)
return response.content[0].text
async def analyze_batch(texts: list[str]) -> list[str]:
tasks = [ask_claude(f"Summarize: {text}") for text in texts]
return await asyncio.gather(*tasks)
asyncio.run(analyze_batch(["text 1", "text 2", "text 3"]))
asyncio vs threading
| asyncio | threading | |
|---|---|---|
| Model | Single thread, event loop | Multiple threads |
| I/O tasks | ✅ Excellent | ✅ Good |
| CPU tasks | ❌ Poor | ✅ Good |
| Complexity | Medium | Higher (race conditions) |
| API calls | ✅ Ideal | ✅ Works |
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!