Pretty Printer in Python (pprint Module)

The fairy basket has a lot more to offer, Right?

Taking no time, let’s start with yet one more important function of Python, Pprint().

The pprint module gives the capability to “pretty-print” arbitrary Python data structures in such a form that can be used as input to the interpreter.

And if the formatted structures include objects which are not fundamental Python types, then the representation is not loadable.

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

What is Pretty Print in Python?

Pretty print acts as a source code which helps in the formatting conventions and markup of small codes in a python program.

What makes pretty print different from any other function is that the coder can simultaneously check and correct the mistake in a code.

Python pprint Module Syntax

from pprint import pprint
x= "Welcome to TechVidvan"
print(x)

Output:

Welcome to TechVidvan

Pprint Module in Python

The simplest way to use Pprint is as given in the above code.

The simplicity of using the Pprint module is to make things like dictionary printouts so much easier to read. And a coder can do this in a fairly easy manner.

In the pprint module, the function prints to standard out while the format function returns a string that is likely to be useful in logging also for other output requirements.

Here is something the fairy basket has to offer as a bonus, to the ones who are new to Pprint.

The above information is quite enough to get started and do your own code, but wait.

Do you have any ideas about python files? Then tune with me, Pprint() does something miraculous here too.

Python pprint example

list=[1,2,3,4,5]
>>>print(list)

Output:

y
[1, 2, 3, 4, 5]

JSON Pretty print in Python

JSON Pretty print is a function in datafile library which simply executes the print method in any of its saved file.

There are two examples listed below:

1. Example of JSON Pretty Print using Python

import json
hijson = '{ "website": "TechVidvan", "topic": "Pprint"}’
parsed =json.loads(hijson)
print json.dumps (parsed, indent=2, sort_keys= True)

2. Example of JSON print from File using Python

import Json
with open ('json TechVidvan.txt') as jasonfile:
         parsed= json.load(json TechVidvan)
print json.dumps(parsed,indent=2, sort_keys= True)

The program will write, read, and create Python objects and dump the Json Data in a string.

Recursive Data Structure with Pprint

Pretty Print proves to be very beneficial when repetitive data is entered by the user.

It treats all the values as different yet in the same variable, which not only makes the code efficient but also saves the time of the coder.

Example of Recursive Data Structure with Pprint

>>> from pprint import pprint
mylist=['a','b','c','d']
mylist.append("t")
print(mylist)

Output:

y
[‘a’, ‘b’, ‘c’, ‘d’, ‘t’]

Controlling Output Width in Python

The actual output width for the formatted text is 80 columns. To adjust that width, use the width argument to pprint().

Python pprint example to control Output Width

mylist=['a','b','c','d']
mylist.append("t")

for i in mylist:
    del (i)
print(mylist)

Output: 

y
[‘a’, ‘b’, ‘c’, ‘d’, ‘t’]

Limiting Nested Output in Python

For the deep data structures, you may not need the output to include all of the details. It might be impossible to format the code properly, the formatted text might be too large to manage, or you may need all of it again.

In that case, the depth argument can control how far down into the nested data structure the pretty-printer goes and executes.

Example of python limiting nested Output

for width_1 in [ 80, 20, 5 ]:
    print ("WIDTH  =", width_1)

Output:

y
WIDTH = 80
WIDTH = 20
WIDTH = 5

Python Pprint Formatting

We can format the data structure without having to write it in a stream. For doing this, we use pformat() to build a string representation, which includes logging.

Python pprint Formatting Syntax:

>>> import logging
>>> from pprint import pformat
>>> logging.basicConfig
       level=logging.DEBUG,
       format='%(levelname)-7s %(message)s',)
>>> logging.debug('Logging pformatted data')

Arbitrary Classes in Python

The arbitrary classes in python act as a normal printing dictionary of the code, which copies the data from the library and executes it in the code. And finally prints it in the source code as a copy.

Summary

Hence, we discussed one more magic spell from the basket. The Python pprint module and its method with its attributes and execution.

The major among these are width, depth, and compact. Moreover, we looked at the example codes of Python pretty print.

Then for the advanced coders who are well versed with python binary data files, we learned how Json uses pprint to read, append as well as write python static/dynamic files.

Towards the end of the article, we learned how we can actually use this simple yet very useful module in various programs of Python.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.