标准pprint
模块在处理列表、字典等时非常有用。但有时完全无法与自定义类一起使用:
让它打印关于某个类的对象的可用信息的唯一方法是覆盖
__repr__
,但是如果我的类已经有 nice,eval()
'able__repr__
没有显示我想在 pprint 输出中看到的信息?好吧,我会写面向打印的
__repr__
,但在这种情况下,不可能在我的类中漂亮地打印一些东西:
.
class Data:
def __init__(self):
self.d = {...}
我不能漂亮地打印 self.d
内容,我只能返回单行表示(至少不使用堆栈跟踪等)。
- 覆盖 PrettyPrinter
不是一个选项,我不想每次都想 pretty-print 同一个类时都这样做。
那么...有没有 pprint 的替代方案可以使自定义类更适合打印?
最佳答案
IPython 中有一个改进和维护的“漂亮”库的 Python 2.x/3.x 端口:https://ipython.readthedocs.io/en/stable/api/generated/IPython.lib.pretty.html
关于 python 3.x : alternative pprint implementation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16633456/