Sobes.tech
Junior — Middle

Can you explain the differences between a task and a coroutine in the context of asynchronous programming?

sobes.tech AI

Answer from AI

In the context of asynchronous programming in Python:

  • Coroutine — is a function that can suspend its execution and return control back to the event loop, allowing other tasks to run concurrently. It is defined using async def and can use await inside to wait for the result of other asynchronous operations.

  • Task — is an object that wraps a coroutine and schedules its execution in the event loop. Tasks allow running coroutines in the background and managing their lifecycle (e.g., canceling or waiting for completion).

Example:

import asyncio

async def coro():
    await asyncio.sleep(1)
    return 'result'

async def main():
    task = asyncio.create_task(coro())  # create a task from a coroutine
    print('Task started')
    result = await task  # wait for the task to complete
    print(f'Result: {result}')

asyncio.run(main())

Thus, a coroutine is the asynchronous function itself, and a task is an object that manages its execution in the event loop.