Beginner Level
Intermediate Level
Advanced Level
Introduction
Asynchronous programming is particularly useful for tasks such as network requests, database queries and web scraping that require waiting for external events. In Python, the asyncio library facilitates asynchronous programming and one fundamental object is the ‘Future’. This tutorial aims to provide an insight into asyncio Future objects and how they can be used to simplify asynchronous programming in Python.
Table of Contents :
- What are Python asyncio Future objects
- Using Python asyncio Future with Await
- Futures, Tasks, and Coroutines in Python
What are Python asyncio Future objects :
- Futures are objects that represent a value that may not yet be available.
- The Python asyncio module provides a Future class that can be used to manage asynchronous operations.
- A future is set to a result using the set_result() method, which notifies any waiting coroutines that the future is complete with the specified result.
Using Python asyncio Future with Await :
- Here's an example of using
asyncio.Future()
to create a future, and await to wait for its result: - Code Sample :
import asyncio
async def coro(fut):
result = await fut
print('Result:', result)
async def main():
print('Main started')
fut = asyncio.Future()
asyncio.create_task(coro(fut))
fut.set_result('Future result')
print('Main completed')
asyncio.run(main())
Explanation :
- In the above example, we define a co-routine
coro()
that waits for a future to be completed and prints its result. - We also define a
main()
coroutine that creates a future fut and a task that executescoro(fut)
. - We set a result for fut using
set_result()
. - When we run this program, it will print "Result: Future result".
Futures, Tasks, and Coroutines in Python :
- Futures, tasks, and co-routines are all related concepts in asynchronous programming with Python
asyncio
. - A co-routine is a special function that can be paused and resumed later.
- A task is a subclass of Future that wraps around a co-routine and provides extra functionality to manage its lifecycle.
- Here's an example of creating a task from a co-routine:
- Code Sample :
import asyncio
async def coro():
print('Coroutine started')
await asyncio.sleep(1)
print('Coroutine completed')
return 'Coroutine result'
async def main():
print('Main started')
task = asyncio.create_task(coro())
print('Main waiting for coroutine result')
result = await task
print('Result:', result)
print('Main completed')
asyncio.run(main())
Explanation :
- In the above example, we define a co-routine
coro()
that waits for one second before returning. - We also define a
main()
co-routine that creates a task fromcoro()
. - We use await to wait for the task to complete and obtain its result.
- When we run this program, it will print "Coroutine started", "Main waiting for coroutine result", "Coroutine completed", and "Result: Coroutine result".
Prev. Tutorial : wait_for() function
Next Tutorial : gather() function