CKTIS / Python
asyncio.Future
Represents one eventual result or exception that can be awaited by multiple callers.
Version: Python 3.14; repository image, production runtime not attested
Syntax
future = asyncio.get_running_loop().create_future()Represents one eventual result or exception that can be awaited by multiple callers.
Resolving an already finished future a second time raises InvalidStateError. Use the loop factory for integration with the active event loop.
Bridge callback-based completion to awaitable code with a Future created by its event loop. It stores one result, exception or cancellation state; repeated awaits see that outcome. Reading result() while pending or setting an already completed result raises InvalidStateError. The sample initially reports not done, then returns 7 and rejects a second completion.
import asyncio
async def main():
f = asyncio.get_running_loop().create_future()
try:
f.result()
except asyncio.InvalidStateError:
pass
else:
raise AssertionError
f.set_result(5)
assert await f == 5 and await f == 5
g = asyncio.get_running_loop().create_future()
g.cancel()
assert g.done() and g.cancelled()
asyncio.run(main())
Examples
import asyncio
async def main():
future = asyncio.get_running_loop().create_future()
print(isinstance(future, asyncio.Future), future.done())
future.set_result(7)
print(await future)
try:
future.set_result(9)
except asyncio.InvalidStateError as error:
print(type(error).__name__)
asyncio.run(main())
Result
True False 7 InvalidStateError
Bridge callback-based completion to awaitable code with a Future created by its event loop. It stores one result, exception or cancellation state; repeated awaits see that outcome. Reading result() while pending or setting an already completed result raises InvalidStateError. The sample initially reports not done, then returns 7 and rejects a second completion.