Hello, readers! In this article, we will be focusing on the functionality of Python pprint module in detail. So, let us begin! 🙂
Understanding Python pprint module
Be it any programming language, the presentation of data has always played a key role while representing the end product or application. Apart from the developer, a lot of other people from the functional team utilize the outcome of a specific module to move further with the operation or analysis. For the same, it is necessary for the output to be pretty and clear.
Especially with API calls, we often get a bulk of unformatted data from the calls as JSON files in key-value pair form. It seems too difficult for us to real and goes through the bulk of unformatted data.
Taking this into consideration, we have Python pprint module to solve the problem.
Python pprint module formats the entire output passed to it and represents the same in a structured format.
So, what’s the problem with Python print() function? Though print() function represents the output, it does NO formatting to it and therefore, is not suitable for heavy data values.
Have a look at the below example to understand the problem with print() function
Why not just use the print() function?
In the below example, we have fetched the data from API and have loaded it into JSON format. We try to print loads of data using the print() function.
import json response_API = requests.get('https://gmail.googleapis.com/$discovery/rest?version=v1') #print(response_API.status_code) data = response_API.text parse_json = json.loads(data) print(parse_json)
As you can see, the bulky data gets represented in an unstructured format due to which it becomes difficult for anyone to analyze the JSON data.
Implementing pprint() module with data from API calls
On the other hand, we now try to represent the same data that we fetched from the API in the above example and try to represent it using the pprint() module.
import requests import json from pprint import pprint response_API = requests.get('https://gmail.googleapis.com/$discovery/rest?version=v1') #print(response_API.status_code) data = response_API.text parse_json = json.loads(data) pprint(parse_json)
As clearly understood above, the entire bulky data is represented in a structured and pretty format using pprint() function, which makes it easier to read and analyze the data.
Try implementing pprint() function with other scenarios and do let us know your understanding about the same in the comment section. And feel free to drop a message in case you come across any question. For more such posts related to Python programming, stay tuned with us.
Till then, Happy Learning!! 🙂