What is the difference between Coroutine, Task, and Future in asyncio?
sobes.tech AI
Answer from AI
In asyncio in Python, there are three key concepts that are often confused: Coroutine, Task, and Future.
-
Coroutine — a function declared with
async defthat returns a coroutine (coroutine object) when called. It describes an asynchronous operation but does not run automatically. To execute a coroutine, you need to eitherawaitit or run it through an event loop. -
Task — a wrapper around a coroutine that schedules its execution in the event loop. Created with
asyncio.create_task(coroutine)orloop.create_task(coroutine). A Task starts the coroutine and allows tracking its state and result. Essentially, a Task is a Future that runs a coroutine. -
Future — a low-level object representing the result of an asynchronous operation that is not yet complete. Futures can be created and completed manually by setting a result or exception. A Task inherits from Future but is intended to run coroutines.
Example:
import asyncio
async def coro():
await asyncio.sleep(1)
return 'result'
async def main():
# Coroutine
c = coro()
# Task — runs the coroutine
t = asyncio.create_task(c)
# Task is a Future
print(isinstance(t, asyncio.Future)) # True
result = await t
print(result)
asyncio.run(main())
Summary:
- Coroutine — describes asynchronous work.
- Task — an object that runs a coroutine and is a Future.
- Future — an object representing the result of an asynchronous operation.