Skip to content

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 def defines a coroutine.
  • awaitawait pauses 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 coffee

Was this page helpful?

Let us know how we did