blob: deadf1820851595777a4e6fb398538ad81e2841a [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 Storchaka6c48bf22018-11-20 19:26:09 +020033.. index:: single: ...; placeholder
34
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030035.. class:: PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, \
36 compact=False)
Georg Brandl116aa622007-08-15 14:28:22 +000037
38 Construct a :class:`PrettyPrinter` instance. This constructor understands
39 several keyword parameters. An output stream may be set using the *stream*
40 keyword; the only method used on the stream object is the file protocol's
41 :meth:`write` method. If not specified, the :class:`PrettyPrinter` adopts
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030042 ``sys.stdout``. The
Georg Brandl116aa622007-08-15 14:28:22 +000043 amount of indentation added for each recursive level is specified by *indent*;
44 the default is one. Other values can cause output to look a little odd, but can
45 make nesting easier to spot. The number of levels which may be printed is
46 controlled by *depth*; if the data structure being printed is too deep, the next
47 contained level is replaced by ``...``. By default, there is no constraint on
48 the depth of the objects being formatted. The desired output width is
49 constrained using the *width* parameter; the default is 80 characters. If a
50 structure cannot be formatted within the constrained width, a best effort will
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030051 be made. If *compact* is false (the default) each item of a long sequence
52 will be formatted on a separate line. If *compact* is true, as many items
53 as will fit within the *width* will be formatted on each output line.
Georg Brandl116aa622007-08-15 14:28:22 +000054
Serhiy Storchaka09bb8462013-10-02 21:40:21 +030055 .. versionchanged:: 3.4
56 Added the *compact* parameter.
57
Christian Heimesb9eccbf2007-12-05 20:18:38 +000058 >>> import pprint
59 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +000060 >>> stuff.insert(0, stuff[:])
61 >>> pp = pprint.PrettyPrinter(indent=4)
62 >>> pp.pprint(stuff)
Georg Brandl3ccb7872008-07-16 03:00:45 +000063 [ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
Christian Heimesb9eccbf2007-12-05 20:18:38 +000064 'spam',
65 'eggs',
66 'lumberjack',
67 'knights',
68 'ni']
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030069 >>> pp = pprint.PrettyPrinter(width=41, compact=True)
70 >>> pp.pprint(stuff)
71 [['spam', 'eggs', 'lumberjack',
72 'knights', 'ni'],
73 'spam', 'eggs', 'lumberjack', 'knights',
74 'ni']
Christian Heimesb9eccbf2007-12-05 20:18:38 +000075 >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
76 ... ('parrot', ('fresh fruit',))))))))
Georg Brandl116aa622007-08-15 14:28:22 +000077 >>> pp = pprint.PrettyPrinter(depth=6)
78 >>> pp.pprint(tup)
Alexandre Vassalottieca20b62008-05-16 02:54:33 +000079 ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
Georg Brandl116aa622007-08-15 14:28:22 +000080
Georg Brandl18244152009-09-02 20:34:52 +000081
Antoine Pitrou64c16c32013-03-23 20:30:39 +010082The :mod:`pprint` module also provides several shortcut functions:
Georg Brandl116aa622007-08-15 14:28:22 +000083
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030084.. function:: pformat(object, indent=1, width=80, depth=None, *, compact=False)
Georg Brandl116aa622007-08-15 14:28:22 +000085
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030086 Return the formatted representation of *object* as a string. *indent*,
87 *width*, *depth* and *compact* will be passed to the :class:`PrettyPrinter`
88 constructor as formatting parameters.
Georg Brandl116aa622007-08-15 14:28:22 +000089
Serhiy Storchaka09bb8462013-10-02 21:40:21 +030090 .. versionchanged:: 3.4
91 Added the *compact* parameter.
92
Georg Brandl116aa622007-08-15 14:28:22 +000093
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030094.. function:: pprint(object, stream=None, indent=1, width=80, depth=None, *, \
95 compact=False)
Georg Brandl116aa622007-08-15 14:28:22 +000096
97 Prints the formatted representation of *object* on *stream*, followed by a
Georg Brandl18244152009-09-02 20:34:52 +000098 newline. If *stream* is ``None``, ``sys.stdout`` is used. This may be used
Georg Brandl6911e3c2007-09-04 07:15:32 +000099 in the interactive interpreter instead of the :func:`print` function for
100 inspecting values (you can even reassign ``print = pprint.pprint`` for use
Serhiy Storchaka7c411a42013-10-02 11:56:18 +0300101 within a scope). *indent*, *width*, *depth* and *compact* will be passed
102 to the :class:`PrettyPrinter` constructor as formatting parameters.
Georg Brandl116aa622007-08-15 14:28:22 +0000103
Serhiy Storchaka09bb8462013-10-02 21:40:21 +0300104 .. versionchanged:: 3.4
105 Added the *compact* parameter.
106
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000107 >>> import pprint
108 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +0000109 >>> stuff.insert(0, stuff)
110 >>> pprint.pprint(stuff)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000111 [<Recursion on list with id=...>,
112 'spam',
113 'eggs',
114 'lumberjack',
115 'knights',
116 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +0000117
Georg Brandl116aa622007-08-15 14:28:22 +0000118
119.. function:: isreadable(object)
120
121 .. index:: builtin: eval
122
123 Determine if the formatted representation of *object* is "readable," or can be
124 used to reconstruct the value using :func:`eval`. This always returns ``False``
Christian Heimesfe337bf2008-03-23 21:54:12 +0000125 for recursive objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000126
127 >>> pprint.isreadable(stuff)
128 False
129
130
131.. function:: isrecursive(object)
132
133 Determine if *object* requires a recursive representation.
134
Georg Brandl116aa622007-08-15 14:28:22 +0000135
Christian Heimesfe337bf2008-03-23 21:54:12 +0000136One more support function is also defined:
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138.. function:: saferepr(object)
139
140 Return a string representation of *object*, protected against recursive data
141 structures. If the representation of *object* exposes a recursive entry, the
142 recursive reference will be represented as ``<Recursion on typename with
143 id=number>``. The representation is not otherwise formatted.
144
Georg Brandl116aa622007-08-15 14:28:22 +0000145 >>> pprint.saferepr(stuff)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000146 "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
Georg Brandl116aa622007-08-15 14:28:22 +0000147
148
149.. _prettyprinter-objects:
150
151PrettyPrinter Objects
152---------------------
153
154:class:`PrettyPrinter` instances have the following methods:
155
156
157.. method:: PrettyPrinter.pformat(object)
158
159 Return the formatted representation of *object*. This takes into account the
160 options passed to the :class:`PrettyPrinter` constructor.
161
162
163.. method:: PrettyPrinter.pprint(object)
164
165 Print the formatted representation of *object* on the configured stream,
166 followed by a newline.
167
168The following methods provide the implementations for the corresponding
169functions of the same names. Using these methods on an instance is slightly
170more efficient since new :class:`PrettyPrinter` objects don't need to be
171created.
172
173
174.. method:: PrettyPrinter.isreadable(object)
175
176 .. index:: builtin: eval
177
178 Determine if the formatted representation of the object is "readable," or can be
179 used to reconstruct the value using :func:`eval`. Note that this returns
180 ``False`` for recursive objects. If the *depth* parameter of the
181 :class:`PrettyPrinter` is set and the object is deeper than allowed, this
182 returns ``False``.
183
184
185.. method:: PrettyPrinter.isrecursive(object)
186
187 Determine if the object requires a recursive representation.
188
189This method is provided as a hook to allow subclasses to modify the way objects
190are converted to strings. The default implementation uses the internals of the
191:func:`saferepr` implementation.
192
193
194.. method:: PrettyPrinter.format(object, context, maxlevels, level)
195
196 Returns three values: the formatted version of *object* as a string, a flag
197 indicating whether the result is readable, and a flag indicating whether
198 recursion was detected. The first argument is the object to be presented. The
199 second is a dictionary which contains the :func:`id` of objects that are part of
200 the current presentation context (direct and indirect containers for *object*
201 that are affecting the presentation) as the keys; if an object needs to be
202 presented which is already represented in *context*, the third return value
Martin Panterd5db1472016-02-08 01:34:09 +0000203 should be ``True``. Recursive calls to the :meth:`.format` method should add
Georg Brandl116aa622007-08-15 14:28:22 +0000204 additional entries for containers to this dictionary. The third argument,
205 *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there
206 is no requested limit. This argument should be passed unmodified to recursive
207 calls. The fourth argument, *level*, gives the current level; recursive calls
208 should be passed a value less than that of the current call.
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000209
210
211.. _pprint-example:
212
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200213Example
214-------
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000215
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200216To demonstrate several uses of the :func:`pprint` function and its parameters,
Stéphane Wirtel19177fb2018-05-15 20:58:35 +0200217let's fetch information about a project from `PyPI <https://pypi.org>`_::
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000218
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200219 >>> import json
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000220 >>> import pprint
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200221 >>> from urllib.request import urlopen
Pablo Galindobf46a092018-11-01 08:29:38 -0400222 >>> with urlopen('https://pypi.org/pypi/sampleproject/json') as resp:
223 ... project_info = json.load(resp)['info']
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)
Pablo Galindobf46a092018-11-01 08:29:38 -0400228 {'author': 'The Python Packaging Authority',
229 'author_email': 'pypa-dev@googlegroups.com',
230 'bugtrack_url': None,
231 'classifiers': ['Development Status :: 3 - Alpha',
232 'Intended Audience :: Developers',
233 'License :: OSI Approved :: MIT License',
234 'Programming Language :: Python :: 2',
235 'Programming Language :: Python :: 2.6',
236 'Programming Language :: Python :: 2.7',
237 'Programming Language :: Python :: 3',
238 'Programming Language :: Python :: 3.2',
239 'Programming Language :: Python :: 3.3',
240 'Programming Language :: Python :: 3.4',
241 'Topic :: Software Development :: Build Tools'],
242 'description': 'A sample Python project\n'
243 '=======================\n'
244 '\n'
245 'This is the description file for the project.\n'
246 '\n'
247 'The file should use UTF-8 encoding and be written using '
248 'ReStructured Text. It\n'
249 'will be used to generate the project webpage on PyPI, and '
250 'should be written for\n'
251 'that purpose.\n'
252 '\n'
253 'Typical contents for this file would include an overview of '
254 'the project, basic\n'
255 'usage examples, etc. Generally, including the project '
256 'changelog in here is not\n'
257 'a good idea, although a simple "What\'s New" section for the '
258 'most recent version\n'
259 'may be appropriate.',
260 'description_content_type': None,
261 'docs_url': None,
262 'download_url': 'UNKNOWN',
263 'downloads': {'last_day': -1, 'last_month': -1, 'last_week': -1},
264 'home_page': 'https://github.com/pypa/sampleproject',
265 'keywords': 'sample setuptools development',
266 'license': 'MIT',
267 'maintainer': None,
268 'maintainer_email': None,
269 'name': 'sampleproject',
270 'package_url': 'https://pypi.org/project/sampleproject/',
271 'platform': 'UNKNOWN',
272 'project_url': 'https://pypi.org/project/sampleproject/',
273 'project_urls': {'Download': 'UNKNOWN',
274 'Homepage': 'https://github.com/pypa/sampleproject'},
275 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
276 'requires_dist': None,
277 'requires_python': None,
278 'summary': 'A sample Python project',
279 'version': '1.2.0'}
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200280
281The result can be limited to a certain *depth* (ellipsis is used for deeper
282contents)::
283
Pablo Galindobf46a092018-11-01 08:29:38 -0400284 >>> pprint.pprint(project_info, depth=1)
285 {'author': 'The Python Packaging Authority',
286 'author_email': 'pypa-dev@googlegroups.com',
287 'bugtrack_url': None,
288 'classifiers': [...],
289 'description': 'A sample Python project\n'
290 '=======================\n'
291 '\n'
292 'This is the description file for the project.\n'
293 '\n'
294 'The file should use UTF-8 encoding and be written using '
295 'ReStructured Text. It\n'
296 'will be used to generate the project webpage on PyPI, and '
297 'should be written for\n'
298 'that purpose.\n'
299 '\n'
300 'Typical contents for this file would include an overview of '
301 'the project, basic\n'
302 'usage examples, etc. Generally, including the project '
303 'changelog in here is not\n'
304 'a good idea, although a simple "What\'s New" section for the '
305 'most recent version\n'
306 'may be appropriate.',
307 'description_content_type': None,
308 'docs_url': None,
309 'download_url': 'UNKNOWN',
310 'downloads': {...},
311 'home_page': 'https://github.com/pypa/sampleproject',
312 'keywords': 'sample setuptools development',
313 'license': 'MIT',
314 'maintainer': None,
315 'maintainer_email': None,
316 'name': 'sampleproject',
317 'package_url': 'https://pypi.org/project/sampleproject/',
318 'platform': 'UNKNOWN',
319 'project_url': 'https://pypi.org/project/sampleproject/',
320 'project_urls': {...},
321 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
322 'requires_dist': None,
323 'requires_python': None,
324 'summary': 'A sample Python project',
325 'version': '1.2.0'}
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200326
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100327Additionally, maximum character *width* can be suggested. If a long object
328cannot be split, the specified width will be exceeded::
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200329
Pablo Galindobf46a092018-11-01 08:29:38 -0400330 >>> pprint.pprint(project_info, depth=1, width=60)
331 {'author': 'The Python Packaging Authority',
332 'author_email': 'pypa-dev@googlegroups.com',
333 'bugtrack_url': None,
334 'classifiers': [...],
335 'description': 'A sample Python project\n'
336 '=======================\n'
337 '\n'
338 'This is the description file for the '
339 'project.\n'
340 '\n'
341 'The file should use UTF-8 encoding and be '
342 'written using ReStructured Text. It\n'
343 'will be used to generate the project '
344 'webpage on PyPI, and should be written '
345 'for\n'
346 'that purpose.\n'
347 '\n'
348 'Typical contents for this file would '
349 'include an overview of the project, '
350 'basic\n'
351 'usage examples, etc. Generally, including '
352 'the project changelog in here is not\n'
353 'a good idea, although a simple "What\'s '
354 'New" section for the most recent version\n'
355 'may be appropriate.',
356 'description_content_type': None,
357 'docs_url': None,
358 'download_url': 'UNKNOWN',
359 'downloads': {...},
360 'home_page': 'https://github.com/pypa/sampleproject',
361 'keywords': 'sample setuptools development',
362 'license': 'MIT',
363 'maintainer': None,
364 'maintainer_email': None,
365 'name': 'sampleproject',
366 'package_url': 'https://pypi.org/project/sampleproject/',
367 'platform': 'UNKNOWN',
368 'project_url': 'https://pypi.org/project/sampleproject/',
369 'project_urls': {...},
370 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
371 'requires_dist': None,
372 'requires_python': None,
373 'summary': 'A sample Python project',
374 'version': '1.2.0'}