Lesson · Async Python
asyncio Tasks
75 min readasyncio Tasks
`asyncio` tasks schedule coroutines independently within an event loop. Creating tasks introduces lifetime, cancellation, exception, and result-management responsibilities.
Learning goals
- Explain what
asyncio.create_taskschedules and when the coroutine body actually starts. - Describe how awaiting a task differs from calling it: the result arrives at the
await, not at creation. - Predict
gather's returned order from the task list rather than from completion times. - Explain why the five-task example finishes in about one sleep instead of five.
- Name what happens to a task's exception when no one keeps its handle.
Mental model
Scheduling a task hands it to the loop, so the body starts on the next pass and the handle stays pending until it finishes. The worked example leans on that: all five tasks are already pending before gather touches them.
Mental model
read it top to bottom
create_task(work(n)) schedule now, body starts on the loop's next pass ↓ Task object (pending) handle with result, exception, and cancel() ↓ await task / gather(*tasks) waits here, other tasks keep running meanwhile ↓ result or raised exception delivered to the awaiting line
Core idea
A task is a coroutine plus a place to put its outcome: create_task schedules it, and the handle reports pending, result, exception, or cancelled. gather waits for a batch of tasks and returns their results in argument order, which is what turns five independent sleeps into one shared wait instead of five sequential ones.
create_task
asyncio.create_task schedules a coroutine as an independent task on the running loop. Keep a reference or structure the task's lifetime so errors and cancellation are not lost.
Awaiting tasks
Awaiting a task suspends the current coroutine until that task finishes, then returns its result or raises its exception. The waiting happens at the await; the task itself runs on the loop independently once scheduled, so several tasks can be in flight while you await one of them.
Concurrent async work
Concurrent async work means several tasks make progress during the same overall wait by interleaving at suspension points. It comes from scheduling coroutines as tasks with create_task, gather, or TaskGroup, not from calling coroutine functions in a loop.
Gathering results
asyncio.gather awaits several awaitables together and returns a list of their results in the order the arguments were given, regardless of completion order. By default it propagates the first exception, and the other tasks keep running unless you cancel them or pass return_exceptions=True.
Cancellation
Async cancellation is a cooperative control-flow event normally delivered as CancelledError at an await point. Cleanup code should release resources and usually re-propagate cancellation.
Timeouts
Timeouts places an upper bound on waiting. A timeout does not automatically undo external side effects, so design cancellation and cleanup around the resource being used.
Walkthrough
- The comprehension
[asyncio.create_task(work(n)) for n in range(5)]schedules five tasks immediately, so all fiveawait asyncio.sleep(0.05)waits overlap and the whole run lasts about 0.05 seconds. await asyncio.gather(*tasks)waits for all five handles and returns[0, 1, 4, 9, 16]:gatherpreserves argument order even though completion order depends on the delays.- The tasks were created before
gatherwas called, andgatherreceives the handles rather than the coroutines, so nothing is scheduled a second time. - Predict before running: the printed list, the approximate total time, and the total when the five
workcalls are awaited one after another in a loop.
Experiments to try
- Time the worked example and a variant that awaits
work(n)five times in a loop; explain the five-fold difference from overlapping against sequential waits. - Print
tasks[0]right after creation and again aftergather; read the change in the repr and checktasks[0].done()at both points. - Raise
ValueErrorinsideworkfor one value and run with plaingatherand withgather(..., return_exceptions=True); compare the two outcomes. - Await only
tasks[0]and return frommainwhile the others still sleep; then look for the shutdown message about pending tasks.
Common mistakes
- Losing the handle:
asyncio.create_task(work(n))with no name kept means no one awaits the result, and a failure surfaces only as a diagnostic when the task object is collected. - Expecting
gatherto order results by finish time: the returned list follows argument order, and completion order only affects timing, which is whatasyncio.as_completedexposes when it matters. - Assuming a failing task cancels its siblings: plain
gatherraises the first exception while the other tasks keep running, so cleanup needs explicit cancellation. - Reading a result too early:
task.result()raisesInvalidStateErroruntil the task has actually completed.
Practice: Easy
- Run the worked example with
time.perf_counter()aroundmainand record the total; compare it with five awaitedwork(n)calls. - Shrink the comprehension to
range(3)and write the expected printed list before running. - Print
tasks[2].done()before and aftergatherand explain both booleans from the task lifecycle.
Practice: Medium
- Add start and finish prints to
workand verify that all five starts appear before any finish; explain from the 0.05 second sleeps. - Serve the same five results with
asyncio.as_completed(tasks), printing values as they arrive with staggered delays; contrast the output order withgather. - Await
tasks[0]directly instead of gathering all five, then calltasks[0].result(); explain what the other four tasks do whenmainreturns.
Practice: Hard
- Write
map_concurrent(fn, items, limit)using a semaphore to cap simultaneous tasks and return results in input order; test it withlimit=2over five items and verify the cap with timestamps. - Make the third task raise
ValueError; first show plaingatherleaving siblings running, then a version that cancels the unfinished tasks and collects them withgather(..., return_exceptions=True); report each task'scancelled()value. - Start a long task, cancel it after 0.05 seconds, and record the
CancelledErrorfromawait task; then calltask.cancel()again after completion and explain theFalse.
Lesson checklist
- I can explain what
create_taskdoes and when the coroutine body first runs. - I can predict the order
gatherreturns results in, and name what determines completion order. - I can keep task handles and say where a failure would surface if I did not.
- I can cancel a task and describe how
CancelledErrorreaches the awaiting code.
Remember
A task is a scheduled coroutine plus a handle holding its outcome: pending, result, exception, or cancelled. `create_task` needs the result to be awaited somewhere, `gather` waits for a whole batch and preserves argument order, and the exceptions of tasks nobody awaits can vanish into a log line.
Interview angles
What is the main purpose of **create_task**?+
asyncio.create_task schedules a coroutine as an independent task on the running loop. Keep a reference or structure the task's lifetime so errors and cancellation are not lost.
What should you pay attention to when using **Awaiting tasks**?+
Awaiting a task suspends the current coroutine until that task finishes, then returns its result or raises its exception. The waiting happens at the await; the task itself runs on the loop independently once scheduled, so several tasks can be in flight while you await one of them.
How does **Concurrent async work** fit into this lesson?+
Concurrent async work means several tasks make progress during the same overall wait by interleaving at suspension points. It comes from scheduling coroutines as tasks with create_task, gather, or TaskGroup, not from calling coroutine functions in a loop.
Why can a task's exception disappear if you never store or await the task?+
The exception is stored on the task object, and if nothing awaits the handle, no caller ever re-raises it. When the object is garbage collected, the loop reports an unretrieved task exception only as a log message, so the failure never reaches your code.