The Architecture of asyncio.Future & asyncio.Task
An `asyncio.Future` is an empty slot waiting for an eventual value or exception. An `asyncio.Task` subclasses `Future`, wrapping a raw coroutine object to automatically schedule its step execution on the running event loop 🎯⏳.
import asyncio
async def main():
loop = asyncio.get_running_loop()
# Raw Future: manual resolution
fut = loop.create_future()
loop.call_soon(fut.set_result, "RESOLVED_DATA ⚡")
val = await fut
print(f"Future payload: {val}")
asyncio.run(main())
# 17. The Architecture of asyncio.Future & asyncio.Task Beginners think `asyncio` is just magic keywords, but under the hood, the engine relies on two foundational structures: `Future` and `Task` 🛑. ```python import asyncio async def compute(): await asyncio.sleep(0.01) return "COMPUTED" async def main(): # Wrapping a coroutine in a Task registers it with the loop: task = asyncio.create_task(compute()) print(f"Task pending? {not task.done()} ⏳") result = await task print(f"Task result: {result} 🚀") asyncio.run(main()) ``` ### Core Architecture 1. **`asyncio.Future`**: Represents an eventual outcome. It holds callbacks (`add_done_callback()`), states (`PENDING`, `CANCELLED`, `FINISHED`), and holds either a `.result()` or an `.exception()` 📦. 2. **`asyncio.Task`**: Inherits from `Future`. It repeatedly calls `.send()` or `.throw()` on its inner coroutine whenever awaited dependencies resolve, driving the coroutine to completion. 3. **Execution Scheduling**: Calling `asyncio.create_task()` registers the coroutine frame onto the loop's ready queue without blocking the current flow ⚡. --- ### Interactive Pop-Quiz 🧠 #### What is the structural relationship between `asyncio.Task` and `asyncio.Future`? - [ ] `Task` is a concrete subclass of `Future` designed to package and step through a coroutine 📦 - [ ] `Task` runs on separate OS threads while `Future` runs strictly inside C extensions - [ ] `Future` is deprecated in Python 3.12+ in favor of raw threading primitives - [ ] `Task` wraps HTTP requests while `Future` wraps file descriptor reads --- ### Practical Challenge 🎯 Inside an async function `resolve_pipeline()`, create a future using `loop.create_future()`. Use `loop.call_soon()` to set its result to `'TASK_OK'`. Await the future, verify it is marked `.done()`, and print the result. <details> <summary>Solution</summary> ```python import asyncio async def resolve_pipeline(): loop = asyncio.get_running_loop() fut = loop.create_future() loop.call_soon(fut.set_result, "TASK_OK") res = await fut assert fut.done() print(res) asyncio.run(resolve_pipeline()) ``` </details>