Futures
Published Sept. 11, 2024, 7:42 p.m. by frank_casanova
Futures in Python: Holding the Promise of Results
A future in Python is an object that acts as a placeholder for a value you expect to receive in the future, but it might not be available yet. When you create a future, it starts in an incomplete or unresolved state, meaning it doesn't hold a value. You can complete the future by assigning it a value, at which point it becomes finished and allows you to extract the result.
Here's how futures relate to tasks and coroutines:
1. The Future-Task Connection:
- Think of a future as a representation of a value you won't have immediately.
- A task combines both a coroutine and a future.
- 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, the result or exception is set in the associated future.
2. Awaitable: The Common Thread
- Tasks and coroutines are closely related because both can be used in
await
expressions. - This shared functionality stems from their connection through the
Awaitable
abstract base class.
3. The Awaitable ABC:
- The
Awaitable
abstract base class defines an abstract method called__await__
. - Anything that implements this method can be used in an
await
expression.
4. Inheritance Hierarchy:
- 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.
(The image can be uploaded to a different platform and linked here if desired.)
By understanding futures, tasks, and coroutines, you can leverage the power of asynchronous programming in Python to create efficient applications!
Similar posts
0 comments
There are no comments yet.