漂亮的打印 Python 字典

Pretty print Python dict

我习惯使用 pprint 模块来漂亮地打印我的内置 Python 容器对象,例如 dictlist。但是,在打印时,我面临着强制容器在包含的对象上使用 __str__ 的困难(因为默认情况下它们在包含的对象上使用 __repr__ 方法),同时保持漂亮打印。

这是一个例子:

import pprint

class H:
    """ Example of a contained object
    """
    def __str__(self):
        return "This is my H class string representation"

    def __repr__(self):
        return "H()"

d = {
    'a': H(),
    'b': {
        'c': H(),
        'd': H()
    }
}

pprint.pprint(d, width=10)

returns 印得很漂亮:

{'a': H(),
 'b': {'c': H(),
       'd': H()}}

但是如您所见,__repr__ 是在 H 对象上调用的。

为了强制 dict 在包含的对象上使用 __str__,有些人建议使用 join()。类似于:

print("{" + "\n".join("{!r}: {!s},".format(k, v) for k, v in d.items()) + "}")

哪个returns:

{'a': This is my H class string representation,
'b': {'c': H(), 'd': H()},}

而且显然不适用于嵌套字典,而且在这种情况下也无法使用 pprint,因为在连接之后我们得到一个字符串。

理想情况下我想要打印的是:

{'a': This is my H class string representation,
 'b': {'c': This is my H class string representation,
       'd': This is my H class string representation}}

对于上下文,我的字典的键总是字符串,值是有问题的对象,例如 H(),我需要 __str__ 表示而不是 __repr__.

Python 允许动态更改 classes 中的方法。所以你可以暂时让 __repr__ 成为 __str__:

def str_pprint(d):
    sv = H.__repr__
    H.__repr__ = H.__str__
    pprint.pprint(d, width=10)
    H.__repr__ = sv

str_pprint(d)

根据您的数据,它给出了预期的结果:

{'a': This is my H class string representation,
 'b': {'c': This is my H class string representation,
       'd': This is my H class string representation}}

但是注意:这会全局更改class属性,因此如果需要多个执行线程(多线程程序或中断处理程序)则不能使用它。