Module 05 / Project 01 — Async Basics¶
Home: README · Module: Async Python
Learn Your Way¶
| Read | Build | Watch | Test | Review | Visualize | Try |
|---|---|---|---|---|---|---|
| — | This project | Walkthrough | — | Flashcards | — | — |
Focus¶
async defto define coroutinesawaitto pause and resumeasyncio.run()to start the event loopasyncio.sleep()vstime.sleep()asyncio.gather()to run tasks concurrently
Why this project exists¶
Before you can use async libraries (aiohttp, FastAPI background tasks, etc.), you need to understand what async and await actually do. This project builds that foundation with simple, visible examples.
Run¶
Expected output¶
--- Sequential execution ---
Task A starting...
Task A done after 2 seconds
Task B starting...
Task B done after 1 second
Task C starting...
Task C done after 3 seconds
Sequential total: ~6 seconds
--- Concurrent execution ---
Task A starting...
Task B starting...
Task C starting...
Task B done after 1 second
Task A done after 2 seconds
Task C done after 3 seconds
Concurrent total: ~3 seconds
Alter it¶
- Add a fourth task that takes 1.5 seconds. Run it both ways and compare times.
- Change
gather()to useasyncio.create_task()instead. What changes? - Add
return_exceptions=Truetogather()and make one task raise an error.
Break it¶
- Call an async function without
await. What happens? - Use
time.sleep()instead ofasyncio.sleep(). Does concurrency still work? Why not? - Try to call
asyncio.run()from inside an already-running event loop.
Fix it¶
- Replace
time.sleep()withasyncio.sleep()to restore concurrency. - Add try/except around tasks to handle errors without crashing the whole group.
- Use
asyncio.wait()withreturn_when=FIRST_COMPLETEDinstead ofgather().
Explain it¶
- What is a coroutine and how is it different from a regular function?
- Why does
time.sleep()break concurrency butasyncio.sleep()does not? - What does the event loop actually do?
- When would you use async instead of threads?
Mastery check¶
You can move on when you can:
- explain the difference between async def and def,
- use gather() to run multiple coroutines concurrently,
- predict the output order of concurrent tasks,
- explain why await is required.