Simplest async/await example possible in Python

Cover Image for Simplest async/await example possible in Python
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

The Simplest Async/Await Example in Python 🐍

Are you tired of diving into complex explanations of async/await in Python? Do you want a minimal example that shows you how these keywords work without the noise of other asyncio functions? Look no further! In this blog post, we'll walk you through a super simple example that demonstrates the power of async/await in just a few lines of code. Let's get started! 💪

The Problem 😫

Many resources available on the internet provide examples of async/await in Python, but they often involve additional functions from the asyncio library, making it difficult to grasp the core concepts behind these keywords. Our goal is to provide you with the most minimalist async/await example that showcases how they work, using just the two keywords and the necessary code to run the async loop.

The Solution 🚀

To achieve our goal, let's consider the following example:

import asyncio

async def async_foo():
    print("async_foo started")
    await asyncio.sleep(5)
    print("async_foo done")

async def main():
    await async_foo()  # directly await async_foo()
    print('Do some actions 1')
    await asyncio.sleep(5)
    print('Do some actions 2')

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

In this example, we have two async functions: async_foo() and main(). The async_foo() function prints a message, awaits for 5 seconds using asyncio.sleep(), and then prints another message. On the other hand, the main() function awaits for async_foo() to complete, performs some actions, awaits for 5 seconds again, and finally performs more actions.

The key idea here is the await keyword. By directly await-ing the async_foo() function in the main() function, we can ensure that it runs within the async loop and behaves asynchronously without the need for the ensure_future() function.

Explanation 📝

When we execute the code above, several things happen:

  1. The main() function is scheduled to run within the event loop using loop.run_until_complete(main()).

  2. The async_foo() function is called within the main() function.

  3. The async_foo() function starts its execution and prints "async_foo started".

  4. The await asyncio.sleep(5) line within async_foo() suspends the execution of async_foo() and allows other tasks within the event loop to run.

  5. While async_foo() is waiting, the program proceeds to execute the next line within main().

  6. "Do some actions 1" is printed.

  7. The await asyncio.sleep(5) line within main() suspends the execution of main() for 5 seconds.

  8. "Do some actions 2" is printed.

  9. After 5 seconds have passed, async_foo() resumes execution and prints "async_foo done".

  10. The event loop completes, and the program terminates.

Conclusion 🎉

Congratulations! 🎉 You've just created and understood the simplest async/await example in Python. You don't need any fancy ensure_future() function or complicated asyncio logic. By directly await-ing an async function within your main function, you can leverage the power of asynchronous programming.

Now that you grasp the core concepts behind async/await, don't stop here! Explore more about asyncio and the vast possibilities it offers. Share your experience, ask questions, and engage with the Python community.

Keep coding! 💻✨


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello