...

Futures

Frank Casanova

Oct. 26, 2023

...

A future in Python is an object that holds a single value you expect to receive in the future, but it may not exist yet. When you create a future, it starts as incomplete or unresolved, meaning it has no value. You can complete the future by setting its value, and at that point, it is considered finished, allowing you to extract the result from it.

  1. Tasks and futures in Python have a strong relationship. A future can be thought of as representing a value that you won't have immediately, while a task combines both a coroutine and a future.
  2. When you create a task, you're essentially creating an empty future and running a coroutine. Once the coroutine finishes, either with a result or an exception, you set the result or exception of the associated future.
  3. Tasks and coroutines are closely related because both can be used in await expressions, thanks to their common connection through the Awaitable abstract base class.
  4. The Awaitable abstract base class defines an abstract method __await__. Anything that implements this method can be used in an await expression.
  5. Coroutines inherit directly from Awaitable, as do futures. Tasks build on futures, creating an inheritance hierarchy where tasks encompass both the features of coroutines and futures.