Python pprint Module – Python Data Pretty Printer

Python course with 57 real-time projects - Learn Python

Earlier we have discussed Python OS Module. Today, we will see Python pprint i.e. Python Pretty Print. Also, we will discuss Python pprint format and its example.

This article includes recursive data structures and own classes in Pretty print in Python. At last, we will see Python pprintpp Module.

So, let’s start the Python pprint tutorial.

Python pprint Module - Python Data Pretty Printer

Python pprint Module – Python Data Pretty Printer

What is Python Pretty Print?

The pprint module lets us pretty-print arbitrary data structures in Python to make them prettier, well-formatted, and more readable. What it gives us is in a form we can use as input to the interpreter.

This is just the kind of thing for aesthetes and it keeps the output on a single line wherever possible. And when on multiple lines, it indents it.

Let’s import it:

>>> from pprint import pprint

Basically, this module has the following class:

class pprint.PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, compact=False)

This constructs a PrettyPrinter instance for us. Let’s talk about its parameters:

  • indent gives us the amount of indentation for each recursive level
  • width gives us the desired output width
  • depth gives us the number of levels to print
  • stream lets us set an output stream
  • compact lets us fit as many items within the width as we can on each line of output

Now, let’s try an example without pprint. Let’s take a list to work with:

>>> data=[(1,{'a':'A','b':'B','c':'C','d':'D'}),(2,{'e':'E','f':'F','g':'G','h':'H','i':'I','j':'J','k':'K','l':'L'}),(3,['m','n']),(4,['o','p','q','r','s','t','u','v','w']),(5,['x','y','z']),]
>>> print(data)

Output

[(1, {‘a’: ‘A’, ‘b’: ‘B’, ‘c’: ‘C’, ‘d’: ‘D’}), (2, {‘e’: ‘E’, ‘f’: ‘F’, ‘g’: ‘G’, ‘h’: ‘H’, ‘i’: ‘I’, ‘j’: ‘J’, ‘k’: ‘K’, ‘l’: ‘L’}), (3, [‘m’, ‘n’]), (4, [‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’]), (5, [‘x’, ‘y’, ‘z’])]

Python pprint Example

So, let’s try printing this with pprint instead.

>>> pprint(data)

Output

[(1, {‘a’: ‘A’, ‘b’: ‘B’, ‘c’: ‘C’, ‘d’: ‘D’}),(2,

{‘e’: ‘E’,

‘f’: ‘F’,

‘g’: ‘G’,

‘h’: ‘H’,

‘i’: ‘I’,

‘j’: ‘J’,

‘k’: ‘K’,

‘l’: ‘L’}),

(3, [‘m’, ‘n’]),

(4, [‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’]),

(5, [‘x’, ‘y’, ‘z’])]

So, what does Python pprint do? It formats an object and writes it to the data stream we pass to it as an argument. By default, this is sys.stdout.

Python pprint Formatting

We can format a data structure without having to write it to a stream. To do this, we use pformat() to build a string representation, and possible use cases include logging.

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

DEBUG    Logging pformatted data

>>> formatted=pformat(data)

So, we can print or log this string independently:

>>> for line in formatted.splitlines():
       logging.debug(line.rstrip())

Output

DEBUG    [(1, {‘a’: ‘A’, ‘b’: ‘B’, ‘c’: ‘C’, ‘d’: ‘D’}),DEBUG     (2,

DEBUG      {‘e’: ‘E’,

DEBUG       ‘f’: ‘F’,

DEBUG       ‘g’: ‘G’,

DEBUG       ‘h’: ‘H’,

DEBUG       ‘i’: ‘I’,

DEBUG       ‘j’: ‘J’,

DEBUG       ‘k’: ‘K’,

DEBUG       ‘l’: ‘L’}),

DEBUG     (3, [‘m’, ‘n’]),

DEBUG     (4, [‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’]),

DEBUG     (5, [‘x’, ‘y’, ‘z’])]

Python Pretty-Printing Our Own Classes

Last, we talked about the repr() built-in function in Python. In that, we observed the __repr__() method.

Today, let’s see how we can make pprint work with our own classes by making use of the __repr__() method.

>>> class Color:
       def __init__(self,name,hex_value):
              self.name=name
              self.hex_value=hex_value
       def __repr__(self):
              return(
                      'I am '+self.name+' and you can find me at '+self.hex_value)
>>> colors=[Color('salmon','#FA8072'),Color('olive','#808000'),Color('purple','#800080')]
>>> print(colors)

Output

