Async/Await with gather in Python

Level 5321 keystrokes

This uses async/await with asyncio.gather to run multiple coroutines concurrently and collect their results.

Python code

# Import asyncio for async operations
1import asyncio
2
# Define async function that simulates data fetching
3async def fetch_data(name, delay):
# Print start message
4 print(f"Fetching {name}...")
# Simulate network delay without blocking
5 await asyncio.sleep(delay)
# Return fetched data
6 return f"{name} data"
7
# Main async function to coordinate tasks
8async def main():
# Create list of coroutines to run
9 tasks = [
# First task with 1 second delay
10 fetch_data("user", 1),
# Second task with 2 second delay
11 fetch_data("posts", 2),
# Third task with 1 second delay
12 fetch_data("comments", 1)
13 ]
# Run all concurrently (about 2 s total); results keep argument order
14 results = await asyncio.gather(*tasks)
# Print collected results
15 print(f"Results: {results}")
16
# Run the async main function
17asyncio.run(main())

Output

Fetching user...
Fetching posts...
Fetching comments...
Results: ['user data', 'posts data', 'comments data']
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • "× 12
  • (× 11
  • )× 11
  • ,× 6
  • .× 6
  • _× 4
  • :× 3
  • {× 3
  • }× 3
  • =× 2

More Python examples at level 5

← Python typing practice