Python pprint Module – Python Data Pretty Printer

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

1. 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)

[(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’])]

2. Python pprint Example

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

>>> pprint(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’])]

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.

Learn about Python sys Module.

3. 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())

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’])]

4. 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)

[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)

[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]

5. 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)

45553504

>>> pprint(mylist)

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

>>> mylist #Pay attention

[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)

[(…), (…), (…), (…), (…)]

>>> pprint(data,depth=2)

[(1, {…}), (2, {…}), (3, […]), (4, […]), (5, […])]

>>> pprint(data,depth=3)

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

Join DataFlair on Telegram

  (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.

6. 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)

[1, 2, ‘c’, ‘d’]

>>> pprint(mylist,width=-1)

[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())

[‘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)

[‘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’]

Python Interview Questions

7. 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.

8. 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.

2 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!

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.