Asynchronous programming has become increasingly popular in Python. Two key concepts for async are asyncio and futures. But what exactly is the difference between the two?
Async IO: Asynchronous I/O Made Easy
The
Some key features of asyncio:
For example:
import asyncio
async def fetch_data():
print('fetching...')
await asyncio.sleep(2) # pause for 2 seconds
print('done!')
async def main():
await fetch_data()
asyncio.run(main())
This allows other tasks to run while
Futures: Managing Promise of a Result
A future represents an eventual result of an asynchronous operation. They provide a way to indirectly wait for and get the result of a long running operation.
Some key aspects of futures:
For example:
from concurrent.futures import Future
f = Future()
def resolve_future():
print('resolving future...')
f.set_result('future is done!')
f.add_done_callback(lambda x: print(x.result()))
resolve_future()
So in summary,