漂亮的打印数据类更漂亮
Python数据类实例还包括一个字符串表示方法,但是当类具有多个字段和/或更长的字段值时,它的结果对于漂亮的打印目的来说并不足够。
基本上,我正在寻找一种方法来自定义默认的数据类字符串表示例程,或者寻找一种理解数据类并更漂亮地打印它们的漂亮打印机。
所以,这只是我想到的一个小自定义:在每个字段之后添加一个换行符,同时在第一个字段之后缩进行。
例如,代替
x = InventoryItem('foo', 23)
print(x) # =>
InventoryItem(name='foo', unit_price=23, quantity_on_hand=0)
我想得到这样的字符串表示:
x = InventoryItem('foo', 23)
print(x) # =>
InventoryItem(
name='foo',
unit_price=23,
quantity_on_hand=0
)
或者类似的。也许漂亮的打印机可以变得更漂亮,例如对齐=分配字符或类似的东西。
当然,它也应该以递归方式工作,例如,也是数据类的字段应该缩进更多。
回答
截至 2021 年(Python 3.9),Python 的标准pprint 还不支持数据类。
然而,prettyprinter包支持数据类并提供一些漂亮的打印功能。
例子:
[ins] In [1]: from dataclasses import dataclass
...:
...: @dataclass
...: class Point:
...: x: int
...: y: int
...:
...: @dataclass
...: class Coords:
...: my_points: list
...: my_dict: dict
...:
...: coords = Coords([Point(1, 2), Point(3, 4)], {'a': (1, 2), (1, 2): 'a'})
[nav] In [2]: import prettyprinter as pp
[ins] In [3]: pp.pprint(coords)
Coords(my_points=[Point(x=1, y=2), Point(x=3, y=4)], my_dict={'a': (1, 2), (1, 2): 'a'})
默认情况下,未启用数据类支持,因此:
[nav] In [4]: pp.install_extras()
[ins] In [5]: pp.pprint(coords)
Coords(
my_points=[Point(x=1, y=2), Point(x=3, y=4)],
my_dict={'a': (1, 2), (1, 2): 'a'}
)
或者强制缩进所有字段:
[ins] In [6]: pp.pprint(coords, width=1)
Coords(
my_points=[
Point(
x=1,
y=2
),
Point(
x=3,
y=4
)
],
my_dict={
'a': (
1,
2
),
(
1,
2
): 'a'
}
)
Prettyprinter 甚至可以语法高亮!(参见cpprint())
注意事项:
- Prettyprinter 不是 python 标准库的一部分
- 根本不打印默认值,截至 2021 年,没有办法解决这个问题