Python Async/Await — Asynchronous Programming

Python AdvancedAsyncFree Lesson

Advertisement

Python Async/Await — Asynchronous Programming

Async programming handles thousands of concurrent operations efficiently. It is essential for web servers, API clients, and real-time applications.

Learning Objectives

  • Understand the event loop and coroutines
  • Write async functions with async/await
  • Use asyncio.gather for concurrent operations
  • Build async context managers and generators

Basics

import asyncio

async def greet(name):
    await asyncio.sleep(1)  # Non-blocking sleep
    return f"Hello, {name}"

result = asyncio.run(greet("Alice"))

Concurrent Operations

import asyncio

async def fetch(url):
    print(f"Fetching {url}")
    await asyncio.sleep(2)
    return f"Data from {url}"

async def main():
    urls = ["url1", "url2", "url3"]
    tasks = [fetch(url) for url in urls]
    results = await asyncio.gather(*tasks)
    print(results)

asyncio.run(main())

Async HTTP with aiohttp

import asyncio
import aiohttp

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

async def main():
    urls = ["https://example.com"] * 5
    async with aiohttp.ClientSession() as session:
        tasks = [fetch_url(session, url) for url in urls]
        results = await asyncio.gather(*tasks)
        print(f"Fetched {len(results)} pages")

asyncio.run(main())

Async Context Managers

class AsyncDatabase:
    async def __aenter__(self):
        await self.connect()
        return self

    async def __aexit__(self, *args):
        await self.disconnect()

async def main():
    async with AsyncDatabase() as db:
        await db.execute("SELECT * FROM users")

Key Takeaways

  1. async def defines a coroutine
  2. await pauses until the awaited coroutine completes
  3. asyncio.gather() runs multiple coroutines concurrently
  4. Use for I/O-bound tasks (network, file, database)
  5. Not suitable for CPU-bound tasks (use multiprocessing)

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement