Search code examples
pythonpython-3.xpprint

Python 3.x: alternative pprint implementation


Standard pprint module is nice when deals with lists, dicts and so on. But sometimes completely unusable with custom classes:

  • The only way to make it print usable information about an object of some class is to override __repr__, but what if my class already have nice, eval()'able __repr__ which is not showing the information I want to see in pprint ouput?

  • Ok, I will write print-oriented __repr__, but in this case it is impossible to pretty-print something inside my class:

.

class Data:
    def __init__(self):
        self.d = {...}

I can't pretty-print self.d contents, I can return one-line representation only(at least without playing with stacktraces, etc). - Overriding PrettyPrinter is not an option, I dont want to do it every time I want to pretty-print the same class.

So... Is there any alternatives to pprint which allows to make a custom class pretty-printable?


Solution

  • There is an improved and maintained Python 2.x/3.x port of "pretty" library in IPython: https://ipython.readthedocs.io/en/stable/api/generated/IPython.lib.pretty.html