Ad – 728Γ—90
πŸš€ Advanced Python

Python Async Programming – asyncio, async/await Explained

Async programming lets a single thread handle thousands of concurrent I/O operations without blocking. Instead of waiting idle for a network request, an async program switches to other work. Python's asyncio library and async/await syntax make this efficient and readable.

⏱️ 25 min read🎯 AdvancedπŸ“… Updated 2026

async def and await – The Basics

async def creates a coroutine function. await suspends execution until the awaited operation completes.

Python
import asyncio

async def greet(name, delay):
    await asyncio.sleep(delay)  # Non-blocking wait
    print(f"Hello, {name}!")

async def main():
    # Run sequentially: takes 3s
    await greet("Alice", 1)
    await greet("Bob", 2)

asyncio.run(main())
β–Ά Output
Hello, Alice! Hello, Bob!

asyncio.gather – True Concurrency

Run multiple coroutines concurrently with asyncio.gather().

Python
import asyncio
import time

async def fetch(url, delay):
    await asyncio.sleep(delay)  # Simulate network I/O
    return f"Response from {url}"

async def main():
    start = time.time()

    # All three run concurrently β€” total ~2s not 6s
    results = await asyncio.gather(
        fetch("api.com/users", 2),
        fetch("api.com/posts", 1),
        fetch("api.com/data",  2)
    )

    for r in results:
        print(r)
    print(f"Done in {time.time()-start:.1f}s")

asyncio.run(main())
β–Ά Output
Response from api.com/users Response from api.com/posts Response from api.com/data Done in 2.0s

asyncio.create_task – Background Tasks

Tasks run in the background. Useful for fire-and-forget operations.

Python
import asyncio

async def background_worker():
    while True:
        print("Background: heartbeat")
        await asyncio.sleep(5)

async def main():
    task = asyncio.create_task(background_worker())

    # Do other work while background runs
    await asyncio.sleep(0)   # Yield control
    print("Main: doing work")
    task.cancel()            # Stop background

asyncio.run(main())
Ad – 336Γ—280

Real Async HTTP with aiohttp

Use aiohttp for async HTTP requests. Dramatically faster than requests for concurrent fetching.

Python
# pip install aiohttp
import asyncio
import aiohttp

async def fetch_url(session, url):
    async with session.get(url) as response:
        return await response.json()

async def main():
    urls = [
        "https://api.github.com/users/python",
        "https://api.github.com/users/torvalds"
    ]
    async with aiohttp.ClientSession() as session:
        tasks = [fetch_url(session, url) for url in urls]
        results = await asyncio.gather(*tasks)
    for r in results:
        print(r["login"])

asyncio.run(main())
β–Ά Output
python torvalds