async def and await β The Basics
async def creates a coroutine function. await suspends execution until the awaited operation completes.
Python
import asyncio
async def greet(name, delay):
await asyncio.sleep(delay) # Non-blocking wait
print(f"Hello, {name}!")
async def main():
# Run sequentially: takes 3s
await greet("Alice", 1)
await greet("Bob", 2)
asyncio.run(main())βΆ Output
Hello, Alice!
Hello, Bob!asyncio.gather β True Concurrency
Run multiple coroutines concurrently with asyncio.gather().
Python
import asyncio
import time
async def fetch(url, delay):
await asyncio.sleep(delay) # Simulate network I/O
return f"Response from {url}"
async def main():
start = time.time()
# All three run concurrently β total ~2s not 6s
results = await asyncio.gather(
fetch("api.com/users", 2),
fetch("api.com/posts", 1),
fetch("api.com/data", 2)
)
for r in results:
print(r)
print(f"Done in {time.time()-start:.1f}s")
asyncio.run(main())βΆ Output
Response from api.com/users
Response from api.com/posts
Response from api.com/data
Done in 2.0sasyncio.create_task β Background Tasks
Tasks run in the background. Useful for fire-and-forget operations.
Python
import asyncio
async def background_worker():
while True:
print("Background: heartbeat")
await asyncio.sleep(5)
async def main():
task = asyncio.create_task(background_worker())
# Do other work while background runs
await asyncio.sleep(0) # Yield control
print("Main: doing work")
task.cancel() # Stop background
asyncio.run(main())Ad β 336Γ280
Real Async HTTP with aiohttp
Use aiohttp for async HTTP requests. Dramatically faster than requests for concurrent fetching.
Python
# pip install aiohttp
import asyncio
import aiohttp
async def fetch_url(session, url):
async with session.get(url) as response:
return await response.json()
async def main():
urls = [
"https://api.github.com/users/python",
"https://api.github.com/users/torvalds"
]
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
results = await asyncio.gather(*tasks)
for r in results:
print(r["login"])
asyncio.run(main())βΆ Output
python
torvalds