-
What is it? A built-in Python library (since Python 3.4) that lets you write asynchronous code.
-
Why use it?
- To handle I/O-bound operations (like networking, files, databases).
- Improve performance instead of waiting for blocking operations.
- It’s the foundation of web frameworks (like FastAPI and Aiohttp).
-
Synchronous vs Asynchronous
- Synchronous: each operation waits for the previous one.
- Asynchronous: operations run concurrently (interleaved).
-
Coroutines Functions defined with
async def
. -
Event Loop The “heart” that runs coroutines.
-
async / await
async def
: define a coroutine.await
: wait for a coroutine or task.
import asyncio async def hello(): print("Hello") await asyncio.sleep(1) print("World") asyncio.run(hello())
-
Tasks
- Run coroutines concurrently.
async def main(): task1 = asyncio.create_task(hello()) task2 = asyncio.create_task(hello()) await task1 await task2 asyncio.run(main())
asyncio.gather()
→ run multiple coroutines together.asyncio.wait_for()
→ set a timeout.asyncio.shield()
→ protect a task from cancellation.
- asyncio.sleep(): simulate delay.
- asyncio streams: handle TCP/UDP sockets.
- aiohttp: HTTP client/server built on asyncio.
- Semaphore / Lock: prevent race conditions.
- Queue: manage task communication between coroutines.
- Subprocesses with asyncio.
- Cancellation & Exception handling.
- Async context managers (
async with
). - Async iterators (
async for
). - Integration with other libraries (FastAPI, SQLAlchemy async).
- Simple scraper with
aiohttp
. - Small chat server using asyncio.
- Combine asyncio with FastAPI.
- Build a small task scheduler.