Python 24-Day Course - Day 23: Asynchronous Programming

Day 23: Asynchronous Programming

What Is Asynchronous?

Synchronous code waits until a task completes, while asynchronous code performs other tasks during the wait time.

async/await Basics

import asyncio

async def say_hello(name, delay):
    await asyncio.sleep(delay)
    print(f"Hello, {name}! (after {delay}s)")

async def main():
    # Sequential execution: 3 seconds
    await say_hello("Alice", 1)
    await say_hello("Bob", 2)

asyncio.run(main())

Concurrent Execution: gather

async def main():
    # Concurrent execution: 2 seconds (based on the longest task)
    await asyncio.gather(
        say_hello("Alice", 1),
        say_hello("Bob", 2),
        say_hello("Charlie", 1.5),
    )

asyncio.run(main())

Synchronous vs Asynchronous Comparison

ItemSynchronousAsynchronous
Keyworddefasync def
Callfunc()await func()
WaitingBlockingNon-blocking
I/O tasksSequentialConcurrent
Best forCPU computationNetwork, file I/O

Asynchronous HTTP Requests

import aiohttp
import asyncio

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

async def fetch_all(urls):
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        results = await asyncio.gather(*tasks)
        return results

urls = [
    "https://jsonplaceholder.typicode.com/posts/1",
    "https://jsonplaceholder.typicode.com/posts/2",
    "https://jsonplaceholder.typicode.com/posts/3",
]

results = asyncio.run(fetch_all(urls))
for r in results:
    print(r["title"])

Async Context Manager

class AsyncTimer:
    def __init__(self, name):
        self.name = name

    async def __aenter__(self):
        self.start = asyncio.get_event_loop().time()
        return self

    async def __aexit__(self, *args):
        elapsed = asyncio.get_event_loop().time() - self.start
        print(f"{self.name}: {elapsed:.2f}s")

async def main():
    async with AsyncTimer("API call"):
        await asyncio.sleep(1)

asyncio.run(main())

Today’s Exercises

  1. Make 5 URL requests concurrently, measure response times, and compare with sequential execution.
  2. Use async file reading (aiofiles) to read multiple files concurrently.
  3. Implement an async producer-consumer pattern using asyncio.Queue.

Was this article helpful?