Python Tutorial: Async & Concurrency
Do multiple things at once without threads. async/await and asyncio make concurrent code readable.
Don't wait around
Fetching a URL takes 200ms. Querying a database takes 100ms. Waiting for user input could take forever.
`async/await` lets your program do other work while waiting — without threads, without complexity. Twelve steps.
What you'll learn in this Python async & concurrency tutorial
This interactive Python tutorial has 8 hands-on exercises. Estimated time: 22 minutes.
- Why do we need async? — Most programs spend most of their time *waiting* — waiting for a network response, a database query, a file to load.
- async and await — the basics — Two keywords:
- gather — run many things at once — `asyncio.gather()` runs multiple coroutines **concurrently** and returns all results:
- create_task — fire and check later — `asyncio.create_task()` schedules a coroutine to run — you get a Task object back immediately and can check it later.
- asyncio.sleep vs time.sleep — This distinction is critical and a common mistake:
- Handle exceptions in async — Exceptions in coroutines work exactly like in regular functions — try/except works perfectly.
- asyncio.timeout — don't wait forever — What if a request takes 10 seconds when you expected 2?
- Build an async downloader — Final challenge — no starter code.
Python Async & Concurrency concepts covered
- Don't wait around