60
Async Programming
Async Programming (asyncio): Run I/O Tasks Concurrently
What you're probably confused about right now
"Is async the same as multithreading?"
Nope. asyncio typically runs a single-threaded event loop that switches between tasks using await.
One-line definition
Async programming uses async/await to switch execution while waiting on I/O, boosting throughput.
Real-life analogy
You're boiling noodles and waiting for water to heat up. Meanwhile, you wash vegetables. You didn't clone yourself -- you just scheduled better.
Minimal working example
import asyncio
async def task(name, sec):
await asyncio.sleep(sec)
print(name)
async def main():
await asyncio.gather(task("A", 1), task("B", 2))
asyncio.run(main())
Quick quiz (5 min)
- Write two concurrent tasks.
- Compare sequential vs concurrent execution time.
- Add error handling to a task.
Quiz answer guide & grading criteria
- Answer direction: write runnable code that covers the core requirements and edge cases from the prompt.
- Criterion 1 (Correctness): Main flow produces correct results, key branches execute.
- Criterion 2 (Readability): Clear variable names, no excessive nesting.
- Criterion 3 (Robustness): Basic protection against null values, type errors, or unexpected input.
Take-home task
Build a demo that concurrently fetches 5 URLs and reports total elapsed time.
Acceptance criteria
You can independently:
- Explain
async/await/gather - Identify I/O-bound scenarios
- Avoid calling blocking I/O inside async functions
Common errors & debugging steps (beginner edition)
- Can't read the error: start from the last line -- find the error type (
TypeError,NameError, etc.), then trace back to the line in your code. - Not sure about a variable's value: throw in a temporary
print(var, type(var))at key points to verify data looks right. - Changed code but nothing happened: make sure the file is saved, you're running the right file, and your terminal is in the correct venv.
Common misconceptions
- Misconception: adding
asyncalways makes things faster. - Reality: you only see gains when there's significant I/O wait time.