Asyncio in Python
What is asyncio?
asyncioasyncio is Pythonβs built-in library for asynchronous I/O.
Itβs designed for workloads that spend lots of time waiting:
- network requests
- database calls
- file I/O (through async libraries)
Async vs threading vs multiprocessing
- asyncio: single-threaded concurrency using an event loop (great for many I/O tasks)
- threading: multiple threads (good for I/O, simpler when using blocking libs)
- multiprocessing: multiple processes (good for CPU-bound)
Mental model
async defasync defdefines a coroutine.awaitawaitpauses the coroutine so other tasks can run.- The event loop schedules coroutines and resumes them when theyβre ready.
Your first coroutine
first_coroutine.py
import asyncio
async def main():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(main())first_coroutine.py
import asyncio
async def main():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(main())When asyncio helps
If you do 100 HTTP requests sequentially, you wait 100 times.
With asyncio you can:
- start many requests
- efficiently wait for them concurrently
When asyncio wonβt help
For CPU-heavy loops, asyncio wonβt speed things up.
Use:
- multiprocessing
- numpy/vectorization
- compiled extensions
π§ͺ Try It Yourself
Exercise 1 β Your First Coroutine
Exercise 2 β await asyncio.sleep
Exercise 3 β Gather Two Coroutines
If this helped you, consider buying me a coffee β
Buy me a coffeeWas this page helpful?
Let us know how we did
