CKTIS / Python
asyncio.Future
Verbindt voltooiing via callbacks met await via een door de lus gemaakt object.
Versie: Python 3.14; repository image, production runtime not attested
Syntax
future = asyncio.get_running_loop().create_future()Verbindt voltooiing via callbacks met await via een door de lus gemaakt object.
Een Future bewaart één resultaat, uitzondering of annulering en herhaald await ziet dezelfde afloop. result() vóór voltooiing en een nieuwe set_result erna geven InvalidStateError.
Het voorbeeld krijgt 7 en de tweede poging om 9 in te stellen faalt.
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())
Voorbeelden
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())
Resultaat
True False 7 InvalidStateError
Het voorbeeld krijgt 7 en de tweede poging om 9 in te stellen faalt.