CodeGym /Courses /Python SELF EN /Future Class

Future Class

Python SELF EN
Level 26 , Lesson 1
Available

8.1 Key Features of the Future Class

The Future class in the asyncio module represents the result of an asynchronous operation that will be available in the future. Future objects are used to manage the state and results of asynchronous tasks.

Main features of the Future class

A Future object acts as a container for a result that will be available later when the task has finished executing. It provides an interface to obtain the result or exception that will be set once the asynchronous operation is completed.

Creating and Managing Future Objects

  • Creating: Usually created using loop.create_future().
  • Setting Result: The result is set using the set_result(result) method.
  • Setting Exception: An exception is set using the set_exception(exception) method.

Key Methods and Attributes

set_result(result):

Sets the result for the Future object. All coroutines awaiting this object will be immediately resumed with this result.

set_exception(exception):

Sets an exception for the Future object. All coroutines awaiting this object will be immediately resumed with this exception.

result():

Returns the result of the Future object if available. If the operation completed with an exception, it will raise that exception.

exception():

Returns the exception if it was set, or None if the Future object is not yet completed or completed successfully.

done():

Returns True if the Future object is completed (with a result or exception).

add_done_callback(callback):

Adds a callback that will be called upon the completion of the Future object.

8.2 Usage Examples

Setting and Getting the Result


import asyncio

async def set_future_result(fut, delay):
    await asyncio.sleep(delay)
    fut.set_result("Future result is ready")
            
async def main():
    loop = asyncio.get_running_loop()
    fut = loop.create_future()
    asyncio.create_task(set_future_result(fut, 2))
    result = await fut
    print(result)
            
asyncio.run(main())

Handling Exceptions


import asyncio

async def set_future_exception(fut, delay):
    await asyncio.sleep(delay)
    fut.set_exception(ValueError("An error occurred"))
            
async def main():
    loop = asyncio.get_running_loop()
    fut = loop.create_future()
    asyncio.create_task(set_future_exception(fut, 2))
    try:
        result = await fut
    except ValueError as e:
        print(f"Caught an exception: {e}")

asyncio.run(main())

Interacting with Tasks

Future objects are often used in conjunction with Tasks. When a task is created using asyncio.create_task(), it automatically creates a Future object that can be used to monitor and control the state of the task.


import asyncio

async def example_coroutine():
    await asyncio.sleep(1)
    return "Task result"
            
async def main():
    task = asyncio.create_task(example_coroutine())
    print(await task)
            
asyncio.run(main())

8.3 Benefits and Features

Future objects allow you to manage the results and exceptions of asynchronous operations, providing flexibility and control over execution. Future can be used in various asynchronous programming scenarios, including tasks, timers, callbacks, and more.

Future objects are often used in conjunction with Tasks. This approach allows for a higher level of control over the execution and state of asynchronous operations.

Limitations

In some cases, using Future might be more complex compared to using higher-level abstractions like Tasks or coroutines. When using Future, more manual management of the state and results of asynchronous operations may be required.

2
Task
Python SELF EN, level 26, lesson 1
Locked
Using a Future Object
Using a Future Object
2
Task
Python SELF EN, level 26, lesson 1
Locked
Handling Future Exceptions
Handling Future Exceptions
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION