blob: 207c3f8bca928b22d06fe2a66033c9c10e844b0d [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
Carl Bordum Hansen06a89162019-06-27 01:13:18 +020028.. versionchanged:: 3.9
29 Added support for pretty-printing :class:`types.SimpleNamespace`.
30
Georg Brandl116aa622007-08-15 14:28:22 +000031The :mod:`pprint` module defines one class:
32
Christian Heimes5b5e81c2007-12-31 16:14:33 +000033.. First the implementation class:
Georg Brandl116aa622007-08-15 14:28:22 +000034
35
Serhiy Storchaka6c48bf22018-11-20 19:26:09 +020036.. index:: single: ...; placeholder
37
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030038.. class:: PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, \
Rémi Lapeyre96831c72019-03-22 18:22:20 +010039 compact=False, sort_dicts=True)
Georg Brandl116aa622007-08-15 14:28:22 +000040
41 Construct a :class:`PrettyPrinter` instance. This constructor understands
42 several keyword parameters. An output stream may be set using the *stream*
43 keyword; the only method used on the stream object is the file protocol's
44 :meth:`write` method. If not specified, the :class:`PrettyPrinter` adopts
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030045 ``sys.stdout``. The
Georg Brandl116aa622007-08-15 14:28:22 +000046 amount of indentation added for each recursive level is specified by *indent*;
47 the default is one. Other values can cause output to look a little odd, but can
48 make nesting easier to spot. The number of levels which may be printed is
49 controlled by *depth*; if the data structure being printed is too deep, the next
50 contained level is replaced by ``...``. By default, there is no constraint on
51 the depth of the objects being formatted. The desired output width is
52 constrained using the *width* parameter; the default is 80 characters. If a
53 structure cannot be formatted within the constrained width, a best effort will
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030054 be made. If *compact* is false (the default) each item of a long sequence
55 will be formatted on a separate line. If *compact* is true, as many items
Rémi Lapeyre96831c72019-03-22 18:22:20 +010056 as will fit within the *width* will be formatted on each output line. If
57 *sort_dicts* is true (the default), dictionaries will be formatted with their
58 keys sorted, otherwise they will display in insertion order.
Georg Brandl116aa622007-08-15 14:28:22 +000059
Serhiy Storchaka09bb8462013-10-02 21:40:21 +030060 .. versionchanged:: 3.4
61 Added the *compact* parameter.
62
Rémi Lapeyre96831c72019-03-22 18:22:20 +010063 .. versionchanged:: 3.8
64 Added the *sort_dicts* parameter.
65
66
Christian Heimesb9eccbf2007-12-05 20:18:38 +000067 >>> import pprint
68 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +000069 >>> stuff.insert(0, stuff[:])
70 >>> pp = pprint.PrettyPrinter(indent=4)
71 >>> pp.pprint(stuff)
Georg Brandl3ccb7872008-07-16 03:00:45 +000072 [ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
Christian Heimesb9eccbf2007-12-05 20:18:38 +000073 'spam',
74 'eggs',
75 'lumberjack',
76 'knights',
77 'ni']
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030078 >>> pp = pprint.PrettyPrinter(width=41, compact=True)
79 >>> pp.pprint(stuff)
80 [['spam', 'eggs', 'lumberjack',
81 'knights', 'ni'],
82 'spam', 'eggs', 'lumberjack', 'knights',
83 'ni']
Christian Heimesb9eccbf2007-12-05 20:18:38 +000084 >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
85 ... ('parrot', ('fresh fruit',))))))))
Georg Brandl116aa622007-08-15 14:28:22 +000086 >>> pp = pprint.PrettyPrinter(depth=6)
87 >>> pp.pprint(tup)
Alexandre Vassalottieca20b62008-05-16 02:54:33 +000088 ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
Georg Brandl116aa622007-08-15 14:28:22 +000089
Georg Brandl18244152009-09-02 20:34:52 +000090
Antoine Pitrou64c16c32013-03-23 20:30:39 +010091The :mod:`pprint` module also provides several shortcut functions:
Georg Brandl116aa622007-08-15 14:28:22 +000092
Rémi Lapeyre96831c72019-03-22 18:22:20 +010093.. function:: pformat(object, indent=1, width=80, depth=None, *, \
94 compact=False, sort_dicts=True)
Georg Brandl116aa622007-08-15 14:28:22 +000095
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030096 Return the formatted representation of *object* as a string. *indent*,
Rémi Lapeyre96831c72019-03-22 18:22:20 +010097 *width*, *depth*, *compact* and *sort_dicts* will be passed to the
98 :class:`PrettyPrinter` constructor as formatting parameters.
Georg Brandl116aa622007-08-15 14:28:22 +000099
Serhiy Storchaka09bb8462013-10-02 21:40:21 +0300100 .. versionchanged:: 3.4
101 Added the *compact* parameter.
102
Rémi Lapeyre96831c72019-03-22 18:22:20 +0100103 .. versionchanged:: 3.8
104 Added the *sort_dicts* parameter.
105
106
107.. function:: pp(object, *args, sort_dicts=False, **kwargs)
108
109 Prints the formatted representation of *object* followed by a newline.
110 If *sort_dicts* is false (the default), dictionaries will be displayed with
111 their keys in insertion order, otherwise the dict keys will be sorted.
Xavier GUIHOT7c822e52019-03-23 01:17:29 +0000112 *args* and *kwargs* will be passed to :func:`pprint` as formatting
Rémi Lapeyre96831c72019-03-22 18:22:20 +0100113 parameters.
114
115 .. versionadded:: 3.8
116
Georg Brandl116aa622007-08-15 14:28:22 +0000117
Serhiy Storchaka7c411a42013-10-02 11:56:18 +0300118.. function:: pprint(object, stream=None, indent=1, width=80, depth=None, *, \
Rémi Lapeyre96831c72019-03-22 18:22:20 +0100119 compact=False, sort_dicts=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000120
121 Prints the formatted representation of *object* on *stream*, followed by a
Georg Brandl18244152009-09-02 20:34:52 +0000122 newline. If *stream* is ``None``, ``sys.stdout`` is used. This may be used
Georg Brandl6911e3c2007-09-04 07:15:32 +0000123 in the interactive interpreter instead of the :func:`print` function for
124 inspecting values (you can even reassign ``print = pprint.pprint`` for use
Rémi Lapeyre96831c72019-03-22 18:22:20 +0100125 within a scope). *indent*, *width*, *depth*, *compact* and *sort_dicts* will
126 be passed to the :class:`PrettyPrinter` constructor as formatting parameters.
Georg Brandl116aa622007-08-15 14:28:22 +0000127
Serhiy Storchaka09bb8462013-10-02 21:40:21 +0300128 .. versionchanged:: 3.4
129 Added the *compact* parameter.
130
Rémi Lapeyre96831c72019-03-22 18:22:20 +0100131 .. versionchanged:: 3.8
132 Added the *sort_dicts* parameter.
133
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000134 >>> import pprint
135 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +0000136 >>> stuff.insert(0, stuff)
137 >>> pprint.pprint(stuff)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000138 [<Recursion on list with id=...>,
139 'spam',
140 'eggs',
141 'lumberjack',
142 'knights',
143 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +0000144
Georg Brandl116aa622007-08-15 14:28:22 +0000145
146.. function:: isreadable(object)
147
148 .. index:: builtin: eval
149
150 Determine if the formatted representation of *object* is "readable," or can be
151 used to reconstruct the value using :func:`eval`. This always returns ``False``
Christian Heimesfe337bf2008-03-23 21:54:12 +0000152 for recursive objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000153
154 >>> pprint.isreadable(stuff)
155 False
156
157
158.. function:: isrecursive(object)
159
160 Determine if *object* requires a recursive representation.
161
Georg Brandl116aa622007-08-15 14:28:22 +0000162
Christian Heimesfe337bf2008-03-23 21:54:12 +0000163One more support function is also defined:
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165.. function:: saferepr(object)
166
167 Return a string representation of *object*, protected against recursive data
168 structures. If the representation of *object* exposes a recursive entry, the
169 recursive reference will be represented as ``<Recursion on typename with
170 id=number>``. The representation is not otherwise formatted.
171
Georg Brandl116aa622007-08-15 14:28:22 +0000172 >>> pprint.saferepr(stuff)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000173 "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
Georg Brandl116aa622007-08-15 14:28:22 +0000174
175
176.. _prettyprinter-objects:
177
178PrettyPrinter Objects
179---------------------
180
181:class:`PrettyPrinter` instances have the following methods:
182
183
184.. method:: PrettyPrinter.pformat(object)
185
186 Return the formatted representation of *object*. This takes into account the
187 options passed to the :class:`PrettyPrinter` constructor.
188
189
190.. method:: PrettyPrinter.pprint(object)
191
192 Print the formatted representation of *object* on the configured stream,
193 followed by a newline.
194
195The following methods provide the implementations for the corresponding
196functions of the same names. Using these methods on an instance is slightly
197more efficient since new :class:`PrettyPrinter` objects don't need to be
198created.
199
200
201.. method:: PrettyPrinter.isreadable(object)
202
203 .. index:: builtin: eval
204
205 Determine if the formatted representation of the object is "readable," or can be
206 used to reconstruct the value using :func:`eval`. Note that this returns
207 ``False`` for recursive objects. If the *depth* parameter of the
208 :class:`PrettyPrinter` is set and the object is deeper than allowed, this
209 returns ``False``.
210
211
212.. method:: PrettyPrinter.isrecursive(object)
213
214 Determine if the object requires a recursive representation.
215
216This method is provided as a hook to allow subclasses to modify the way objects
217are converted to strings. The default implementation uses the internals of the
218:func:`saferepr` implementation.
219
220
221.. method:: PrettyPrinter.format(object, context, maxlevels, level)
222
223 Returns three values: the formatted version of *object* as a string, a flag
224 indicating whether the result is readable, and a flag indicating whether
225 recursion was detected. The first argument is the object to be presented. The
226 second is a dictionary which contains the :func:`id` of objects that are part of
227 the current presentation context (direct and indirect containers for *object*
228 that are affecting the presentation) as the keys; if an object needs to be
229 presented which is already represented in *context*, the third return value
Martin Panterd5db1472016-02-08 01:34:09 +0000230 should be ``True``. Recursive calls to the :meth:`.format` method should add
Georg Brandl116aa622007-08-15 14:28:22 +0000231 additional entries for containers to this dictionary. The third argument,
232 *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there
233 is no requested limit. This argument should be passed unmodified to recursive
234 calls. The fourth argument, *level*, gives the current level; recursive calls
235 should be passed a value less than that of the current call.
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000236
237
238.. _pprint-example:
239
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200240Example
241-------
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000242
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200243To demonstrate several uses of the :func:`pprint` function and its parameters,
Stéphane Wirtel19177fb2018-05-15 20:58:35 +0200244let's fetch information about a project from `PyPI <https://pypi.org>`_::
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000245
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200246 >>> import json
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000247 >>> import pprint
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200248 >>> from urllib.request import urlopen
Pablo Galindobf46a092018-11-01 08:29:38 -0400249 >>> with urlopen('https://pypi.org/pypi/sampleproject/json') as resp:
250 ... project_info = json.load(resp)['info']
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000251
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200252In its basic form, :func:`pprint` shows the whole object::
253
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100254 >>> pprint.pprint(project_info)
Pablo Galindobf46a092018-11-01 08:29:38 -0400255 {'author': 'The Python Packaging Authority',
256 'author_email': 'pypa-dev@googlegroups.com',
257 'bugtrack_url': None,
258 'classifiers': ['Development Status :: 3 - Alpha',
259 'Intended Audience :: Developers',
260 'License :: OSI Approved :: MIT License',
261 'Programming Language :: Python :: 2',
262 'Programming Language :: Python :: 2.6',
263 'Programming Language :: Python :: 2.7',
264 'Programming Language :: Python :: 3',
265 'Programming Language :: Python :: 3.2',
266 'Programming Language :: Python :: 3.3',
267 'Programming Language :: Python :: 3.4',
268 'Topic :: Software Development :: Build Tools'],
269 'description': 'A sample Python project\n'
270 '=======================\n'
271 '\n'
272 'This is the description file for the project.\n'
273 '\n'
274 'The file should use UTF-8 encoding and be written using '
275 'ReStructured Text. It\n'
276 'will be used to generate the project webpage on PyPI, and '
277 'should be written for\n'
278 'that purpose.\n'
279 '\n'
280 'Typical contents for this file would include an overview of '
281 'the project, basic\n'
282 'usage examples, etc. Generally, including the project '
283 'changelog in here is not\n'
284 'a good idea, although a simple "What\'s New" section for the '
285 'most recent version\n'
286 'may be appropriate.',
287 'description_content_type': None,
288 'docs_url': None,
289 'download_url': 'UNKNOWN',
290 'downloads': {'last_day': -1, 'last_month': -1, 'last_week': -1},
291 'home_page': 'https://github.com/pypa/sampleproject',
292 'keywords': 'sample setuptools development',
293 'license': 'MIT',
294 'maintainer': None,
295 'maintainer_email': None,
296 'name': 'sampleproject',
297 'package_url': 'https://pypi.org/project/sampleproject/',
298 'platform': 'UNKNOWN',
299 'project_url': 'https://pypi.org/project/sampleproject/',
300 'project_urls': {'Download': 'UNKNOWN',
301 'Homepage': 'https://github.com/pypa/sampleproject'},
302 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
303 'requires_dist': None,
304 'requires_python': None,
305 'summary': 'A sample Python project',
306 'version': '1.2.0'}
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200307
308The result can be limited to a certain *depth* (ellipsis is used for deeper
309contents)::
310
Pablo Galindobf46a092018-11-01 08:29:38 -0400311 >>> pprint.pprint(project_info, depth=1)
312 {'author': 'The Python Packaging Authority',
313 'author_email': 'pypa-dev@googlegroups.com',
314 'bugtrack_url': None,
315 'classifiers': [...],
316 'description': 'A sample Python project\n'
317 '=======================\n'
318 '\n'
319 'This is the description file for the project.\n'
320 '\n'
321 'The file should use UTF-8 encoding and be written using '
322 'ReStructured Text. It\n'
323 'will be used to generate the project webpage on PyPI, and '
324 'should be written for\n'
325 'that purpose.\n'
326 '\n'
327 'Typical contents for this file would include an overview of '
328 'the project, basic\n'
329 'usage examples, etc. Generally, including the project '
330 'changelog in here is not\n'
331 'a good idea, although a simple "What\'s New" section for the '
332 'most recent version\n'
333 'may be appropriate.',
334 'description_content_type': None,
335 'docs_url': None,
336 'download_url': 'UNKNOWN',
337 'downloads': {...},
338 'home_page': 'https://github.com/pypa/sampleproject',
339 'keywords': 'sample setuptools development',
340 'license': 'MIT',
341 'maintainer': None,
342 'maintainer_email': None,
343 'name': 'sampleproject',
344 'package_url': 'https://pypi.org/project/sampleproject/',
345 'platform': 'UNKNOWN',
346 'project_url': 'https://pypi.org/project/sampleproject/',
347 'project_urls': {...},
348 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
349 'requires_dist': None,
350 'requires_python': None,
351 'summary': 'A sample Python project',
352 'version': '1.2.0'}
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200353
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100354Additionally, maximum character *width* can be suggested. If a long object
355cannot be split, the specified width will be exceeded::
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200356
Pablo Galindobf46a092018-11-01 08:29:38 -0400357 >>> pprint.pprint(project_info, depth=1, width=60)
358 {'author': 'The Python Packaging Authority',
359 'author_email': 'pypa-dev@googlegroups.com',
360 'bugtrack_url': None,
361 'classifiers': [...],
362 'description': 'A sample Python project\n'
363 '=======================\n'
364 '\n'
365 'This is the description file for the '
366 'project.\n'
367 '\n'
368 'The file should use UTF-8 encoding and be '
369 'written using ReStructured Text. It\n'
370 'will be used to generate the project '
371 'webpage on PyPI, and should be written '
372 'for\n'
373 'that purpose.\n'
374 '\n'
375 'Typical contents for this file would '
376 'include an overview of the project, '
377 'basic\n'
378 'usage examples, etc. Generally, including '
379 'the project changelog in here is not\n'
380 'a good idea, although a simple "What\'s '
381 'New" section for the most recent version\n'
382 'may be appropriate.',
383 'description_content_type': None,
384 'docs_url': None,
385 'download_url': 'UNKNOWN',
386 'downloads': {...},
387 'home_page': 'https://github.com/pypa/sampleproject',
388 'keywords': 'sample setuptools development',
389 'license': 'MIT',
390 'maintainer': None,
391 'maintainer_email': None,
392 'name': 'sampleproject',
393 'package_url': 'https://pypi.org/project/sampleproject/',
394 'platform': 'UNKNOWN',
395 'project_url': 'https://pypi.org/project/sampleproject/',
396 'project_urls': {...},
397 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
398 'requires_dist': None,
399 'requires_python': None,
400 'summary': 'A sample Python project',
401 'version': '1.2.0'}