📝 LLM & AI

asyncio in Python: Asynchronous Programming

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
83
🌿
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

📝

Event Loop in Python: How asyncio Achieves "Paral…

Event loop is the heart of asyncio. It doesn't run code in parallel across multiple...

📅 30.06.2026 👁️ 123
📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 132
📝

pip: Python Package Manager

Охватываемые темы: Installing packages, Upgrading and removing, requirements.txt, Virtual environment.

📅 30.06.2026 👁️ 120

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!