Sobes.tech
Junior — Middle

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:

  1. Coroutine — a function declared with async def, which returns a coroutine object when called. It can be awaited to get the result.

  2. Task — a wrapper around a coroutine that is scheduled to run in the event loop. Created with asyncio.create_task() or loop.create_task(). Task is also Awaitable.

  3. Future — an object representing the result of an asynchronous operation that will be available in the future. In asyncio, Future is 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.