簡體   English   中英

漂亮的打印數據類更漂亮

[英]Pretty-print dataclasses prettier

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還不支持數據類。

然而,漂亮的打印機 package支持數據類並提供了一些漂亮的打印功能。

例子:

[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()


注意事項:

Python 3.10+支持漂亮的打印數據類:

Python 3.10.0b2+ (heads/3.10:f807a4fad4, Sep  4 2021, 18:58:04) [GCC 11.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from dataclasses import dataclass
>>> @dataclass
... class Literal:
...     value: 'Any'
... 
>>> @dataclass
... class Binary:
...     left: 'Binary | Literal'
...     operator: str
...     right: 'Binary | Literal'
... 
>>> from pprint import pprint
>>> # magic happens here
>>> pprint(
... Binary(Binary(Literal(2), '*', Literal(100)), '+', Literal(50)))
Binary(left=Binary(left=Literal(value=2),
                   operator='*',
                   right=Literal(value=100)),
       operator='+',
       right=Literal(value=50))

可悲的是,它沒有被廣泛使用(......然而,截至 2021 年)

我們可以使用dataclasses.fields遞歸嵌套數據類並漂亮地打印它們:

from collections.abc import Mapping, Iterable
from dataclasses import is_dataclass, fields

def pretty_print(obj, indent=4):
    """
    Pretty prints a (possibly deeply-nested) dataclass.
    Each new block will be indented by `indent` spaces (default is 4).
    """
    print(stringify(obj, indent))

def stringify(obj, indent=4, _indents=0):
    if isinstance(obj, str):
        return f"'{obj}'"

    if not is_dataclass(obj) and not isinstance(obj, (Mapping, Iterable)):
        return str(obj)

    this_indent = indent * _indents * ' '
    next_indent = indent * (_indents + 1) * ' '
    start, end = f'{type(obj).__name__}(', ')'  # dicts, lists, and tuples will re-assign this

    if is_dataclass(obj):
        body = '\n'.join(
            f'{next_indent}{field.name}='
            f'{stringify(getattr(obj, field.name), indent, _indents + 1)},' for field in fields(obj)
        )

    elif isinstance(obj, Mapping):
        if isinstance(obj, dict):
            start, end = '{}'

        body = '\n'.join(
            f'{next_indent}{stringify(key, indent, _indents + 1)}: '
            f'{stringify(value, indent, _indents + 1)},' for key, value in obj.items()
        )

    else:  # is Iterable
        if isinstance(obj, list):
            start, end = '[]'
        elif isinstance(obj, tuple):
            start = '('

        body = '\n'.join(
            f'{next_indent}{stringify(item, indent, _indents + 1)},' for item in obj
        )

    return f'{start}\n{body}\n{this_indent}{end}'

我們可以使用嵌套數據類對其進行測試:

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'})

pretty_print(coords)

# Coords(
#     my_points=[
#         Point(
#             x=1,
#             y=2,
#         ),
#         Point(
#             x=3,
#             y=4,
#         ),
#     ],
#     my_dict={
#         'a': (
#             1,
#             2,
#         ),
#         (
#             1,
#             2,
#         ): 'a',
#     },
# )

這應該足以涵蓋大多數情況。 希望這可以幫助!

您可能應該使用prettyprinter但如果由於某種原因無法添加依賴項,那么您可以使用它,它比 salt-die 的示例略短(因為它使用pprint

import dataclasses
import pprint


def dcppformat(x, chars=0):
    def parts():
        if dataclasses.is_dataclass(x):
            yield type(x).__name__ + "("

            def fields():
                for field in dataclasses.fields(x):
                    nindent = chars + len(field.name) + 4
                    value = getattr(x, field.name)
                    rep_value = dcppformat(value)
                    yield " " * (chars + 3) + indent_body_chars(
                        "{}={}".format(field.name, rep_value), chars=nindent
                    )

            yield ",\n".join(fields())
            yield " " * chars + ")"
        else:
            yield pprint.pformat(x)

    return "\n".join(parts())


def indent(x, level=1):
    indent_chars(x, level * 4)


def indent_chars(x, chars=1):
    return "\n".join(" " * chars + p for p in x.split("\n"))


def indent_body_chars(x, chars=4):
    a, *b = x.split("\n")
    if b:
        return a + "\n" + indent_chars("\n".join(b), chars=chars,)
    else:
        return a


def dcpprint(x):
    print(dcppformat(x))


def test():
    @dataclasses.dataclass
    class A:
        a: object
        b: str

    dcpprint(A(a=A(a=None, b={"a": 1, "c": 1, "long": "a" * 100}), b=2))


if __name__ == "__main__":
    test()

我所關心的只是將字段放在不同的行上,所以我最終使用了dataclasses.asdictpprint.pprint

from dataclasses import dataclass, asdict
from pprint import pprint

@dataclass
class SomeClass:
   there: int
   needs: int
   to: int
   be: int
   many: int
   fields: int
   for_: int
   it: int
   to2: int
   work: int


a = SomeClass(there=1, needs=2, to=3, be=4, many=5, fields=6, for_=7, it=8, to2=9, work=10)

pprint(asdict(a), sort_dicts=False)

Output:

{'there': 1,
 'needs': 2,
 'to': 3,
 'be': 4,
 'many': 5,
 'fields': 6,
 'for_': 7,
 'it': 8,
 'to2': 9,
 'work': 10}

我使用的是 Python 3.9。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM