Python7 min read

Python Async/Await

Write asynchronous code using async and await.

David Miller
December 18, 2025
0.0k0

Handle async operations.

Basic Async Function

```python import asyncio

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

Run async function asyncio.run(greet("Tom")) ```

Multiple Async Tasks

```python import asyncio

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

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

asyncio.run(main()) ```

Async with Requests

```python import asyncio import aiohttp

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()) ```

Remember

- Use async def for async functions - Use await for async operations - asyncio.gather() for concurrent tasks

#Python#Advanced#Async