Asynchronous Programming in Python
Asynchronous programming is a concept that allows tasks or operations to run concurrently and independently, without blocking the execution of other tasks. It enables the writing of concurrent and non-blocking code, leading to better resource utilization. Traditionally, program execution in Python has been linear, where code is executed line by line. In this scenario, a succeeding block of code cannot be executed until feedback from the current code execution is received.
Asynchronous programming is crucial for performing I/O-bound tasks. I/O-bound tasks are operations in a computer program that are primarily limited by input and output (I/O) processes rather than CPU processing. These tasks involve reading from or writing to external resources, where the program needs to wait for data to be fetched or written. By implementing asynchronous programming, the idle time during waiting can be utilized to perform other tasks or operations.
Python provides coroutines and async/await syntax features that make it possible to write asynchronous programs. Coroutines are the building blocks of asynchronous programming. They are defined using the async keyword before the def keyword in a function declaration. Although they look like regular functions, they have the ability to pause their execution at specific points without blocking the entire program's execution.
their execution at specific points without blocking the entire program’s execution.
async def my_coroutine():
# Coroutine codeWhen a coroutine encounters an operation that would normally block, it can voluntarily
Get Limoo Kiplimo’s stories in your inbox
Join Medium for free to get updates from this writer.
When a coroutine encounters an operation that would normally block, it can voluntarily suspend its execution and give control back to the event loop, allowing other tasks to run. The async/await syntax, on the other hand, is used within a coroutine to handle asynchronous operations.
async def my_coroutine():
result = await some_asynchronous_function()The async keyword defines a function as a coroutine, while the await keyword pauses the execution of the coroutine until the awaited synchronous operation is completed.
The primary library for asynchronous programming in Python is called asyncio. Let's explore a real-life operation to demonstrate this concept:
import asyncio
async def generate_token():
auth = ['consumer_key', 'consumer_secret']
url = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"
response = await requests.get(url, auth=auth)
response_json = response.json()
access_token = response_json["access_token"]
return access_token
async def make_payment():
access_token = await generate_token()
transaction_details = {
# some transaction details
"CallBackURL": "https://924d-197-248-202-33.ngrok-free.app/callbackdata",
# more transaction details
}
stkpush_url = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest"
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json"
}
response = requests.post(stkpush_url, json=transaction_details, headers=headers)
response_json = response.json()
return response_json
@app.route("/stkpush", methods=["GET"])
async def handle_make_payment(request: Request):
payment_result = await make_payment()
return JSONResponse(payment_result)
@app.route("/callbackdata", methods=["POST"])
async def handle_callback(request: Request):
json_data = await request.json()
await handle_make_payment(json_data)
return JSONResponse({"message": "Callback data processed successfully."})
asyncio.run(handle_callback)In this web app, the "/stkpush" endpoint is defined to handle GET requests and calls the handle_make_payment() function to initiate the payment transaction. The "/callbackdata" endpoint is defined to handle POST requests and processes the callback data, calling the handle_make_payment() function with the JSON data. Finally, the application is run using asyncio.run(handle_callback), starting the event loop and allowing the application to handle incoming requests.
Edge Cases and Conclusion
Some edge cases and considerations that developers should be aware of when working with asynchronous code include misusing the await keyword, mixing blocking and non-blocking code, shared resource management, nested coroutines, as well as debugging complexity. Despite these challenges, asynchronous programming in Python remains a valuable approach for specific scenarios where I/O-bound tasks dominate the workload. By understanding these challenges and applying best practices, developers can leverage the benefits of asynchronous programming and build responsive, efficient applications.






![Python DSA Coding Interview Series:27/29 [Dynamic Programming IV]](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*TkGqNdbkSpP-_TlGfb7ojA.png)
