DEV Community

Cover image for Asynchronous Python: A Beginner’s Guide to asyncio
Alvison Hunter Arnuero | Front-End Web Developer
Alvison Hunter Arnuero | Front-End Web Developer

Posted on • Edited on

Asynchronous Python: A Beginner’s Guide to asyncio

Howdy Folks: Ever wondered about asynchronous processes in programming? Join us on a journey into the realm of asynchronous Python with a focus on the asyncio module. We’ll demystify the concepts, delve into syntax, and showcase how asyncio empowers concurrent task execution. Get ready to harness the power of asynchronous Python and elevate your programming prowess!

What is an Asynchronous process anyways?
In the world of programming, there are tasks that take varying amounts of time to complete. Some tasks may be quick, while others might require waiting for external resources, such as data from a server or user input. As developers, we often encounter situations where we need to perform multiple tasks concurrently without waiting for each one to finish before starting the next. This is where asynchronous programming comes into play, and the asyncio module in Python is a powerful tool to achieve this.

Importing the asyncio Module

Ok folks, the first step in utilizing the asyncio module is to import it into our Python script. This can be done using the following line of code:

import asyncio
Enter fullscreen mode Exit fullscreen mode

This line makes all the asynchronous magic provided by the asyncio module available for use in our script. easy peasy, lemon squeasy, right?

Understanding Asynchronous Tasks

In traditional synchronous programming, tasks are executed one after the other, and the program waits for each task to complete before moving on to the next. In asynchronous programming, we can mark certain functions as asynchronous using the async keyword, allowing them to run concurrently with other tasks.

Let’s take a simple example to illustrate this concept, folks:

async def task1():
    print("Wake Up started")
    await asyncio.sleep(1)
    print("Wake Up completed")
Enter fullscreen mode Exit fullscreen mode

Oh, what is that? Ok, allow me to explain it: In this code, the async def declaration indicates that the function task1 is asynchronous. The await asyncio.sleep(1) line simulates a task that takes 1 second to complete. While waiting for this task, other asynchronous functions can execute.

The Main Function and asyncio.gather

Now, in order to coordinate and execute multiple asynchronous tasks, we use the asyncio.gather method within a main asynchronous function.

Let’s take a look at this example, champs:

async def main():
    await asyncio.gather(task1(), task2(), task3())
Enter fullscreen mode Exit fullscreen mode

In this code, the main function is marked as asynchronous using async def. The asyncio.gather method is then used to execute the tasks task1, task2, and task3 concurrently. The await keyword is used before asyncio.gather to ensure that the program waits for the completion of all tasks.

Bringing It All Together

Now, let’s put everything together into a complete script:

import asyncio

async def task1():
    print("Wake Up started")
    await asyncio.sleep(1)
    print("Wake Up completed")

async def task2():
    print("Take a shower started")
    await asyncio.sleep(2)
    print("Take a shower completed")

async def task3():
    print("Have Breakfast started")
    await asyncio.sleep(4)
    print("Have Breakfast completed")

async def main():
    await asyncio.gather(task1(), task2(), task3())

asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

When you run this script, you’ll see the output reflecting the asynchronous execution of tasks. Each task begins, and while waiting for the time-delayed sleep to complete, other tasks proceed concurrently.

Wrapping Up

In this article, we explored the basics of asynchronous programming in Python using the asyncio module. We learned how to mark functions as asynchronous, use the await keyword to wait for asynchronous tasks, and coordinate multiple tasks using asyncio.gather. Asynchronous programming enables more efficient use of resources and improves the responsiveness of applications, making it a valuable skill for developers working on various projects.

I trust you found this article both educational and enjoyable. I’ve strived to simplify the content for a quick and effective learning experience. Happy coding, and may your Python endeavors always thrive in your daily life!

❤️ Enjoyed the article? Your feedback fuels more content.
💬 Share your thoughts in a comment.
🔖 No time to read now? Well, Bookmark for later.
🔗 If it helped, pass it on, dude!

Top comments (0)