Debian Codegraph @

docs/source/pretty.rst

raw
1 Pretty Printing
2 ===============
3
4 In addition to syntax highlighting, Rich will format (i.e. *pretty print*) containers such as lists, dicts, and sets.
5
6 Run the following command to see an example of pretty printed output::
7
8 python -m rich.pretty
9
10 Note how the output will change to fit within the terminal width.
11
12 pprint method
13 -------------
14
15 The :func:`~rich.pretty.pprint` method offers a few more arguments you can use to tweak how objects are pretty printed. Here's how you would import it::
16
17 >>> from rich.pretty import pprint
18 >>> pprint(locals())
19
20 Indent guides
21 ~~~~~~~~~~~~~
22
23 Rich can draw *indent guides* to highlight the indent level of a data structure. These can make it easier to read more deeply nested output. The pprint method enables indent guides by default. You can set ``indent_guides=False`` to disable this feature.
24
25 Expand all
26 ~~~~~~~~~~
27
28 Rich is quite conservative about expanding data structures and will try to fit as much in each line as it can. If you prefer, you can tell Rich to fully expand all data structures by setting ``expand_all=True``. Here's an example::
29
30 >>> pprint(["eggs", "ham"], expand_all=True)
31
32 Truncating pretty output
33 ~~~~~~~~~~~~~~~~~~~~~~~~
34
35 Very long data structures can be difficult to read and you may find yourself scrolling through multiple pages in the terminal to find the data you are interested in. Rich can truncate containers and long strings to give you an overview without swamping your terminal.
36
37
38 If you set the ``max_length`` argument to an integer, Rich will truncate containers with more than the given number of elements. If data is truncated, Rich will display an ellipsis ``...`` and the number of elements not shown.
39
40 Here's an example::
41
42 >>> pprint(locals(), max_length=2)
43
44 If you set the ``max_string`` argument to an integer, Rich will truncate strings over that length. Truncated string will be appended with the number of characters that have not been shown. Here's an example::
45
46 >>> pprint("Where there is a Will, there is a Way", max_string=21)
47
48 Pretty renderable
49 -----------------
50
51 Rich offers a :class:`~rich.pretty.Pretty` class which you can use to insert pretty printed data in to another renderable.
52
53 The following example displays pretty printed data within a simple panel::
54
55 from rich import print
56 from rich.pretty import Pretty
57 from rich.panel import Panel
58
59 pretty = Pretty(locals())
60 panel = Panel(pretty)
61 print(panel)
62
63 There are a large number of options to tweak the pretty formatting, See the :class:`~rich.pretty.Pretty` reference for details.
64
65 Rich Repr Protocol
66 ------------------
67
68 Rich is able to syntax highlight any output, but the formatting is restricted to built-in containers, dataclasses, and other objects Rich knows about, such as objects generated by the `attrs <https://www.attrs.org/en/stable/>`_ library. To add Rich formatting capabilities to custom objects, you can implement the *rich repr protocol*.
69
70 Run the following command to see an example of what the Rich repr protocol can generate::
71
72 python -m rich.repr
73
74 First, let's look at a class that might benefit from a Rich repr::
75
76 class Bird:
77 def __init__(self, name, eats=None, fly=True, extinct=False):
78 self.name = name
79 self.eats = list(eats) if eats else []
80 self.fly = fly
81 self.extinct = extinct
82
83 def __repr__(self):
84 return f"Bird({self.name!r}, eats={self.eats!r}, fly={self.fly!r}, extinct={self.extinct!r})"
85
86 BIRDS = {
87 "gull": Bird("gull", eats=["fish", "chips", "ice cream", "sausage rolls"]),
88 "penguin": Bird("penguin", eats=["fish"], fly=False),
89 "dodo": Bird("dodo", eats=["fruit"], fly=False, extinct=True)
90 }
91 print(BIRDS)
92
93 The result of this script would be::
94
95 {'gull': Bird('gull', eats=['fish', 'chips', 'ice cream', 'sausage rolls'], fly=True, extinct=False), 'penguin': Bird('penguin', eats=['fish'], fly=False, extinct=False), 'dodo': Bird('dodo', eats=['fruit'], fly=False, extinct=True)}
96
97 The output is long enough to wrap on to the next line, which can make it hard to read. The repr strings are informative but a little verbose since they include default arguments. If we print this with Rich, things are improved somewhat::
98
99 {
100 'gull': Bird('gull', eats=['fish', 'chips', 'ice cream', 'sausage rolls'],
101 fly=True, extinct=False),
102 'penguin': Bird('penguin', eats=['fish'], fly=False, extinct=False),
103 'dodo': Bird('dodo', eats=['fruit'], fly=False, extinct=True)
104 }
105
106 Rich knows how to format the container dict, but the repr strings are still verbose, and there is some wrapping of the output (assumes an 80 character terminal).
107
108 We can solve both these issues by adding the following ``__rich_repr__`` method::
109
110 def __rich_repr__(self):
111 yield self.name
112 yield "eats", self.eats
113 yield "fly", self.fly, True
114 yield "extinct", self.extinct, False
115
116 Now if we print the same object with Rich we would see the following::
117
118 {
119 'gull': Bird(
120 'gull',
121 eats=['fish', 'chips', 'ice cream', 'sausage rolls']
122 ),
123 'penguin': Bird('penguin', eats=['fish'], fly=False),
124 'dodo': Bird('dodo', eats=['fruit'], fly=False, extinct=True)
125 }
126
127 The default arguments have been omitted, and the output has been formatted nicely. The output remains readable even if we have less room in the terminal, or our objects are part of a deeply nested data structure::
128
129 {
130 'gull': Bird(
131 'gull',
132 eats=[
133 'fish',
134 'chips',
135 'ice cream',
136 'sausage rolls'
137 ]
138 ),
139 'penguin': Bird(
140 'penguin',
141 eats=['fish'],
142 fly=False
143 ),
144 'dodo': Bird(
145 'dodo',
146 eats=['fruit'],
147 fly=False,
148 extinct=True
149 )
150 }
151
152 You can add a ``__rich_repr__`` method to any class to enable the Rich formatting. This method should return an iterable of tuples. You could return a list of tuples, but it's easier to express with the ``yield`` keywords, making it a *generator*.
153
154 Each tuple specifies an element in the output.
155
156 - ``yield value`` will generate a positional argument.
157 - ``yield name, value`` will generate a keyword argument.
158 - ``yield name, value, default`` will generate a keyword argument *if* ``value`` is not equal to ``default``.
159
160 If you use ``None`` as the ``name``, then it will be treated as a positional argument as well, in order to support having ``tuple`` positional arguments.
161
162 You can also tell Rich to generate the *angular bracket* style of repr, which tend to be used where there is no easy way to recreate the object's constructor. To do this set the function attribute ``"angular"`` to ``True`` immediately after your ``__rich_repr__`` method. For example::
163
164 __rich_repr__.angular = True
165
166 This will change the output of the Rich repr example to the following::
167
168 {
169 'gull': <Bird 'gull' eats=['fish', 'chips', 'ice cream', 'sausage rolls']>,
170 'penguin': <Bird 'penguin' eats=['fish'] fly=False>,
171 'dodo': <Bird 'dodo' eats=['fruit'] fly=False extinct=True>
172 }
173
174
175 Note that you can add ``__rich_repr__`` methods to third-party libraries *without* including Rich as a dependency. If Rich is not installed, then nothing will break. Hopefully more third-party libraries will adopt Rich repr methods in the future.
176
177 Typing
178 ~~~~~~
179
180 If you want to type the Rich repr method you can import and return ``rich.repr.Result``, which will help catch logical errors::
181
182
183 import rich.repr
184
185
186 class Bird:
187 def __init__(self, name, eats=None, fly=True, extinct=False):
188 self.name = name
189 self.eats = list(eats) if eats else []
190 self.fly = fly
191 self.extinct = extinct
192
193 def __rich_repr__(self) -> rich.repr.Result:
194 yield self.name
195 yield "eats", self.eats
196 yield "fly", self.fly, True
197 yield "extinct", self.extinct, False
198
199
200 Automatic Rich Repr
201 ~~~~~~~~~~~~~~~~~~~
202
203 Rich can generate a rich repr automatically if the parameters are named the same as your attributes.
204
205 To automatically build a rich repr, use the :meth:`~rich.repr.auto` class decorator. The Bird example above follows the above rule, so we don't strictly need to implement our own ``__rich_repr__``. The following code would generate the same repr::
206
207 import rich.repr
208
209 @rich.repr.auto
210 class Bird:
211 def __init__(self, name, eats=None, fly=True, extinct=False):
212 self.name = name
213 self.eats = list(eats) if eats else []
214 self.fly = fly
215 self.extinct = extinct
216
217
218 BIRDS = {
219 "gull": Bird("gull", eats=["fish", "chips", "ice cream", "sausage rolls"]),
220 "penguin": Bird("penguin", eats=["fish"], fly=False),
221 "dodo": Bird("dodo", eats=["fruit"], fly=False, extinct=True)
222 }
223 from rich import print
224 print(BIRDS)
225
226 Note that the decorator will also create a `__repr__`, so you will get an auto-generated repr even if you don't print with Rich.
227
228 If you want to auto-generate the angular type of repr, then set ``angular=True`` on the decorator::
229
230 @rich.repr.auto(angular=True)
231 class Bird:
232 def __init__(self, name, eats=None, fly=True, extinct=False):
233 self.name = name
234 self.eats = list(eats) if eats else []
235 self.fly = fly
236 self.extinct = extinct
237
238
239 Example
240 -------
241
242 See `repr.py <https://github.com/willmcgugan/rich/blob/master/examples/repr.py>`_ for the example code used in this page.