[I am salmon and you can find me at #FA8072, I am olive and you can find me at #808000, I am purple and you can find me at #800080]

Now see what Python pprint does to this:

>>> pprint(colors)

Output

[I am salmon and you can find me at #FA8072,I am olive and you can find me at #808000,

I am purple and you can find me at #800080]

Python Pprint with Recursive Data Structures

Let’s create a list and append it to its end. This makes for a recursive list.

>>> from pprint import pprint
>>> mylist=[1,2,'c','d']
>>> mylist.append(mylist)
>>> id(mylist)

Output

45553504
>>> pprint(mylist)

Output

[1, 2, ‘c’, ‘d’, <Recursion on list with id=45553504>]

#The recursive reference

>>> mylist #Pay attention

Output

[1, 2, ‘c’, ‘d’, […]]
  • Controlling Depth-

To control how far the Python pretty printer recurses down a nested structure, we can use the depth argument:

>>> pprint(data,depth=1)

Output

[(…), (…), (…), (…), (…)]
>>> pprint(data,depth=2)

Output

[(1, {…}), (2, {…}), (3, […]), (4, […]), (5, […])]
>>> pprint(data,depth=3)

Output

[(1, {‘a’: ‘A’, ‘b’: ‘B’, ‘c’: ‘C’, ‘d’: ‘D’}),
   (2,{‘e’: ‘E’,’f’: ‘F’,’g’: ‘G’,

‘h’: ‘H’,

‘i’: ‘I’,

‘j’: ‘J’,

‘k’: ‘K’,

‘l’: ‘L’}),

(3, [‘m’, ‘n’]),

(4, [‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’]),

(5, [‘x’, ‘y’, ‘z’])]

Here, the ellipses denote the levels it excludes from the output.

Deciding Output Width

We can decide the width for the output- this is the number of columns. The default is 80, but we can change that with width.

>>> mylist=[1,2,'c','d']
>>> pprint(mylist)

Output

[1, 2, ‘c’, ‘d’]
>>> pprint(mylist,width=-1)

Output

[1,2,

‘c’,

‘d’]

So, you can also pretty-print the output of the listdir() method or your system’s environment variables with pprint(dict(os.environ),width=1).

>>> pprint(os.listdir())

Output

[‘DLLs’,’Doc’,

‘etc’,

‘include’,

‘Lib’,

‘libs’,

‘LICENSE.txt’,

‘man’,

‘NEWS.txt’,

‘opencv_ffmpeg343.dll’,

‘out.log’,

‘python.exe’,

‘python3.dll’,

‘python37.dll’,

‘pythonw.exe’,

‘Scripts’,

‘share’,

‘tcl’,

‘Tools’,

‘vcruntime140.dll’]

You can use the compact flag to make this more compact-

>>> pprint(os.listdir(),compact=True)

Output

[‘DLLs’, ‘Doc’, ‘etc’, ‘include’, ‘Lib’, ‘libs’, ‘LICENSE.txt’, ‘man’,’NEWS.txt’, ‘opencv_ffmpeg343.dll’, ‘out.log’, ‘python.exe’, ‘python3.dll’,

‘python37.dll’, ‘pythonw.exe’, ‘Scripts’, ‘share’, ‘tcl’, ‘Tools’,

‘vcruntime140.dll’]

The pprintpp Module

Before we say goodbye, why don’t we talk about pprintpp? This is another module for pretty printing and we like to call it pprint++.

It is available in the PyPI and you can install it as:

Python pip install pprintpp

Let’s import this.

>>> import pprintpp

Now, let’s try printing something with this.

>>> pprintpp.pprint(data)
Python pprint

Python pprintpp module

  • pp-ez

You can also install the pp-ez package to do this:

>>> pp.pprint(data)

This gives us the same output. So how is pprint++ different from pprint? One difference is what you can see in the outputs.

Well, the goal of pprint++ is to emit a readable representation of the input that is also largely PEP-8 compliant.

So, this was all in Python pprint. Hope you liked our explanation of Python Pretty Print.

Python Interview Questions on pprint Module

  1. What is pprint in Python?
  2. How to use pprint in Python?
  3. How to make pretty print list in Python?
  4. What is the difference between print and pprint in Python?
  5. What does Python pretty print do?

Summary

Hence, we discussed the Python pprint module and its method with its attributes. Some among these were width, depth, and compact.

Moreover, we looked at the example of Python pretty print. Also, we saw formatting in Pretty Print. Happy pretty-printing! This is the time to explore the most asked Python interview questions

Still, if you have any query regarding Python pprint, ask in the comment section.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

follow dataflair on YouTube

5 Responses

  1. saravana says:

    Hi Team,

    I am getting error (‘NameError: name ‘pprint’ is not defined ‘ ) when i entered ‘pprint’ in python 3.0

    • DataFlair Team says:

      Hello Saravana,
      You are running into an error because you didn’t import it first.
      You’ll need to import it:
      from pprint import pprint
      Hope, you find it useful!

  2. Alok Kumar says:

    instead of “import pprint” it should be “from pprint import pprint”.

  3. Lorena Ribeiro says:

    I would like to know if there is a possibility of not ordering the dictionaries using pprintpp.pprint or pp.pprint, I need the printing exactly as it is done in these mentioned modes, but in them or dictionaries are automatically selected in alphabetical order and it is not exactly necessary.

Leave a Reply

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