Sobes.tech
Middle

What does await do in Python?

sobes.tech AI

Answer from AI

In Python, the keyword await is used inside asynchronous functions to suspend execution until an asynchronous operation (such as a coroutine, Future, or other awaitable object) completes.

This allows writing asynchronous code that looks like synchronous code but does not block the execution thread.

Example:

import asyncio

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

async def main():
    result = await fetch_data()
    print(result)

asyncio.run(main())

Here, await fetch_data() pauses main until fetch_data completes, allowing other tasks to run in the meantime.