Search⌘ K
AI Features

Solution: Asynchronous Programming

Explore how to refactor Python code to use asynchronous programming with async functions and asyncio features. Understand replacing blocking calls with asyncio.sleep, managing concurrent tasks with asyncio.gather, and running asynchronous workflows effectively.

We'll cover the following...

Solution overview

We have refactored our script to make it asynchronous in the following manner:

Python 3.8
import asyncio
import time
# Function to process individual items
async def process_item(item):
await asyncio.sleep(1) # Simulating a process that takes a lot of execution time
return f"Processed: {item}"
# Function to process entire data set
async def process_data(data):
# Using asyncio.gather to process the data concurrently
tasks = [process_item(item) for item in data]
return await asyncio.gather(*tasks)
async def main():
# Simulating a large amount of data
data = [i for i in range(10)]
# Processing data and noting start and end times
start_time = time.time()
processed_data = await process_data(data)
end_time = time.time()
for item in processed_data:
print(item)
# Printing execution time
print(f"Execution time: {end_time - start_time:.4f} seconds")
if __name__ == "__main__":
asyncio.run(main())

Code explanation

    ...