Glossary · Python
asyncio
Also known as: async await python, event loop, coroutine
Python's standard library for writing concurrent I/O code with async/await, running many tasks on a single-threaded event loop.
Example
import asyncio
async def fetch(name: str, delay: float) -> str:
await asyncio.sleep(delay) # stands in for a network call
return f"{name} done"
async def main() -> None:
results = await asyncio.gather(fetch("a", 1), fetch("b", 1), fetch("c", 1))
print(results) # finishes in ~1s, not ~3s
asyncio.run(main())
Good to know
- It speeds up I/O-bound work (HTTP, databases, files), not CPU-bound work. For CPU-bound work use processes.
- Never call blocking functions such as
time.sleeporrequests.getinside a coroutine; they freeze the whole loop. asyncio.TaskGroup(Python 3.11+) is the safer modern way to run and cancel groups of tasks.