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







