
Every Programming language can output. Print variables in the console can be considered as the most elementary debugging method – at least you know what it contains. This is even more true for Python if you’re using interactive notebooks such as Jupyter Notebook, because the output is all you have after running a cell.
However, have you been bothered with the format of the output? For example
- A dictionary with many key-value pairs that are printed in a single line
- A nested list is printed in a single line that is not human-readable
- A dictionary with uninterested nested objects that are very deep
You may have already known the Pretty Printer library in Python, or maybe not. No matter which case is right for you, this article will try to guide you into it and have a deep dive.
Be noticed that the Pretty Printer library is built-in to Python so you don’t need to download anything.
1. Basic Usage

To begin with, we need to import the library, as well as make up a sample dictionary for demonstration purposes.
import pprint as pp
sample_dict = {
'name': 'Chris',
'age': 33,
'message': 'Thank you for reading my article!',
'topic':'Python Programming'
}
Now, if we simply print this dictionary, everything will be output in a single line.
print(sample_dict)

Well, that’s probably not too bad, but what if we have much more key-value pairs or some of the values are extremely long? It will be difficult to read. Now, let’s have a look at what magic that the pretty printer library can do.
pp.pprint(sample_dict)

Firstly, each key-value pair is presented in one row, which is much more readable. Also, you might not be noticed, the dictionary is automatically sorted by the key names alphabetically.
2. Text Wrapping

I guess most Python developers would know the basic usage above-shown. However, do you know that the Pretty Printer library has more parameters and flags that can be used to further customise the output?
One of the example usages is text wrapping. Suppose we are not only satisfied to have one key-value pair per row, but also we want to have text wrapping when the value is too long. In this case, we can use the width
parameter.
pp.pprint(sample_dict, width=30)

So, we can use the width to constrain the length of the rows to achieve better readability. Apart from that, the indent
parameter can add indentation in front of each row.
pp.pprint(sample_dict, width=30, indent=10)

3. Nested Objects Truncating

Sometimes, we may don’t want to view all the details of what we’re printing to the output. For example, we may want to prevent something recursively printed, or just not interested in deeper-levelled contents in a nested object.
Suppose we have a nested Python list as follows.
sample_list = ['level1', ['level2', ['level3']]]
If we use the plain pretty printer, there will be nothing different from normal print.
pp.pprint(sample_list)

However, if we specify the depth
parameter, anything deeper than the argument will be truncated.
pp.pprint(sample_list, depth=2)
# OR
pp.pprint(sample_list, depth=1)

4. Instantiating Pretty Printer

So far, it is pretty cool. However, it could be too verbose and tiring to write the code as demonstrated above just for printing something, EVERY TIME.
Indeed, I wouldn’t suggest using the pretty printer to replace the default print function. It sounds kind of freak 🙂 So, only use it when necessary. For example, when you are debugging a JSON response from a web service.
However, this is another problem. When you want to use the pretty printer not only once but multiple times. It is also tired to write the function with arguments every time. In fact, we can instantiate the Pretty Printer class with all the necessary arguments. Then, we can reuse it again and again.
The PrettyPrinter
class is at the root level of the pprint
package. Therefore, let’s re-import it.
import pprint
Then, we can pass the argument in the constructor as follows.
pp = pprint.PrettyPrinter(depth=2)
After that, we have got the instance with a pre-defined style, which can be used directly.
pp.pprint(sample_list)

5. Example in Practice

Last but not the least, I want to show you a practical example to demonstrate when we need the Pretty Printer library.
Let’s use the sample JSON from the PyPI sample project. This example is also used in the official documentation.
import json
import pprint
from urllib.request import urlopen
with urlopen('https://pypi.org/pypi/sampleproject/json') as res:
project_info = json.load(res)['info']
del project_info['description']
Please note that I’ve deleted the description
key because it is too long to be appropriately demonstrated in this article.
If we simply print it, we get nothing useful information from the output. Everything in one line.
print(project_info)

Rather than copy the output and use an extra text editor such as Sublime to format and pretty the JSON document, we can not simply use the Pretty Printer library to generate readable output.
pprint.pprint(project_info, depth=1, width=60)

Summary

In this article, I have introduced the Pretty Printer library that is built-in to Python. Of course, we don’t have to use it to replace the default print function. We have to import it before use, and the code will become verbose. However, in certain scenarios, we can use it to generate better readable output that facilitates our programming and debugging activities.
If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)