Python Await Keyword Tutorial – Complete Guide

Welcome to this comprehensive guide on Python’s await keyword. If you’ve been seeking an easy-to-understand, engaging and useful tutorial about this feature in Python, then you’re in the right place. So, buckle up and get ready to dive into the world of Python’s asynchronous programming!

What is Python’s await keyword?

In Python, the await keyword is a part of Python’s asynchronous I/O functionality and is used to suspend coroutine execution until the awaited object is complete. It’s essentially a tool to control the order of execution in a Python program.

This powerful keyword is used to handle simultaneous tasks, such as those in web scraping, where you have to juggle between multiple web pages at once. It can also be used in creating multiplayer games where several players are interacting in real-time.

The ability to work with asynchronous code is incredibly valuable in many fields of programming. Plus, it will make your code more efficient and faster in many situations where you need to handle concurrent tasks, such as in game development.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Working with Await: The Basics

Let’s start coding and see how await can be used in Python’s asynchronous programming. Note that await can only be used inside async functions.

First, we will use the asyncio module’s sleep() function to illustrate the use of await keyword:

import asyncio

async def main():
    print('Start')
    await asyncio.sleep(1)
    print('End')

asyncio.run(main())

In the above example, calling asyncio.sleep() returns a coroutine object. The await keyword is then used to suspend the execution until asyncio.sleep() is complete. After the sleep time, the next print function is called. Consequently, ‘Start’ will be printed immediately, and after one second ‘End’ will be printed.

Combining async and await in Tasks

By creating several tasks that run asynchronously and then awaiting those tasks, you can control task parallelism with the await keyword:

import asyncio

async def task(name, time):
    print('Start', name)
    await asyncio.sleep(time)
    print('End', name)

async def main():
    task1 = asyncio.create_task(task('Task 1', 2))
    task2 = asyncio.create_task(task('Task 2', 1))
    
    await task1
    await task2

asyncio.run(main())

Here, ‘Task 2’ finishes first because its sleep time is shorter. We use the asyncio.create_task() to create tasks which run asynchronously and we wait for both tasks in the main function.

The above code demonstrates how to use the await keyword to suspend coroutine execution until the task is complete, and then it moves onto the next task.

Nested Async Functions

You can also have nested async functions, with await at different levels. In our next code snippet, the await keyword is used to hold main_until_5() execution until task_until_3() is complete. It is used again in task_until_3() to pause its execution until task_until_done() finishes:

import asyncio

async def task_until_done(task_id):
    print('Start Task', task_id)
    await asyncio.sleep(task_id)
    print('End Task', task_id)

async def task_until_3():
    print('Running tasks until Task 3')
    for i in range(1, 4):
        await task_until_done(i)
    print('Completed tasks until Task 3')

async def main_until_5():
    print('Running the main task')
    await task_until_3()
    print('Main task complete')

asyncio.run(main_until_5())

You can see how the tasks are run sequentially. The next task doesn’t start until the current one is finished, creating a synchronizing effect while using asynchronous routines.

Asyncio Gather Function with await

Another effective way to manage simultaneous tasks with await is by utilizing the gather function of the asyncio module. This method allows us to run multiple tasks concurrently:

import asyncio

async def main():
    task1 = task('Task 1', 3)
    task2 = task('Task 2', 2)
    task3 = task('Task 3', 1)
    
    await asyncio.gather(task1, task2, task3)
    
async def task(name, time):
    print('Start', name)
    await asyncio.sleep(time)
    print('End', name)
    
asyncio.run(main())

The asyncio.gather() function takes in multiple tasks as arguments and runs them concurrently. The await keyword ensures the tasks are completed before proceeding to the next line of code.

Working with Async and Await in Web Scraping

Among the numerous practical applications for async and await in Python, web scraping is a helpful skill for many developers:

import aiohttp
import asyncio

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, 'http://python.org')
        print(html)

asyncio.run(main())

Here, we use the aiohttp library along with asyncio to fetch a web page’s HTML content. The await keyword is used to ensure that the response is fully received before we move on to calling the print function.

Handling Exceptions with Async and Await

Just like synchronous code, we can handle exceptions in async code using try…except blocks. To illustrate this, let’s assume we have an async function that may throw an exception, and we want to catch that exception if it occurs:

import asyncio

async def risky_task():
    raise Exception('A problem occurred!')

async def main():
    try:
        await risky_task()
    except Exception as e:
        print('Caught exception:', str(e))

asyncio.run(main())

When we run the above code, the exception raised within the risky_task() function is caught in main(), since we await the risky_task inside a try…except block.

Using Async With Context Managers

Finally, Python supports async context managers. These are normal context managers, but for asynchronous code:

import aiohttp
import asyncio

async def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

async def main():
    html = await fetch('http://python.org')
    print(html)

asyncio.run(main())

In this example, we have two await keywords in separate context management statements. The aiohttp.ClientSession() and session.get(url) are both context managers and they’re called with async with, which ensures the context is freed up once the associated code block is executed.

Where to Go Next With Your Python Journey?

Now that you’ve dipped your toes into Python’s await functionality, you might be wondering: where to go next?

One excellent avenue for this is our Python Mini-Degree. Our Python Mini-Degree is a comprehensive suite of courses that delves deep into Python, a popular language celebrated for its simple syntax and versatility. Here’s a glimpse into what you can expect:

  • Learn the basics of Python, discovering coding fundamentals like algorithms and object-oriented programming.
  • Explore applied Python by branching out into game development and app creation.
  • Experience the gratification of knowledge firmly rooted in practical application by creating your own games, algorithms and real-world apps.
  • Work on and complete fun and exciting projects like a medical diagnosis bot, an escape room game and a to-do list app!

No matter where you’re starting from – be it a beginner or an experienced programmer – our Python Mini-Degree will provide you with a flexible learning path built for your convenience. What’s more, with our project-oriented curriculum, you can diligently work towards building a portfolio of Python projects as proof of your newfound skills.

If you feel like expanding a bit wider into Python, we also welcome you to check out our collection of Python courses.

Conclusion

Python’s await keyword is a powerful instrument in the hands of a well-versed coder. In today’s fast-paced technological world, the knowledge to construct and manipulate asynchronous code is a significantly beneficial addition to your programming repertoire.

At Zenva, we believe in boosting your skill set strategically and efficiently. If you’re excited about honing your Python skills, we invite you to start your journey with our Python Mini-Degree today. We look forward to supporting you in your pursuit of becoming a proficient Python programmer.

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.