Awaitable Objects in Python for Asynchronous Programming

in

Do you want to spice things up by adding some async flavor to your code? Well, my friend, you’re in luck because today we’ll be talking about awaitables in Python.

First off, what the ***** an “awaitable” is. In simple terms, it’s a fancy way of saying that something can wait for another thing to finish before continuing on with its own execution. This is useful when dealing with asynchronous programming because we don’t want our code to block and freeze up while waiting for some external process to complete.

So how do we use awaitables in Python? Well, it’s actually pretty simple! We just need to add the “async” keyword before a function definition and then use the “await” keyword inside that function when we want something to wait. Here’s an example:

# Import the necessary modules
import asyncio # Import the asyncio module for asynchronous programming
import time # Import the time module for time-related functions

# Define a function with the "async" keyword to make it awaitable
async def my_function():
    print("Starting...")
    await asyncio.sleep(2) # Use the "await" keyword to wait for 2 seconds before continuing
    print("Done!")

# Define the main function with the "async" keyword
async def main():
    await my_function() # Use the "await" keyword to wait for the my_function() to complete
    
    # Do some more stuff here that doesn't need to wait
    print("Finished!")

# Create an event loop to run the async function
loop = asyncio.get_event_loop() # Get the event loop
loop.run_until_complete(main()) # Run the main function until it is complete

In this example, we have two functions: `my_function` and `main`. The `my_function` is an asynchronous function because of the “async” keyword before its definition. Inside that function, we use the awaitable `asyncio.sleep()` to wait for 2 seconds before continuing on with our execution.

The `main` function is also async and uses the awaitable syntax to call the `my_function`. This allows us to run both functions asynchronously without blocking or freezing up our code.

To test this out, we create a loop using `asyncio.get_event_loop()` and then call the `main` function inside that loop. When you run this program, you should see output like:

# Importing the necessary libraries
import asyncio # Importing the asyncio library to use its functions for asynchronous programming

# Defining the function "my_function" with the parameter "name"
async def my_function(name):
    print("Starting...") # Printing "Starting..." to indicate the start of the function
    await asyncio.sleep(1) # Using the "await" keyword to pause the function for 1 second
    print("Finished!") # Printing "Finished!" to indicate the end of the function
    return "Done!" # Returning the string "Done!" to indicate the completion of the function

# Defining the function "main" to call the "my_function" asynchronously
async def main():
    tasks = [] # Creating an empty list to store the tasks
    for i in range(5): # Creating a loop to call the "my_function" 5 times
        tasks.append(asyncio.create_task(my_function(f"Task {i+1}"))) # Using the "asyncio.create_task" function to create a task for each call of "my_function" and adding it to the list
    await asyncio.gather(*tasks) # Using the "await" keyword to wait for all the tasks to complete before moving on to the next line
    print("Done!") # Printing "Done!" to indicate the completion of all tasks

# Creating a loop using "asyncio.get_event_loop()" and calling the "main" function inside it
loop = asyncio.get_event_loop() # Creating a loop using the "asyncio.get_event_loop()" function
loop.run_until_complete(main()) # Using the "loop.run_until_complete" function to run the "main" function inside the loop
loop.close() # Closing the loop to prevent any potential errors

# Output:
# Starting...
# Starting...
# Starting...
# Starting...
# Starting...
# Finished!
# Finished!
# Finished!
# Finished!
# Finished!
# Done!

It’s not rocket science, but it can definitely make your code more efficient and less boring to write.

SICORPS