The Futures of Python
Futures defer execution of code. They can allow code to wait for external resources like file reads, network calls, and database access, and then automatically continue without stopping every other operation. They allow the definition (i.e. coding) of entire sequences of work in one place rather than having one function hand-off to another (presumably coordinated) function
Python’s syntax for Futures (and coroutines) is simple and, for me, surprisingly confusing at first. I have concluded that Futures in Python boil down to three (3) rules:
Functions prefixed with
async
return a Future1 when called even if the function itself does not return a result. The code inside the function does not execute until something resolves the Future-
The ways to resolve a Future are
await <Future>
-
asyncio.get_event_loop().run_until_complete(<Future>)
orayncio.run(<Future>)
2
Use
await
insideasyn
...