Can you list the types of Awaitable objects used in asyncio?
sobes.tech AI
Answer from AI
In asyncio in Python, Awaitable is an object that can be used with the keyword await. The main types of Awaitable objects:
-
Coroutine — a function declared with
async def, which returns a coroutine object when called. It can beawaited to get the result. -
Task — a wrapper around a coroutine that is scheduled to run in the event loop. Created with
asyncio.create_task()orloop.create_task(). Task is also Awaitable. -
Future — an object representing the result of an asynchronous operation that will be available in the future. In asyncio,
Futureis a low-level Awaitable that can be manually completed or awaited.
Example:
import asyncio
async def coro():
await asyncio.sleep(1)
return 'result'
async def main():
# Coroutine
c = coro()
print(await c)
# Task
t = asyncio.create_task(coro())
print(await t)
# Future
f = asyncio.Future()
asyncio.get_event_loop().call_later(1, f.set_result, 'future result')
print(await f)
asyncio.run(main())
Thus, Awaitable objects are those that can be awaited using await, including coroutines, tasks, and futures.