await

In Python, the await keyword pauses the execution of a coroutine until the result is available, allowing other tasks to run concurrently. It’s a crucial component in asynchronous programming, enabling you to write non-blocking code. The await keyword can only be used inside an async function or another coroutine.

Python await Keyword Examples

Here’s a quick example demonstrating how to use the await keyword:

Python hello.py
import asyncio

async def greet():
    print("Hello")
    await asyncio.sleep(1)
    print("World!")

asyncio.run(main())

Inside greet(), the await keyword waits one second using asyncio.sleep(1). Other asynchronous tasks can run during the waiting period, which is the base of the non-blocking behavior.

Python await Keyword Use Cases

  • Waiting for asynchronous I/O operations, such as reading from or writing to a file or network
  • Pausing execution in coroutines to prevent blocking the event loop
  • Scheduling concurrent execution of multiple coroutines

Tutorial

Async IO in Python: A Complete Walkthrough

This tutorial will give you a firm grasp of Python’s approach to async IO, which is a concurrent programming design that has received dedicated support in Python, evolving rapidly from Python 3.4 through 3.7 (and probably beyond).

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 6, 2025 • Reviewed by Dan Bader