Part 13 / Topic 7 of 11
asyncio basics
asyncio gives you concurrency in one thread. Each task says where it is willing to pause (with await), and an event loop (a manager that keeps a list of tasks) runs another task during that pause.
Like a single waiter with many tables: they take an order, and while that kitchen order cooks, they go to the next table. Nobody stands still.
| Word | Meaning |
|---|---|
async def |
Defines a coroutine function. Calling it does not run it; it gives a coroutine object |
await x |
"Pause me here until x is done; let others run meanwhile". Only allowed inside async def |
asyncio.run(main()) |
Creates the event loop, runs main() to the end, closes the loop. Call it once, at the top |
asyncio.sleep(s) |
Async waiting: pauses this task only |
time.sleep(s) |
Blocking waiting: freezes the whole event loop. Never use it in async code |
import asyncio
async def greet(name: str, seconds: float) -> str:
await asyncio.sleep(seconds) # pause; the event loop can run others
return f"Namaste, {name}"
async def main() -> None:
coro = greet("Priya", 0.1)
print(type(coro).__name__) # coroutine (nothing has run yet)
print(await coro) # Namaste, Priya
print(await greet("Arjun", 0.1)) # Namaste, Arjun
asyncio.run(main())
Here the two awaits still run one after another (0.2 s). await alone does not make things run together. The next topic shows how.
๐ Going deeper: an async program is fast only if every slow call inside it is awaitable.
urllibandtime.sleepare not, so section 9 shows how to wrap them. Popular async HTTP libraries such ashttpxandaiohttpare third-party (Stage 5).
Read more: the official asyncio documentation.
Done here? The practice set for Part 13 โ 8 exercises with solutions โ is on the part page.