Skip to content

pretty

This module calls install() on import, and defines print as pprint.

It allows setting up pretty print functionality in only one line.

Usage
>>> from pytermgui.pretty import print

PTGFormatter

Bases: BaseFormatter

An IPython formatter for PTG pretty printing.

Source code in pytermgui/pretty.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
class PTGFormatter(BaseFormatter):  # pylint: disable=too-few-public-methods
    """An IPython formatter for PTG pretty printing."""

    def __init__(self, **kwargs: Any) -> None:
        """Initializes PTGFormatter, storing **kwargs."""

        super().__init__()

        self.kwargs = kwargs

    def __call__(self, value: Any) -> None:
        """Pretty prints the given value, as well as a leading newline.

        The newline is needed since IPython output is prepended with
        "Out[i]:", and it might mess alignments up.
        """

        builtins.print("\n")
        pprint(value, **self.kwargs)

        # Sets up "_" as a way to access return value,
        # inkeeping with sys.displayhook
        builtins._ = value  # type: ignore

__call__(value)

Pretty prints the given value, as well as a leading newline.

The newline is needed since IPython output is prepended with "Out[i]:", and it might mess alignments up.

Source code in pytermgui/pretty.py
164
165
166
167
168
169
170
171
172
173
174
175
176
def __call__(self, value: Any) -> None:
    """Pretty prints the given value, as well as a leading newline.

    The newline is needed since IPython output is prepended with
    "Out[i]:", and it might mess alignments up.
    """

    builtins.print("\n")
    pprint(value, **self.kwargs)

    # Sets up "_" as a way to access return value,
    # inkeeping with sys.displayhook
    builtins._ = value  # type: ignore

__init__(**kwargs)

Initializes PTGFormatter, storing **kwargs.

Source code in pytermgui/pretty.py
157
158
159
160
161
162
def __init__(self, **kwargs: Any) -> None:
    """Initializes PTGFormatter, storing **kwargs."""

    super().__init__()

    self.kwargs = kwargs

install(indent=2, force_markup=False, expand_all=False)

Sets up pprint to print all REPL output. IPython is also supported.

This function sets up a hook that will call pprint after every interactive return. The given arguments are passed directly to pprint, so for more information you can check out that function.

Usage is pretty simple:

>>> from pytermgui import pretty
>>> tim.setup_displayhook()
>>> # Any function output will now be prettified

...or alternatively, you can import print from pytermgui.pretty, and have it automatically set up, and replace your namespace's print function with tim.pprint:

>>> from pytermgui.pretty import print
... # Under the hood, the above is called and `tim.pprint` is set
... # for the `print` name
>>> # Any function output will now be prettified

Parameters:

Name Type Description Default
indent int

The indentation value used for multi-line objects. This is ignored when the given object has a len() < 2, and expand_all is not set.

2
force_markup bool

Turn all ANSI-sequences into tim before pretty printing.

False
expand_all bool

Force-expand containers, even when they would normally be collapsed.

False
Source code in pytermgui/pretty.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def install(
    indent: int = 2, force_markup: bool = False, expand_all: bool = False
) -> None:
    """Sets up `pprint` to print all REPL output. IPython is also supported.

    This function sets up a hook that will call `pprint` after every interactive return.
    The given arguments are passed directly to `pprint`, so for more information
    you can check out that function.

    Usage is pretty simple:

    ```python3
    >>> from pytermgui import pretty
    >>> tim.setup_displayhook()
    >>> # Any function output will now be prettified
    ```

    ...or alternatively, you can import `print` from `pytermgui.pretty`,
    and have it automatically set up, and replace your namespace's `print`
    function with `tim.pprint`:

    ```python3
    >>> from pytermgui.pretty import print
    ... # Under the hood, the above is called and `tim.pprint` is set
    ... # for the `print` name
    >>> # Any function output will now be prettified
    ```

    Args:
        indent: The indentation value used for multi-line objects. This is ignored when
            the given object has a `len() < 2`, and `expand_all is not set.`
        force_markup: Turn all ANSI-sequences into tim before pretty printing.
        expand_all: Force-expand containers, even when they would normally be collapsed.
    """

    def _hook(value: Any) -> None:
        if value is None:
            return

        pprint(value, force_markup=force_markup, indent=indent, expand_all=expand_all)

        # Sets up "_" as a way to access return value,
        # inkeeping with sys.displayhook
        builtins._ = value  # type: ignore

    if IPYTHON is not None:
        IPYTHON.display_formatter.formatters["text/plain"] = PTGFormatter(
            force_markup=force_markup, indent=indent, expand_all=expand_all
        )

    else:
        sys.displayhook = _hook

    if not NO_WELCOME:
        with get_terminal().no_record():
            builtins.print()
            tim.print("[113 bold]Successfully set up prettification!")
            tim.print("[245 italic]> All function returns will now be pretty-printed,")
            builtins.print()
            pprint("[245 italic]Including [/italic 210]Markup!")
            builtins.print()

    get_terminal().displayhook_installed = True

pprint(*items, indent=2, expand_all=False, force_markup=False, parse=True, **print_args)

A wrapper to pretty-print any object.

This essentially just calls prettify on each given object, and passes the **print_args right through to print. Note that when the sep print argument is ommitted it is manually set to ", \n".

To customize any of the styles, see MarkupLanguage.prettify.

Parameters:

Name Type Description Default
*items Any

The items to print. These are passed in the same way they would be into builtin print.

()
indent int

The indentation value used for multi-line objects. This is ignored when the given object has a len() < 2, and expand_all is not set.

2
force_markup bool

Turn all ANSI-sequences into markup before pretty printing.

False
expand_all bool

Force-expand containers, even when they would normally be collapsed.

False
**print_args Any

All arguments passed to builtin print.

{}
Source code in pytermgui/pretty.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def pprint(
    *items: Any,
    indent: int = 2,
    expand_all: bool = False,
    force_markup: bool = False,
    parse: bool = True,
    **print_args: Any,
) -> None:
    r"""A wrapper to pretty-print any object.

    This essentially just calls `prettify` on each given object, and passes the
    `**print_args` right through to print. Note that when the `sep` print argument is
    ommitted it is manually set to `", \n"`.

    To customize any of the styles, see `MarkupLanguage.prettify`.

    Args:
        *items: The items to print. These are passed in the same way they would be into
            builtin print.
        indent: The indentation value used for multi-line objects. This is ignored when
            the given object has a `len() < 2`, and `expand_all is not set.`
        force_markup: Turn all ANSI-sequences into markup before pretty printing.
        expand_all: Force-expand containers, even when they would normally be collapsed.
        **print_args: All arguments passed to builtin print.
    """

    if "sep" not in print_args:
        print_args["sep"] = ", \n"

    pretty = []
    for item in items:
        pretty.append(
            prettify(
                item,
                force_markup=force_markup,
                indent=indent,
                expand_all=expand_all,
                parse=parse,
            )
        )

    get_terminal().print(*pretty, **print_args)