await
`await` pauses your async function until another operation finishes, then hands you its result.
Used in 21 lessons of the course, from 01.05.
await is only written inside an async def function. It goes in front of something awaitable, such as a call to another async function or to asyncio.sleep.
When Python reaches await, your function pauses. While it waits, the event loop can run other tasks. When the result is ready, your function resumes on the same line and the value is available, as in x = await something().
That is why it exists: to wait without blocking the whole program. A normal call runs right away. Calling an async function only creates a coroutine, and await is what actually runs it.
In the course you see it in lessons like 01.05: await asyncio.sleep(DELAY). The program waits DELAY seconds without freezing everything else.
Reach for it when: inside an `async def` function, you need the result of another async operation, such as a wait or a model call.
Examples
Common mistake
import asyncio
async def dato():
return 42
async def main():
x = dato()
print(x == 42)
asyncio.run(main())Why: Without `await`, `x` is a coroutine object, not 42. The function never ran (Python also warns with a RuntimeWarning on stderr).
How to write it: Write x = await dato().
Common mistake
import asyncio
def main():
await asyncio.sleep(0)Why: `await` is only valid inside an `async def` function.
How to write it: Declare the function as async def main(): and run it with asyncio.run(main()).
