What is Async/Await?

Async/await allows writing asynchronous code that can handle multiple I/O operations concurrently without blocking. Perfect for network requests and file operations.

Basic Syntax

Define async functions:

import asyncio

async def fetch_data():
    await asyncio.sleep(1)  # Simulate I/O
    return "Data fetched"

async def main():
    result = await fetch_data()
    print(result)

asyncio.run(main())

Running Multiple Tasks

Run tasks concurrently:

async def task(name, delay):
    await asyncio.sleep(delay)
    print(f"{name} completed")

async def main():
    await asyncio.gather(
        task("Task 1", 1),
        task("Task 2", 2),
        task("Task 3", 1)
    )

asyncio.run(main())

Async with Requests

Use aiohttp for async HTTP requests:

import aiohttp
import asyncio

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

async def main():
    async with aiohttp.ClientSession() as session:
        html = await fetch_url(session, "https://example.com")
        print(html[:100])

asyncio.run(main())

When to Use

  • I/O-bound operations: Network, files, databases
  • Concurrent tasks: Multiple independent operations
  • Web servers: Handle multiple requests
  • Avoid for CPU-bound: Use multiprocessing instead

Best Practices

  • Use async/await consistently: Don't mix sync and async
  • Use asyncio.gather: For concurrent operations
  • Handle errors: Use try/except in async functions
  • Close resources: Use async context managers

Next Steps

Learn about multithreading and multiprocessing.