blob: aa97d3eabafabdc2b677a74afbd45a4f4cb468e6 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`pprint` --- Data pretty printer
2=====================================
3
4.. module:: pprint
5 :synopsis: Data pretty printer.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
8.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
9
Raymond Hettinger10480942011-01-10 03:26:08 +000010**Source code:** :source:`Lib/pprint.py`
Georg Brandl116aa622007-08-15 14:28:22 +000011
Raymond Hettinger4f707fd2011-01-10 19:54:11 +000012--------------
13
Georg Brandl116aa622007-08-15 14:28:22 +000014The :mod:`pprint` module provides a capability to "pretty-print" arbitrary
15Python data structures in a form which can be used as input to the interpreter.
16If the formatted structures include objects which are not fundamental Python
17types, the representation may not be loadable. This may be the case if objects
Antoine Pitrou64c16c32013-03-23 20:30:39 +010018such as files, sockets or classes are included, as well as many other
19objects which are not representable as Python literals.
Georg Brandl116aa622007-08-15 14:28:22 +000020
21The formatted representation keeps objects on a single line if it can, and
22breaks them onto multiple lines if they don't fit within the allowed width.
23Construct :class:`PrettyPrinter` objects explicitly if you need to adjust the
24width constraint.
25
Georg Brandl55ac8f02007-09-01 13:51:09 +000026Dictionaries are sorted by key before the display is computed.
Georg Brandl116aa622007-08-15 14:28:22 +000027
28The :mod:`pprint` module defines one class:
29
Christian Heimes5b5e81c2007-12-31 16:14:33 +000030.. First the implementation class:
Georg Brandl116aa622007-08-15 14:28:22 +000031
32
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030033.. class:: PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, \
34 compact=False)
Georg Brandl116aa622007-08-15 14:28:22 +000035
36 Construct a :class:`PrettyPrinter` instance. This constructor understands
37 several keyword parameters. An output stream may be set using the *stream*
38 keyword; the only method used on the stream object is the file protocol's
39 :meth:`write` method. If not specified, the :class:`PrettyPrinter` adopts
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030040 ``sys.stdout``. The
Georg Brandl116aa622007-08-15 14:28:22 +000041 amount of indentation added for each recursive level is specified by *indent*;
42 the default is one. Other values can cause output to look a little odd, but can
43 make nesting easier to spot. The number of levels which may be printed is
44 controlled by *depth*; if the data structure being printed is too deep, the next
45 contained level is replaced by ``...``. By default, there is no constraint on
46 the depth of the objects being formatted. The desired output width is
47 constrained using the *width* parameter; the default is 80 characters. If a
48 structure cannot be formatted within the constrained width, a best effort will
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030049 be made. If *compact* is false (the default) each item of a long sequence
50 will be formatted on a separate line. If *compact* is true, as many items
51 as will fit within the *width* will be formatted on each output line.
Georg Brandl116aa622007-08-15 14:28:22 +000052
Serhiy Storchaka09bb8462013-10-02 21:40:21 +030053 .. versionchanged:: 3.4
54 Added the *compact* parameter.
55
Christian Heimesb9eccbf2007-12-05 20:18:38 +000056 >>> import pprint
57 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +000058 >>> stuff.insert(0, stuff[:])
59 >>> pp = pprint.PrettyPrinter(indent=4)
60 >>> pp.pprint(stuff)
Georg Brandl3ccb7872008-07-16 03:00:45 +000061 [ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
Christian Heimesb9eccbf2007-12-05 20:18:38 +000062 'spam',
63 'eggs',
64 'lumberjack',
65 'knights',
66 'ni']
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030067 >>> pp = pprint.PrettyPrinter(width=41, compact=True)
68 >>> pp.pprint(stuff)
69 [['spam', 'eggs', 'lumberjack',
70 'knights', 'ni'],
71 'spam', 'eggs', 'lumberjack', 'knights',
72 'ni']
Christian Heimesb9eccbf2007-12-05 20:18:38 +000073 >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
74 ... ('parrot', ('fresh fruit',))))))))
Georg Brandl116aa622007-08-15 14:28:22 +000075 >>> pp = pprint.PrettyPrinter(depth=6)
76 >>> pp.pprint(tup)
Alexandre Vassalottieca20b62008-05-16 02:54:33 +000077 ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
Georg Brandl116aa622007-08-15 14:28:22 +000078
Georg Brandl18244152009-09-02 20:34:52 +000079
Antoine Pitrou64c16c32013-03-23 20:30:39 +010080The :mod:`pprint` module also provides several shortcut functions:
Georg Brandl116aa622007-08-15 14:28:22 +000081
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030082.. function:: pformat(object, indent=1, width=80, depth=None, *, compact=False)
Georg Brandl116aa622007-08-15 14:28:22 +000083
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030084 Return the formatted representation of *object* as a string. *indent*,
85 *width*, *depth* and *compact* will be passed to the :class:`PrettyPrinter`
86 constructor as formatting parameters.
Georg Brandl116aa622007-08-15 14:28:22 +000087
Serhiy Storchaka09bb8462013-10-02 21:40:21 +030088 .. versionchanged:: 3.4
89 Added the *compact* parameter.
90
Georg Brandl116aa622007-08-15 14:28:22 +000091
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030092.. function:: pprint(object, stream=None, indent=1, width=80, depth=None, *, \
93 compact=False)
Georg Brandl116aa622007-08-15 14:28:22 +000094
95 Prints the formatted representation of *object* on *stream*, followed by a
Georg Brandl18244152009-09-02 20:34:52 +000096 newline. If *stream* is ``None``, ``sys.stdout`` is used. This may be used
Georg Brandl6911e3c2007-09-04 07:15:32 +000097 in the interactive interpreter instead of the :func:`print` function for
98 inspecting values (you can even reassign ``print = pprint.pprint`` for use
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030099 within a scope). *indent*, *width*, *depth* and *compact* will be passed
100 to the :class:`PrettyPrinter` constructor as formatting parameters.
Georg Brandl116aa622007-08-15 14:28:22 +0000101
Serhiy Storchaka09bb8462013-10-02 21:40:21 +0300102 .. versionchanged:: 3.4
103 Added the *compact* parameter.
104
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000105 >>> import pprint
106 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +0000107 >>> stuff.insert(0, stuff)
108 >>> pprint.pprint(stuff)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000109 [<Recursion on list with id=...>,
110 'spam',
111 'eggs',
112 'lumberjack',
113 'knights',
114 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +0000115
Georg Brandl116aa622007-08-15 14:28:22 +0000116
117.. function:: isreadable(object)
118
119 .. index:: builtin: eval
120
121 Determine if the formatted representation of *object* is "readable," or can be
122 used to reconstruct the value using :func:`eval`. This always returns ``False``
Christian Heimesfe337bf2008-03-23 21:54:12 +0000123 for recursive objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000124
125 >>> pprint.isreadable(stuff)
126 False
127
128
129.. function:: isrecursive(object)
130
131 Determine if *object* requires a recursive representation.
132
Georg Brandl116aa622007-08-15 14:28:22 +0000133
Christian Heimesfe337bf2008-03-23 21:54:12 +0000134One more support function is also defined:
Georg Brandl116aa622007-08-15 14:28:22 +0000135
136.. function:: saferepr(object)
137
138 Return a string representation of *object*, protected against recursive data
139 structures. If the representation of *object* exposes a recursive entry, the
140 recursive reference will be represented as ``<Recursion on typename with
141 id=number>``. The representation is not otherwise formatted.
142
Georg Brandl116aa622007-08-15 14:28:22 +0000143 >>> pprint.saferepr(stuff)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000144 "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
Georg Brandl116aa622007-08-15 14:28:22 +0000145
146
147.. _prettyprinter-objects:
148
149PrettyPrinter Objects
150---------------------
151
152:class:`PrettyPrinter` instances have the following methods:
153
154
155.. method:: PrettyPrinter.pformat(object)
156
157 Return the formatted representation of *object*. This takes into account the
158 options passed to the :class:`PrettyPrinter` constructor.
159
160
161.. method:: PrettyPrinter.pprint(object)
162
163 Print the formatted representation of *object* on the configured stream,
164 followed by a newline.
165
166The following methods provide the implementations for the corresponding
167functions of the same names. Using these methods on an instance is slightly
168more efficient since new :class:`PrettyPrinter` objects don't need to be
169created.
170
171
172.. method:: PrettyPrinter.isreadable(object)
173
174 .. index:: builtin: eval
175
176 Determine if the formatted representation of the object is "readable," or can be
177 used to reconstruct the value using :func:`eval`. Note that this returns
178 ``False`` for recursive objects. If the *depth* parameter of the
179 :class:`PrettyPrinter` is set and the object is deeper than allowed, this
180 returns ``False``.
181
182
183.. method:: PrettyPrinter.isrecursive(object)
184
185 Determine if the object requires a recursive representation.
186
187This method is provided as a hook to allow subclasses to modify the way objects
188are converted to strings. The default implementation uses the internals of the
189:func:`saferepr` implementation.
190
191
192.. method:: PrettyPrinter.format(object, context, maxlevels, level)
193
194 Returns three values: the formatted version of *object* as a string, a flag
195 indicating whether the result is readable, and a flag indicating whether
196 recursion was detected. The first argument is the object to be presented. The
197 second is a dictionary which contains the :func:`id` of objects that are part of
198 the current presentation context (direct and indirect containers for *object*
199 that are affecting the presentation) as the keys; if an object needs to be
200 presented which is already represented in *context*, the third return value
Martin Panterd5db1472016-02-08 01:34:09 +0000201 should be ``True``. Recursive calls to the :meth:`.format` method should add
Georg Brandl116aa622007-08-15 14:28:22 +0000202 additional entries for containers to this dictionary. The third argument,
203 *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there
204 is no requested limit. This argument should be passed unmodified to recursive
205 calls. The fourth argument, *level*, gives the current level; recursive calls
206 should be passed a value less than that of the current call.
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000207
208
209.. _pprint-example:
210
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200211Example
212-------
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000213
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200214To demonstrate several uses of the :func:`pprint` function and its parameters,
Stéphane Wirtel19177fb2018-05-15 20:58:35 +0200215let's fetch information about a project from `PyPI <https://pypi.org>`_::
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000216
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200217 >>> import json
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000218 >>> import pprint
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200219 >>> from urllib.request import urlopen
Stéphane Wirtel19177fb2018-05-15 20:58:35 +0200220 >>> with urlopen('http://pypi.org/project/Twisted/json') as url:
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200221 ... http_info = url.info()
222 ... raw_data = url.read().decode(http_info.get_content_charset())
Éric Araujo6a21f552011-05-29 03:46:31 +0200223 >>> project_info = json.loads(raw_data)
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000224
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200225In its basic form, :func:`pprint` shows the whole object::
226
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100227 >>> pprint.pprint(project_info)
228 {'info': {'_pypi_hidden': False,
229 '_pypi_ordering': 125,
230 'author': 'Glyph Lefkowitz',
231 'author_email': 'glyph@twistedmatrix.com',
232 'bugtrack_url': '',
233 'cheesecake_code_kwalitee_id': None,
234 'cheesecake_documentation_id': None,
235 'cheesecake_installability_id': None,
236 'classifiers': ['Programming Language :: Python :: 2.6',
237 'Programming Language :: Python :: 2.7',
238 'Programming Language :: Python :: 2 :: Only'],
Serhiy Storchakafcfcf852015-04-05 08:22:41 +0300239 'description': 'An extensible framework for Python programming, with '
240 'special focus\r\n'
241 'on event-based network programming and multiprotocol '
242 'integration.',
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100243 'docs_url': '',
244 'download_url': 'UNKNOWN',
245 'home_page': 'http://twistedmatrix.com/',
246 'keywords': '',
247 'license': 'MIT',
248 'maintainer': '',
249 'maintainer_email': '',
250 'name': 'Twisted',
Stéphane Wirtel19177fb2018-05-15 20:58:35 +0200251 'package_url': 'http://pypi.org/project/Twisted',
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100252 'platform': 'UNKNOWN',
Stéphane Wirtel19177fb2018-05-15 20:58:35 +0200253 'release_url': 'http://pypi.org/project/Twisted/12.3.0',
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100254 'requires_python': None,
255 'stable_version': None,
256 'summary': 'An asynchronous networking framework written in Python',
257 'version': '12.3.0'},
258 'urls': [{'comment_text': '',
259 'downloads': 71844,
260 'filename': 'Twisted-12.3.0.tar.bz2',
261 'has_sig': False,
262 'md5_digest': '6e289825f3bf5591cfd670874cc0862d',
263 'packagetype': 'sdist',
264 'python_version': 'source',
265 'size': 2615733,
266 'upload_time': '2012-12-26T12:47:03',
Stéphane Wirtel19177fb2018-05-15 20:58:35 +0200267 'url': 'https://pypi.org/packages/source/T/Twisted/Twisted-12.3.0.tar.bz2'},
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100268 {'comment_text': '',
269 'downloads': 5224,
270 'filename': 'Twisted-12.3.0.win32-py2.7.msi',
271 'has_sig': False,
272 'md5_digest': '6b778f5201b622a5519a2aca1a2fe512',
273 'packagetype': 'bdist_msi',
274 'python_version': '2.7',
275 'size': 2916352,
276 'upload_time': '2012-12-26T12:48:15',
Stéphane Wirtel19177fb2018-05-15 20:58:35 +0200277 'url': 'https://pypi.org/packages/2.7/T/Twisted/Twisted-12.3.0.win32-py2.7.msi'}]}
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200278
279The result can be limited to a certain *depth* (ellipsis is used for deeper
280contents)::
281
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100282 >>> pprint.pprint(project_info, depth=2)
283 {'info': {'_pypi_hidden': False,
284 '_pypi_ordering': 125,
285 'author': 'Glyph Lefkowitz',
286 'author_email': 'glyph@twistedmatrix.com',
287 'bugtrack_url': '',
288 'cheesecake_code_kwalitee_id': None,
289 'cheesecake_documentation_id': None,
290 'cheesecake_installability_id': None,
291 'classifiers': [...],
Serhiy Storchakafcfcf852015-04-05 08:22:41 +0300292 'description': 'An extensible framework for Python programming, with '
293 'special focus\r\n'
294 'on event-based network programming and multiprotocol '
295 'integration.',
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100296 'docs_url': '',
297 'download_url': 'UNKNOWN',
298 'home_page': 'http://twistedmatrix.com/',
299 'keywords': '',
300 'license': 'MIT',
301 'maintainer': '',
302 'maintainer_email': '',
303 'name': 'Twisted',
Stéphane Wirtel19177fb2018-05-15 20:58:35 +0200304 'package_url': 'http://pypi.org/project/Twisted',
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100305 'platform': 'UNKNOWN',
Stéphane Wirtel19177fb2018-05-15 20:58:35 +0200306 'release_url': 'http://pypi.org/project/Twisted/12.3.0',
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100307 'requires_python': None,
308 'stable_version': None,
309 'summary': 'An asynchronous networking framework written in Python',
310 'version': '12.3.0'},
311 'urls': [{...}, {...}]}
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200312
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100313Additionally, maximum character *width* can be suggested. If a long object
314cannot be split, the specified width will be exceeded::
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200315
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100316 >>> pprint.pprint(project_info, depth=2, width=50)
317 {'info': {'_pypi_hidden': False,
318 '_pypi_ordering': 125,
319 'author': 'Glyph Lefkowitz',
320 'author_email': 'glyph@twistedmatrix.com',
321 'bugtrack_url': '',
322 'cheesecake_code_kwalitee_id': None,
323 'cheesecake_documentation_id': None,
324 'cheesecake_installability_id': None,
325 'classifiers': [...],
326 'description': 'An extensible '
Serhiy Storchakafcfcf852015-04-05 08:22:41 +0300327 'framework for Python '
328 'programming, with '
329 'special focus\r\n'
330 'on event-based network '
331 'programming and '
332 'multiprotocol '
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100333 'integration.',
334 'docs_url': '',
335 'download_url': 'UNKNOWN',
336 'home_page': 'http://twistedmatrix.com/',
337 'keywords': '',
338 'license': 'MIT',
339 'maintainer': '',
340 'maintainer_email': '',
341 'name': 'Twisted',
Stéphane Wirtel19177fb2018-05-15 20:58:35 +0200342 'package_url': 'http://pypi.org/project/Twisted',
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100343 'platform': 'UNKNOWN',
Stéphane Wirtel19177fb2018-05-15 20:58:35 +0200344 'release_url': 'http://pypi.org/project/Twisted/12.3.0',
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100345 'requires_python': None,
346 'stable_version': None,
Serhiy Storchakafcfcf852015-04-05 08:22:41 +0300347 'summary': 'An asynchronous networking '
348 'framework written in '
349 'Python',
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100350 'version': '12.3.0'},
351 'urls': [{...}, {...}]}