Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 581
Equidamoid Avatar asked May 19 '13 10:05

Equidamoid


2 Answers

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

like image 133
Mikhail Korobov Avatar answered Sep 24 '22 00:09

Mikhail Korobov


If the pretty module satisfies your needs, you can make it work with Python 3.

  1. Download and unpack the pretty.py file.
  2. Run 2to3 on it:

    python -m lib2to3 -w pretty.py
    
  3. Comment out the following lines:

    569: types.DictProxyType:        _dict_pprinter_factory('<dictproxy {', '}>'),
    580: xrange:                     _repr_pprint,
    
  4. Put the file near your script.

  5. Import it as usual:

    import pretty
    
like image 31
utapyngo Avatar answered Sep 24 '22 00:09

utapyngo