Python Advanced
Python Async and Await
async and await let you write concurrent code that handles many waiting tasks efficiently using a single thread, powered by Python's asyncio library.
What is asyncio?
asyncio is Python's standard library for writing asynchronous code. Instead of using multiple threads or processes, it runs many tasks on a single thread by pausing a task whenever it is waiting and switching to another one that is ready to run.
Coroutines with async def
You define a coroutine using async def instead of a plain def. Calling a coroutine doesn't run it immediately — it creates a coroutine object that must be awaited or scheduled to actually execute.
import asyncio
async def greet(name):
print(f"Hello {name}")
await asyncio.sleep(1)
print(f"Goodbye {name}")
asyncio.run(greet("Aarav"))The await Keyword
await pauses the current coroutine until the awaited operation finishes, without blocking the whole program — other tasks can run during that pause. You can only use await inside a function defined with async def.
import asyncio
async def fetch(name, delay):
print(f"Start {name}")
await asyncio.sleep(delay)
print(f"Done {name}")
async def main():
await asyncio.gather(
fetch("A", 2),
fetch("B", 1),
fetch("C", 3),
)
asyncio.run(main())asyncio.gather() runs multiple coroutines concurrently and waits for all of them to finish, so the total time is close to the longest single task, not the sum of all of them.
The Event Loop
Behind the scenes, asyncio.run() starts an event loop, which is the engine that keeps track of all pending coroutines and decides which one runs next whenever another one pauses at an await. You rarely manage the event loop directly — asyncio.run() handles it for you.
async/await vs Threads
Both approaches handle waiting-heavy tasks well, but they work very differently under the hood, and asyncio requires libraries that are specifically written to support it (like aiohttp for web requests).
| Aspect | threading | asyncio |
|---|---|---|
| Concurrency model | Multiple OS threads | Single thread, cooperative switching |
| Switching happens | Anytime (preemptive) | Only at await points |
| Overhead | Higher per thread | Very low per task |
| Needs special libraries | No | Yes (async-compatible libraries) |
Use asyncio when you need to handle thousands of simultaneous waiting tasks efficiently, such as web scraping many URLs or building a chat server.
