But tbh, I don’t understand why anyone would need this.
import asyncio
async def set_future_result_after_delay(fut, delay, value):
await asyncio.sleep(delay)
if not fut.done(): # Check if it hasn't been cancelled or already set
fut.set_result(value)
async def main_asyncio_future():
loop = asyncio.get_running_loop()
# Create an asyncio.Future object
my_future = loop.create_future()
print("Main: Created future, scheduling setter task...")
# Schedule a coroutine to set the future's result later
asyncio.create_task(set_future_result_after_delay(my_future, 2, "Data from async source"))
print("Main: Waiting for my_future to complete...")
# Await the future - this will pause main_asyncio_future until my_future's result is set
result = await my_future
print(f"Main: my_future completed with result: {result}")
if __name__ == "__main__":
asyncio.run(main_asyncio_future())