Search code examples
pythonipythonpretty-print

Copy IPython's pretty printing of results


When displaying results in IPython (without using print()), nested objects gets an easy-to-view formatting. Is there a way to create/copy a function in Python with the same pretty formatting functionalities as IPython uses? I have been trying to look through their code for a possible module to import, but it seems like an impossible task. Would it be possible to write one yourself?

IPython example:

In [1]: {'Mario': {'Stats': [63, 10, 69, 24, 82], 'Result': [(2, 7, 5, {'ids': 
[46737432927499418861568L, 61421050754327147184128L, 46239274047769245908992L]})]}, 
'Luigi': {'Results': [(7, 9, 6, {'ids': [20471482889415933558784L, 
87284089722223609249792L, 27117156251036496691200L]})], 'Stats': [14, 71, 93, 49, 53]}}

Out[1]: 
{'Luigi': {'Results': [(7,
    9,
    6,
    {'ids': [20471482889415933558784L,
      87284089722223609249792L,
      27117156251036496691200L]})],
  'Stats': [14, 71, 93, 49, 53]},
 'Mario': {'Result': [(2,
    7,
    5,
    {'ids': [46737432927499418861568L,
      61421050754327147184128L,
      46239274047769245908992L]})],
  'Stats': [63, 10, 69, 24, 82]}}

[EDIT] I know of the pprint module, but it does not do indentations the same way as IPython does (I don't want the indentation level of child elements to be dependent on their parent).

What pprint outputs:

{'Luigi': {'Results': [(7,
                        9,
                        6,
                        {'ids': [20471482889415933558784L,
                                 87284089722223609249792L,
                                 27117156251036496691200L]})],
           'Stats': [14, 71, 93, 49, 53]},
 'Mario': {'Result': [(2,
                       7,
                       5,
                       {'ids': [46737432927499418861568L,
                                61421050754327147184128L,
                                46239274047769245908992L]})],
           'Stats': [63, 10, 69, 24, 82]}}

Solution

  • IPython uses its own formatter, IPython.core.formatters.PlainTextFormatter, for output pretty-printing. If you want to use it, you'll either need to install IPython or copy the IPython.lib.pretty source. With IPython installed, you can use

    from IPython.lib.pretty import pprint
    
    pprint(your_big_ugly_data_structure)
    

    If you want to copy the source, it's available on Github. It looks like the only dependencies on the rest of IPython are trivial to remove. Take note of the license.