Sobes.tech
Junior — Middle

Could you explain the concept of Future in the asyncio library and its role when working with asynchronous code?

sobes.tech AI

Answer from AI

In asyncio in Python, a Future object represents a promise (placeholder) of the result of an asynchronous operation that will appear in the future.

A Future is a low-level object that contains the state of a task: it can be completed, canceled, or waiting for a result. It allows other parts of the code to subscribe to the completion event.

When you run a coroutine, it returns a Future or Task object (Task is a subclass of Future), which can be awaited using await. This allows the program to continue working without blocking until the result is ready.

Example of using Future:

import asyncio

async def main():
    loop = asyncio.get_running_loop()
    future = loop.create_future()

    # Simulate completing the operation after 1 second
    loop.call_later(1, future.set_result, 'Result is ready')

    result = await future
    print(result)

asyncio.run(main())

Here, Future serves as a container for a result that will be set later, and await allows asynchronous waiting for its appearance.