Site icon DataFlair

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

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)

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

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

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’, […]]

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 pprintpp module

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.

Exit mobile version