๐Ÿ“ LLM & AI

asyncio in Python: Asynchronous Programming

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
317
๐ŸŒฟ
Level
Medium

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 coroutine
  • await โ€” pauses execution and yields control to the event loop
  • asyncio.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

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

httpx: A Modern HTTP Client for Python

httpx is a next-generation HTTP client. Its interface is similar to requests, but it supports...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 329
๐Ÿ“

AI Agents: ReAct Loop and Autonomous Actions

A chatbot answers questions. An agent takes action: it calls tools, retrieves real data, and...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 334
๐Ÿ“

Pydantic v2: Data Validation in Python

Pydantic validates and converts data through type annotations. It is commonly used in APIs and...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 327