create_task
- Python course
- Advanced
- Lesson 29/83
- 5 min
Learn concurrent tasks with asyncio.create_task.
create_task
asyncio.create_task turns a coroutine into a Task that runs in the background. The task is registered with the event loop; you wait for its result with await.
async def main():
t = asyncio.create_task(work())
result = await t
return resultCalling create_task starts the coroutine right away; but the main flow is not blocked. await t waits for completion.
You can create several tasks and wait with asyncio.gather; that's covered in the next group.
Task lifecycle
Once a Task is created, it is registered with the event loop and starts running as soon as possible. You wait for it to finish with await; awaiting gives its result.
Tasks can be cancelled: t.cancel() raises CancelledError in the task. This is used to stop long-running work.
After a task completes, you can read its result with t.result() and its raised exception with t.exception().
Practice Background task with create_task
Start with import asyncio. The function async def work() returns 42. Inside async def main() create t = asyncio.create_task(work()); return return await t. Add print(asyncio.run(main())).
Starter code
# import the asyncio module
# declare a coroutine named work; return 42
# declare a coroutine named main; start work as a Task, await its result and return
# print the result of main via asyncio.runSample solution
import asyncio
async def work():
return 42
async def main():
t = asyncio.create_task(work())
return await t
print(asyncio.run(main()))Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 create_task call
import asyncio
async def main():
t = asyncio.____(work())
return await t
import asyncio
async def main():
t = asyncio.create_task(work())
return await t
Explanation: asyncio.create_task(work()) turns the work coroutine into a Task.
2 Match the Task methods
| Term | Meaning |
|---|---|
create_task(coro) |
Creates a Task |
await t |
Waits for completion |
t.cancel() |
Cancels it |
t.result() |
Gets the result |
3 When is asyncio.create_task useful?
- To cancel a coroutine
- To run a coroutine immediately
- To delete a coroutine
- To run a coroutine as a background Task Correct answer
Explanation: create_task turns the coroutine into a Task running in the background.