Sobes.tech
Junior — Middle

What is the role of the 'await' keyword in asynchronous programming in Python?

sobes.tech AI

Answer from AI

The await keyword in Python is used to suspend the execution of an asynchronous function until the asynchronous operation that returns an awaitable (such as a coroutine or Future) completes.

This allows writing asynchronous code that looks like synchronous code but does not block the execution thread, enabling other tasks to run concurrently.

Example:

import asyncio

async def fetch_data():
    await asyncio.sleep(1)  # simulate an asynchronous operation
    return 'data'

async def main():
    result = await fetch_data()  # wait for fetch_data to complete
    print(result)

asyncio.run(main())

Here, await suspends main until the result from fetch_data is obtained, without blocking the entire thread.