async/await — syntax for asynchronous programming. Allows writing concurrent code that looks synchronous.
async def defines a coroutine. await pauses execution until the result is ready.
1import asyncio23async def fetch_data(url):4 print(f"Start fetching {url}")5 await asyncio.sleep(2) # Simulate I/O6 return f"Data from {url}"78async def main():9 # Sequential (slow)10 result1 = await fetch_data("api1.com")11 result2 = await fetch_data("api2.com")1213 # Concurrent (fast)14 task1 = asyncio.create_task(fetch_data("api1.com"))15 task2 = asyncio.create_task(fetch_data("api2.com"))16 result1, result2 = await task1, await task21718asyncio.run(main())
Key rules:
await only inside async def.asyncio.run() starts the event loop.