Sobes.tech
Junior — Middle

How do the create_task and await methods differ when using the AsyncIO module in Python?

sobes.tech AI

Answer from AI

In Python's AsyncIO module, create_task and await serve different functions related to asynchronous code execution:

  • asyncio.create_task(coro) — starts the coroutine coro as a separate asynchronous task, which runs concurrently with other code. It returns a Task object that can be stored and awaited or canceled later.

  • await — is used to suspend the execution of the current coroutine until another coroutine or awaitable object completes. That is, await waits for the result without blocking the thread.

Example:

import asyncio

async def say_after(delay, message):
    await asyncio.sleep(delay)
    print(message)

async def main():
    task = asyncio.create_task(say_after(2, "Hello"))  # Run task in background
    print("Task started")
    await task  # Wait for task to complete
    print("Task finished")

asyncio.run(main())

Here, create_task runs say_after in the background, and await task waits for its completion. Without create_task and just with await say_after(...), execution would be sequential.