liveBook · Manning

Future

As explained in Python Concurrency with asyncio

A future is an object representing the eventual result or exception of an asynchronous operation that may not yet be complete.

A future represents one value that an asynchronous operation may produce later. It begins incomplete, unresolved, or not done; setting a result or exception completes it. Calling result before completion raises an invalid-state exception. section 2.5.1

Awaiting a future pauses the current coroutine until its value is available. A task combines a coroutine with a future: it runs the coroutine and records its eventual result or exception. Futures and coroutines are awaitables because they support __await__, while tasks extend futures. section 2.5 section 2.5.2

Awaiting delayed work

Create a future, schedule a task that sets its value after a one-second sleep, and await it. The caller receives the future immediately, observes that it is incomplete, then resumes with 42 after completion.

Listing 14.8 A custom future implementation
class CustomFuture:
 
    def __init__(self):
        self._result = None
        self._is_finished = False
        self._done_callback = None
 
    def result(self):
        return self._result
 
    def is_finished(self):
        return self._is_finished
 
    def set_result(self, result):
        self._result = result
        self._is_finished = True
        if self._done_callback:
            self._done_callback(result)
 
    def add_done_callback(self, fn):
        self._done_callback = fn
 
    def __await__(self):
        if not self._is_finished:
            yield self
        return self.result()

Demonstrates the internal awaitable mechanism by yielding an unfinished custom future and returning its result after completion. section 14.5.3

How Python Concurrency with asyncio covers it

How deep it goes
Defines states, result handling, awaiting, inheritance, and custom __await__ mechanics, but does not develop custom awaitables beyond a basic implementation.
Examples
Uses direct result assignment, delayed web-request simulation, a responsive URL stress tester, and a custom future driven by an event loop.
What it assumes
Assumes basic Python functions and asynchronous execution, while building the future, task, coroutine, and awaitable relationships progressively.
What you can do after
Apply it via asyncio by awaiting results, setting completion values or exceptions, and tracking thread-safe coroutine submissions.
How it connects
Connects futures with coroutines, tasks, awaitables, event loops, exceptions, cancellation, and thread-safe concurrency.

Also explained in

Compare how 8 books explain future →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.