⚡

How to Use async/await in Python

PythonAdvanced

Write asynchronous code with async/await.

Code Example

Python
import asyncio

# Async function
async def say_hello():
    print("Hello")
    await asyncio.sleep(1)
    print("World")

# Run async function
asyncio.run(say_hello())

# Multiple async tasks
async def task1():
    await asyncio.sleep(1)
    return "Task 1 done"

async def task2():
    await asyncio.sleep(2)
    return "Task 2 done"

async def main():
    # Run tasks concurrently
    results = await asyncio.gather(task1(), task2())
    print(results)

asyncio.run(main())

# Async generator
async def async_range(n):
    for i in range(n):
        await asyncio.sleep(0.1)
        yield i

async def consume():
    async for i in async_range(5):
        print(i, end=" ")
    print()

asyncio.run(consume())

# Async context manager
class AsyncTimer:
    async def __aenter__(self):
        import time
        self.start = time.time()
        return self
    
    async def __aexit__(self, exc_type, exc_val, exc_tb):
        import time
        print(f"\nElapsed: {time.time() - self.start:.2f}s")

async def timed_task():
    async with AsyncTimer():
        await asyncio.sleep(1)

asyncio.run(timed_task())

# Async iteration
class AsyncCounter:
    def __init__(self, limit):
        self.limit = limit
        self.current = 0
    
    def __aiter__(self):
        return self
    
    async def __anext__(self):
        if self.current >= self.limit:
            raise StopAsyncIteration
        await asyncio.sleep(0.1)
        self.current += 1
        return self.current

async def count():
    async for i in AsyncCounter(5):
        print(i, end=" ")
    print()

asyncio.run(count())

Explanation

async def creates coroutine. await pauses execution. asyncio.run() starts event loop. gather() runs tasks concurrently. Use for I/O-bound operations.

Related Tutorials