是否有可能改变IPython的漂亮打印机?

Dav*_*ver 2 python ipython pprint

是否有可能改变IPython使用的漂亮的打印机?

我想切换默认的漂亮的打印机pprint++,我更喜欢嵌套结构之类的东西:

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},
    ],
}
Run Code Online (Sandbox Code Playgroud)

Aly*_*sen 5

这可以通过技术上猴子修补类完成IPython.lib.pretty.RepresentationPrinter使用这里的IPython中.

这就是人们可能会这样做的方式:

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},
    ],
}
Run Code Online (Sandbox Code Playgroud)

出于多种原因,这是一个糟糕的主意,但从技术上来说应该是现在的工作.目前似乎没有官方的,支持的方式来覆盖IPython中的所有漂亮打印,至少简单.

(注意:这.rstrip()是必需的,因为IPython不期望结果的尾随换行符)