简体   繁体   中英

Pretty print __str__ of custom python objects

In the following two classes:

from dataclasses import dataclass
from typing import List

@dataclasses
class A:
    statements: List[str]
    def __str__(self) -> str:
        return "\n".join(f"{s}" for s in self.statements)
@dataclasses
class B:
    objects: List[A]
    def __str__(self) -> str:
        return "From B\n".join(f"{o}" for o in self.objects)

is there a way to print them in a pretty way respecting also indentation. Meaning that when I only print object AI will get a list of whatever it holds:

A

hello
world

and when I print BI will have:

B

From B
    hello
    world

My own tests only ident the first object:

>>> a = A(statements=[1, 2, 3])
>>> b = A(statements=[4, 5, 6])
>>> print(a)
1
2
3
>>> dd = B(objects=[a, b])
>>> print(dd)
From B
    1
2
3
    4
5
6

You can use thetextwrap module from the standard library:

>>> from dataclasses import dataclass
>>> from typing import List
>>> import textwrap

>>> @dataclass
    class A:
        statements: List[str]
        def __str__(self) -> str:
            return "\n".join(f"{s}" for s in self.statements)

    @dataclass
    class B:
        objects: List[A]
        def __str__(self) -> str:
            return "From B\n" + textwrap.indent(
                "\n".join(str(o) for o in self.objects),
                "    ",
            )

>>> alphas = [A(statements=[1, 2, 3]), A(statements=[4, 5, 6])]
>>> beta = B(objects=alphas)
>>> delta = B(objects=[beta])
>>> print(str(delta))
From B
    From B
        1
        2
        3
        4
        5
        6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM