Is it possible to change IPython's pretty printer?

239 Views Asked by At

Is it possible to change the pretty printer that IPython uses?

I'd like to switch out the default pretty printer for pprint++, which I prefer for things like nested structures:

In [42]: {"foo": [{"bar": 42}, {"bar": 16}] * 3, "bar": [1,2,3,4,5]}
Out[42]: 
{'bar': [1, 2, 3, 4, 5],
 'foo': [{'bar': 42},
  {'bar': 16},
  {'bar': 42},
  {'bar': 16},
  {'bar': 42},
  {'bar': 16}]}

In [43]: pprintpp.pprint({"foo": [{"bar": 42}, {"bar": 16}] * 5, "bar": [1,2,3,4,5]})
{
    'bar': [1, 2, 3, 4, 5],
    'foo': [
        {'bar': 42},
        {'bar': 16},
        {'bar': 42},
        {'bar': 16},
        {'bar': 42},
        {'bar': 16},
        {'bar': 42},
        {'bar': 16},
        {'bar': 42},
        {'bar': 16},
    ],
}
1

There are 1 best solutions below

1
On BEST ANSWER

This can technically be done by monkey-patching the class IPython.lib.pretty.RepresentationPrinter used here in IPython.

This is how one might do it:

In [1]: o = {"foo": [{"bar": 42}, {"bar": 16}] * 3, "bar": [1,2,3,4,5]}

In [2]: o
Out[2]: 
{'bar': [1, 2, 3, 4, 5],
 'foo': [{'bar': 42},
  {'bar': 16},
  {'bar': 42},
  {'bar': 16},
  {'bar': 42},
  {'bar': 16}]}

In [3]: import IPython.lib.pretty

In [4]: import pprintpp

In [5]: class NewRepresentationPrinter:
            def __init__(self, stream, *args, **kwargs):
                self.stream = stream
            def pretty(self, obj):
                p = pprintpp.pformat(obj)
                self.stream.write(p.rstrip())
            def flush(self):
                pass


In [6]: IPython.lib.pretty.RepresentationPrinter = NewRepresentationPrinter

In [7]: o
Out[7]: 
{
    'bar': [1, 2, 3, 4, 5],
    'foo': [
        {'bar': 42},
        {'bar': 16},
        {'bar': 42},
        {'bar': 16},
        {'bar': 42},
        {'bar': 16},
    ],
}

This is a bad idea for a multitude of reasons, but should technically work for now. Currently it doesn't seem there's an official, supported way to override all pretty-printing in IPython, at least simply.

(note: the .rstrip() is needed because IPython doesn't expect a trailing newline on the result)