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.
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
- 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.
- 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:
Explanation
async def: By declaring a function withasync defkeyword, 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 anasyncfunction to pause execution until the awaitedawaitable(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 byasyncioto run our coroutine.
Breakdown of the Example
async def say_hello(): Thesay_hellofunction is an asynchronous function. It pretends to do work by usingawait asyncio.sleep(1), simulating a short delay, ideal for testing purposes.await say_hello(): We await the completion ofsay_hello. This ensures thatsay_helloruns to completion beforemain()terminates.asyncio.run(main()): Kicks off the event loop and executesmain(). Themainfunction, in turn, waits forsay_helloto finish before exiting.
Core Concepts
Here's a summary table of core concepts related to async/await:
| Concept | Description |
Coroutine | A function declared with async def. Awaitables that have to be executed. |
await | Yields control back to the event loop, pausing the coroutine until the awaited task is ready. |
Event Loop | The 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
awaitwhen 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
- Simplest async/await example possible in Python
- Simplest way to do a fire and forget method in C?
- Simplest way to do a fire and forget method in c 4.0
- Single thread concept of JavaScript running in browser
- Simplest way to form a union of two lists
- Simplify Chained Comparison
- Singleton/Synchronization in Clustered environment
- Sinon async test array is not filled in before push happens
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.