python
async
await
programming
tutorial

Simplest async/await example possible in Python

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Python's asyncio library introduced two powerful constructs: async and await, designed to simplify the way asynchronous programming is both written and understood. Asynchronous programming allows for operations that can be suspended and resumed, making efficient use of system resources by not blocking execution. Let's dive into the simplest example possible to understand the basic mechanics of async/await.

Understanding Asynchronous Programming

What Is Asynchronous Programming?

Asynchronous programming is a paradigm that allows multiple operations to begin executing, but not complete, while others are running. This is particularly useful for I/O-bound applications, such as web servers. The key to asynchronous programming is non-blocking code execution.

Synchronous vs Asynchronous

  1. Synchronous Programming: Processes are run in a sequence. A process must finish before the next starts, making the system wait for tasks to complete, leading to possible inefficiencies.
  2. Asynchronous Programming: Multiple tasks can run in overlapping times, without waiting for each to complete before starting the next. This usually involves a cooperative multitasking scheduler.

Async/Await Example in Python

Let's write the simplest async/await example:

python
1import asyncio
2
3async def say_hello():
4    await asyncio.sleep(1)
5    print("Hello, world!")
6
7async def main():
8    await say_hello()
9
10# Run the function
11asyncio.run(main())

Explanation

  • async def: By declaring a function with async def keyword, we define it as an asynchronous coroutine. Python treats coroutines differently from regular functions. They must be awaited to execute their bodies.
  • await: This keyword is used within an async function to pause execution until the awaited awaitable (another coroutine, a task, or a Future) is done, freeing the event loop to do useful work elsewhere.
  • asyncio.run(): This method is used to run an entry point coroutine until it completes. It's a high-level API provided by asyncio to run our coroutine.

Breakdown of the Example

  • async def say_hello(): The say_hello function is an asynchronous function. It pretends to do work by using await asyncio.sleep(1), simulating a short delay, ideal for testing purposes.
  • await say_hello(): We await the completion of say_hello. This ensures that say_hello runs to completion before main() terminates.
  • asyncio.run(main()): Kicks off the event loop and executes main(). The main function, in turn, waits for say_hello to finish before exiting.

Core Concepts

Here's a summary table of core concepts related to async/await:

ConceptDescription
CoroutineA function declared with async def. Awaitables that have to be executed.
awaitYields control back to the event loop, pausing the coroutine until the awaited task is ready.
Event LoopThe core of every asyncio application, running and managing tasks. It does not start tasks on its own.
asyncio.run()Established in Python 3.7+, a high-level function to execute coroutines and manage the lifecycle of the event loop.

Additional Aspects

Pros and Cons of Async/Await

  • Pros:
    • Simplifies asynchronous code to read and write.
    • Avoids callback hell (deep nesting of callbacks in asynchronous scenarios).
  • Cons:
    • Only suitable for I/O bound and high-level structured network code; not suited for CPU-bound tasks.
    • Needs an understanding of event-driven programming.

Best Practices

  • Prefer asyncio.run() to start an asyncio program, especially when not integrating with an existing event loop.
  • Use await when you have something that takes time to accomplish, such as I/O operations.
  • Test asynchronous code with frameworks and modules that specifically support async programming, like pytest-asyncio.

Understanding and incorporating async programming can significantly optimize the performance of programs, especially those involving multiple I/O operations. The async/await keywords streamline asynchronous code, improving readability and maintainability.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.