Async/Await

Asynchronous programming with asyncio for concurrent operations

#async #await #asyncio #concurrency

Async/Await

Write asynchronous code in Python using async/await syntax.

Basic Async Function

import asyncio

async def greet(name):
    print(f"Hello, {name}!")
    await asyncio.sleep(1)
    print(f"Goodbye, {name}!")

# Run async function
asyncio.run(greet("Alice"))

Multiple Concurrent Tasks

import asyncio

async def fetch_data(id, delay):
    print(f"Fetching data {id}...")
    await asyncio.sleep(delay)
    return f"Data {id}"

async def main():
    # Run tasks concurrently
    results = await asyncio.gather(
        fetch_data(1, 2),
        fetch_data(2, 1),
        fetch_data(3, 3)
    )
    print(results)  # ['Data 1', 'Data 2', 'Data 3']

asyncio.run(main())

Async with Timeout

import asyncio

async def slow_operation():
    await asyncio.sleep(5)
    return "Done"

async def main():
    try:
        result = await asyncio.wait_for(slow_operation(), timeout=2.0)
        print(result)
    except asyncio.TimeoutError:
        print("Operation timed out!")

asyncio.run(main())

Async Context Manager

import asyncio

class AsyncResource:
    async def __aenter__(self):
        print("Acquiring resource")
        await asyncio.sleep(1)
        return self

    async def __aexit__(self, exc_type, exc, tb):
        print("Releasing resource")
        await asyncio.sleep(1)

    async def do_work(self):
        print("Working...")
        await asyncio.sleep(1)

async def main():
    async with AsyncResource() as resource:
        await resource.do_work()

asyncio.run(main())

Async Generators

import asyncio

async def async_range(count):
    for i in range(count):
        await asyncio.sleep(0.1)
        yield i

async def main():
    async for num in async_range(5):
        print(num)  # 0, 1, 2, 3, 4

asyncio.run(main())

Task Management

import asyncio

async def worker(name, queue):
    while True:
        task = await queue.get()
        if task is None:
            break
        print(f"{name} processing {task}")
        await asyncio.sleep(1)
        queue.task_done()

async def main():
    queue = asyncio.Queue()

    # Create workers
    tasks = []
    for i in range(3):
        task = asyncio.create_task(worker(f"Worker-{i}", queue))
        tasks.append(task)

    # Add work items
    for item in range(10):
        await queue.put(item)

    # Wait for all tasks to complete
    await queue.join()

    # Stop workers
    for _ in range(3):
        await queue.put(None)

    await asyncio.gather(*tasks)

asyncio.run(main())

Discover another handy tool from EditPDF.pro