2

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},
    ],
}
4

1 に答える 1

6

これは技術的には、ここで IPython でIPython.lib.pretty.RepresentationPrinter使用されているクラスにモンキー パッチを適用することで実行できます。

これを行う方法は次のとおりです。

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},
    ],
}

これは多くの理由から悪い考えですが、今のところ技術的にはうまくいくはずです。現在、少なくとも単純に、IPython のすべてのプリティ プリンティングをオーバーライドする公式のサポートされている方法はないようです。

(注: .rstrip()IPython は結果の末尾の改行を想定していないため、が必要です)

于 2016-02-13T02:13:48.690 に答える