Dan's solution is just wrong, and Ismail's in incomplete.

  1. __str__() is not called, __repr__() is called.
  2. __repr__() should return a string, as pformat does.
  3. print normally indents only 1 character and tries to save lines. If you are trying to figure out structure, set the width low and indent high.

Here is an example

class S:
    def __repr__(self):
        from pprint import pformat
        return pformat(vars(self), indent=4, width=1)

a = S()
a.b = 'bee'
a.c = {'cats': ['blacky', 'tiger'], 'dogs': ['rex', 'king'] }
a.d = S()
a.d.more_c = a.c

print(a)

This prints

{   'b': 'bee',
    'c': {   'cats': [   'blacky',
                         'tiger'],
             'dogs': [   'rex',
                         'king']},
    'd': {   'more_c': {   'cats': [   'blacky',
                               'tiger'],
                  'dogs': [   'rex',
                              'king']}}}

Which is not perfect, but passable.

Answer from Charles Merriam on Stack Overflow
🌐
Python
docs.python.org › 3 › library › pprint.html
pprint — Data pretty printer
The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the ...
🌐
W3Schools
w3schools.com › python › ref_module_pprint.asp
Python pprint Module
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training · ❮ Standard Library Modules · Pretty-print nested data in a readable way: from pprint import pprint data = {"users": [{"name": "Emil", "tags": ["admin", "editor"]}]} pprint(data) Try it Yourself » ·
Discussions

Why Pretty Print?
It is a bit convoluted for something that you'd normally only use during software development, and you can't really give a simple user-case of the form that you'd normally see in a beginner's book. It's useful when you're debugging, and need to look at a huge data structure, a large complicated list or json file, or whatever, and just printing it normally gives an impenetrable wall of text. More on reddit.com
🌐 r/learnpython
4
1
October 7, 2020
python - Prettyprint to a file? - Stack Overflow
The output is a list not a graph which is pretty printed on the screen. 2019-02-06T18:03:21.903Z+00:00 ... Worked for me with Python 3.7.2. More on stackoverflow.com
🌐 stackoverflow.com
How can I make my class pretty printable in Python? - Stack Overflow
Python has a pretty printer (pprint(...)). I would like to make my classes pretty printable. Will pretty print print my instances in a better way, if I provide a certain interface? The Python More on stackoverflow.com
🌐 stackoverflow.com
How to print a list in Python "nicely" - Stack Overflow
In PHP, I can do this: echo ' ' print_r($array); echo ' ' In Python, I currently just do this: print the_list However, this will cause a big jumble of data. Is there any way to More on stackoverflow.com
🌐 stackoverflow.com
🌐
Jython
jython.org › jython-old-sites › docs › library › pprint.html
8.18. pprint — Data pretty printer — Jython v2.5.2 documentation
The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the representation may not be loadable.
🌐
GeeksforGeeks
geeksforgeeks.org › python › pprint-data-pretty-printer-python
pprint : Data pretty printer in Python - GeeksforGeeks
The pprint module (pretty print) is a built-in utility that formats complex data structures like dictionaries, lists, or JSON in a readable way with proper indentation and line breaks.
Published: January 9, 2026
🌐
Real Python
realpython.com › python-pretty-print
Prettify Your Data Structures With Pretty Print in Python – Real Python
March 18, 2026 - The pprint module, Python's data pretty printer, is a useful part of the standard library. You can work with it for debugging data structures and increasing the readability of your output.
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › why pretty print?
r/learnpython on Reddit: Why Pretty Print?
October 7, 2020 -

Hi all

I'm trying to understand the usefulness of Pretty Print.

In automate the boring stuff it was used a few times earlier in the book to make things look 'prettier', it didn't really look much better to me but I assumed this was down to taste.

Now I just saw an actual use-case for it later in the book and it seems like a very convoluted method.

After importing pretty print, the format function can be used to convert a list to a string which makes it easier to write to a text doc and subsequently reimport (apparently). But you can just put 'str' in front of the list to achieve the same thing, so I fail to see the point.

Any ideas?

:\

