漂亮的Python字典

时间:2020-07-21 10:01:26

标签: python string dictionary printing pretty-print

我曾经使用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)

返回d精美打印:

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

但是您可以看到__repr__在H个对象上被调用。

为强制字典在包含的对象上使用__str__,有人建议使用join()。像这样:

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

返回:

{'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__

1 个答案:

答案 0 :(得分:1)

Python允许动态更改类中的方法。因此,您可以暂时将__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}}

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