Schedule Tasks and Observe Futures
Core idea
A Task schedules a coroutine on the running event loop and holds its eventual result or exception. asyncio.create_task returns a Task; keep a reference and await it. A Future represents an eventual outcome, often provided by callback code; use loop.create_future for a loop-compatible Future. Tasks and Futures are awaitable and can be awaited again once finished.
import asyncio
async def main(): async def read(): return 9 task = asyncio.create_task(read()) print(await task) print(task.done(), task.result())
asyncio.run(main())After awaiting success, done is true and result is available.
Expected output:
9True 9Resolve a future by callback
import asyncio
async def main(): loop = asyncio.get_running_loop() f = loop.create_future() print(f.done()) loop.call_soon(f.set_result, 'ready') print(await f) print(await f)
asyncio.run(main())The callback completes the Future; both awaits receive the same result.
Expected output:
FalsereadyreadyCommon mistake
Calling result() before completion raises InvalidStateError. A failed task must have its exception observed; keep task references and use TaskGroup for related work. Do not confuse asyncio.Future with concurrent.futures.Future.
Practice
Create a Future and resolve it using call_soon; inspect done before and after awaiting.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tasks and futures
Check your understanding of tasks and futures.
What is printed?
import asyncio
async def main(): f=asyncio.get_running_loop().create_future() f.set_result(3) print(await f, f.done())
asyncio.run(main())What is printed?
import asyncio
async def main(): async def job(): return 'ok' t=asyncio.create_task(job()) print(await t, await t)
asyncio.run(main())What schedules a coroutine as a separate task?
When is task.result() safe for a successful task?