🌐
YouTube
youtube.com › que8
Python's pprint Module: Mastering Pretty Printing in Python - YouTube
Join us as we unravel Python's pprint module! Learn how to pretty print complex data structures, making them more readable and easier to debug. This tutorial...
Published: July 10, 2023
Views: 1K
🌐
Rich
rich.readthedocs.io › en › latest › pretty.html
Pretty Printing — Rich 14.1.0 documentation
Run the following command to see an example of pretty printed output: python -m rich.pretty · Note how the output will change to fit within the terminal width. The pprint() method offers a few more arguments you can use to tweak how objects are pretty printed.
🌐
CodeGym
codegym.cc › java blog › learning python › pretty-print (pprint) in python
Pretty-Print (pprint) in Python
July 31, 2024 - The pprint module in Python is designed to provide a more human-readable output for complex data structures, such as dictionaries, lists, and nested combinations of these. In simpler terms, pprint formats your data neatly and clearly, making ...
Top answer
1 of 4
16

pprint does not look for any hooks. The pprint.PrettyPrinter uses a dispatch pattern instead; a series of methods on the class that are keyed on class.__repr__ references.

You can subclass pprint.PrettyPrinter to teach it about your class:

class YourPrettyPrinter(pprint.PrettyPrinter):
    _dispatch = pprint.PrettyPrinter._dispatch.copy()

    def _pprint_yourtype(self, object, stream, indent, allowance, context, level):
        stream.write('YourType(')
        self._format(object.foo, stream, indent, allowance + 1,
                     context, level)
        self._format(object.bar, stream, indent, allowance + 1,
                     context, level)
        stream.write(')')

    _dispatch[YourType.__repr__] = _pprint_yourtype

then use the class directly to pretty print data containing YourType instances. Note that this is contingent on the type having their own custom __repr__ method!

You can also plug functions directly into the PrettyPrinter._dispatch dictionary; self is passed in explicitly. This is probably the better option for a 3rd-party library:

from pprint import PrettyPrinter

if isinstance(getattr(PrettyPrinter, '_dispatch'), dict):
     # assume the dispatch table method still works
     def pprint_ExtendedConfigParser(printer, object, stream, indent, allowance, context, level):
         # pretty print it!
     PrettyPrinter._dispactch[ExtendedConfigParser.__repr__] = pprint_ExtendedConfigParser

See the pprint module source code for how the other dispatch methods are written.

As always, single-underscore names like _dispatch are internal implementation details that can be altered in a future version. However, it is the best option you have here. The dispatch table was added in Python 3.5 and is present in at least Python 3.5 - 3.9 alpha.

You may want to look at rich, a third-party library that has some great pretty-printing capabilities, and supports hooks (__rich_repr__); see the documentation on customising pretty-printing.

2 of 4
4

It is not really a solution, but I usually just make objects serializable and pretty print them like this:

pprint(obj.dict())
🌐
Medium
medium.com › codex › prettify-your-python-outputs-using-pprint-60522ef997d0
Prettify your Python Outputs using pprint()! | by Satyam Gupta | CodeX | Medium
August 2, 2022 - The pprint module in Python is a utility module that you can use to print data in a more readable and pretty manner.
🌐
PyPI
pypi.org › project › prettyprint
prettyprint · PyPI
This module privides pretty printing for list/dict/tuple/set python object.
      » pip install prettyprint
    
Published: Feb 23, 2012
Version: 0.1.5
🌐
Medium
medium.com › analytics-vidhya › pretty-printing-in-python-277bc4db2847
Pretty Printing In Python!. Dictionaries in Python can get long… | by Dhairye Kataria | Analytics Vidhya | Medium
February 11, 2024 - If you want to obtain the prettified text as a string value instead of displaying it on the screen, call pprint.pformat() instead. These two lines are equivalent to each other: pprint.pprint(someDictionaryValue) print(pprint.pformat(someDic...
🌐
Educative
educative.io › answers › what-is-the-pretty-print-module-in-python
What is the pretty-print module in Python?
The pprint module can be used to pretty-print the Python data structures in a readable format.
🌐
PyPI
pypi.org › project › prettyprinter
prettyprinter · PyPI
Syntax-highlighting, declarative and composable pretty printer for Python 3.5+
🌐
Python
docs.python.org › uk › 3.9 › library › pprint.html
pprint — Data pretty printer — Python 3.9.25 documentation
Змінено в версії 3.4: Додано параметр compact. Змінено в версії 3.8: Додано параметр sort_dicts. pprint.pp(object, *args, sort_dicts=False, **kwargs)¶ · Prints the formatted representation of object followed by a newline.