gpt4 book ai didi

python - 是否可以更改 IPython 的 pretty-print ?

转载 作者:行者123 更新时间:2023-11-28 21:48:26 26 4
gpt4 key购买 nike

是否可以更改 IPython 使用的 pretty-print ?

我想关闭 pprint++ 的默认 pretty-print ,我更喜欢嵌套结构之类的东西:

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

最佳答案

这在技术上可以通过猴子修补类 IPython.lib.pretty.RepresentationPrinter 使用 here 来完成在 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},
],
}

出于多种原因,这是一个坏主意,但从技术上讲,目前应该可行。目前似乎没有官方的、受支持的方法来覆盖 IPython 中的所有 pretty-print ,至少是简单的。

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

关于python - 是否可以更改 IPython 的 pretty-print ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35375099/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com