Problem Statement
When should you use async and await in Python and what are common pitfalls?
Explanation
Use async for high-concurrency I O like sockets, HTTP calls, or databases with async drivers. The event loop schedules tasks that yield at await points, so many operations overlap without threads.
Pitfalls include calling blocking functions inside async code, which stalls the loop. Use run in executor or an async variant. Also ensure you await tasks or gather them; otherwise work may never run or errors may be lost.
Code Solution
SolutionRead Only
import asyncio, aiohttp
async def fetch(url):
async with aiohttp.ClientSession() as s:
async with s.get(url) as r:
return await r.text()
asyncio.run(fetch('https://example.com'))