capypad
0 day streak
python / intermediate
Snippet

Asynchronous Programming with async/await

Asyncio is used for concurrent code execution using the async/await syntax. It is ideal for I/O-bound tasks like web requests or database queries.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
import asyncio
 
async def fetch_data():
print("Fetching...")
await asyncio.sleep(1)
return {"id": 1}
 
async def main():
result = await fetch_data()
print(result)
Breakdown
1
async def fetch_data():
Defines a coroutine, which can be paused and resumed.
2
await asyncio.sleep(1)
Suspends the coroutine for 1 second without blocking the execution thread.