blob: c0589a31a90e5d7d2d39ba5c5d0badcdecf32207 [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.
6.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
7.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
8
Raymond Hettinger10480942011-01-10 03:26:08 +00009**Source code:** :source:`Lib/pprint.py`
Georg Brandl116aa622007-08-15 14:28:22 +000010
Raymond Hettinger4f707fd2011-01-10 19:54:11 +000011--------------
12
Georg Brandl116aa622007-08-15 14:28:22 +000013The :mod:`pprint` module provides a capability to "pretty-print" arbitrary
14Python data structures in a form which can be used as input to the interpreter.
15If the formatted structures include objects which are not fundamental Python
16types, the representation may not be loadable. This may be the case if objects
Antoine Pitrou64c16c32013-03-23 20:30:39 +010017such as files, sockets or classes are included, as well as many other
18objects which are not representable as Python literals.
Georg Brandl116aa622007-08-15 14:28:22 +000019
20The formatted representation keeps objects on a single line if it can, and
21breaks them onto multiple lines if they don't fit within the allowed width.
22Construct :class:`PrettyPrinter` objects explicitly if you need to adjust the
23width constraint.
24
Georg Brandl55ac8f02007-09-01 13:51:09 +000025Dictionaries are sorted by key before the display is computed.
Georg Brandl116aa622007-08-15 14:28:22 +000026
27The :mod:`pprint` module defines one class:
28
Christian Heimes5b5e81c2007-12-31 16:14:33 +000029.. First the implementation class:
Georg Brandl116aa622007-08-15 14:28:22 +000030
31
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030032.. class:: PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, \
33 compact=False)
Georg Brandl116aa622007-08-15 14:28:22 +000034
35 Construct a :class:`PrettyPrinter` instance. This constructor understands
36 several keyword parameters. An output stream may be set using the *stream*
37 keyword; the only method used on the stream object is the file protocol's
38 :meth:`write` method. If not specified, the :class:`PrettyPrinter` adopts
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030039 ``sys.stdout``. The
Georg Brandl116aa622007-08-15 14:28:22 +000040 amount of indentation added for each recursive level is specified by *indent*;
41 the default is one. Other values can cause output to look a little odd, but can
42 make nesting easier to spot. The number of levels which may be printed is
43 controlled by *depth*; if the data structure being printed is too deep, the next
44 contained level is replaced by ``...``. By default, there is no constraint on
45 the depth of the objects being formatted. The desired output width is
46 constrained using the *width* parameter; the default is 80 characters. If a
47 structure cannot be formatted within the constrained width, a best effort will
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030048 be made. If *compact* is false (the default) each item of a long sequence
49 will be formatted on a separate line. If *compact* is true, as many items
50 as will fit within the *width* will be formatted on each output line.
Georg Brandl116aa622007-08-15 14:28:22 +000051
Serhiy Storchaka09bb8462013-10-02 21:40:21 +030052 .. versionchanged:: 3.4
53 Added the *compact* parameter.
54
Christian Heimesb9eccbf2007-12-05 20:18:38 +000055 >>> import pprint
56 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +000057 >>> stuff.insert(0, stuff[:])
58 >>> pp = pprint.PrettyPrinter(indent=4)
59 >>> pp.pprint(stuff)
Georg Brandl3ccb7872008-07-16 03:00:45 +000060 [ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
Christian Heimesb9eccbf2007-12-05 20:18:38 +000061 'spam',
62 'eggs',
63 'lumberjack',
64 'knights',
65 'ni']
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030066 >>> pp = pprint.PrettyPrinter(width=41, compact=True)
67 >>> pp.pprint(stuff)
68 [['spam', 'eggs', 'lumberjack',
69 'knights', 'ni'],
70 'spam', 'eggs', 'lumberjack', 'knights',
71 'ni']
Christian Heimesb9eccbf2007-12-05 20:18:38 +000072 >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
73 ... ('parrot', ('fresh fruit',))))))))
Georg Brandl116aa622007-08-15 14:28:22 +000074 >>> pp = pprint.PrettyPrinter(depth=6)
75 >>> pp.pprint(tup)
Alexandre Vassalottieca20b62008-05-16 02:54:33 +000076 ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
Georg Brandl116aa622007-08-15 14:28:22 +000077
Georg Brandl18244152009-09-02 20:34:52 +000078
Antoine Pitrou64c16c32013-03-23 20:30:39 +010079The :mod:`pprint` module also provides several shortcut functions:
Georg Brandl116aa622007-08-15 14:28:22 +000080
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030081.. function:: pformat(object, indent=1, width=80, depth=None, *, compact=False)
Georg Brandl116aa622007-08-15 14:28:22 +000082
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030083 Return the formatted representation of *object* as a string. *indent*,
84 *width*, *depth* and *compact* will be passed to the :class:`PrettyPrinter`
85 constructor as formatting parameters.
Georg Brandl116aa622007-08-15 14:28:22 +000086
Serhiy Storchaka09bb8462013-10-02 21:40:21 +030087 .. versionchanged:: 3.4
88 Added the *compact* parameter.
89
Georg Brandl116aa622007-08-15 14:28:22 +000090
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030091.. function:: pprint(object, stream=None, indent=1, width=80, depth=None, *, \
92 compact=False)
Georg Brandl116aa622007-08-15 14:28:22 +000093
94 Prints the formatted representation of *object* on *stream*, followed by a
Georg Brandl18244152009-09-02 20:34:52 +000095 newline. If *stream* is ``None``, ``sys.stdout`` is used. This may be used
Georg Brandl6911e3c2007-09-04 07:15:32 +000096 in the interactive interpreter instead of the :func:`print` function for
97 inspecting values (you can even reassign ``print = pprint.pprint`` for use
Serhiy Storchaka7c411a42013-10-02 11:56:18 +030098 within a scope). *indent*, *width*, *depth* and *compact* will be passed
99 to the :class:`PrettyPrinter` constructor as formatting parameters.
Georg Brandl116aa622007-08-15 14:28:22 +0000100
Serhiy Storchaka09bb8462013-10-02 21:40:21 +0300101 .. versionchanged:: 3.4
102 Added the *compact* parameter.
103
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000104 >>> import pprint
105 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +0000106 >>> stuff.insert(0, stuff)
107 >>> pprint.pprint(stuff)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000108 [<Recursion on list with id=...>,
109 'spam',
110 'eggs',
111 'lumberjack',
112 'knights',
113 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +0000114
Georg Brandl116aa622007-08-15 14:28:22 +0000115
116.. function:: isreadable(object)
117
118 .. index:: builtin: eval
119
120 Determine if the formatted representation of *object* is "readable," or can be
121 used to reconstruct the value using :func:`eval`. This always returns ``False``
Christian Heimesfe337bf2008-03-23 21:54:12 +0000122 for recursive objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124 >>> pprint.isreadable(stuff)
125 False
126
127
128.. function:: isrecursive(object)
129
130 Determine if *object* requires a recursive representation.
131
Georg Brandl116aa622007-08-15 14:28:22 +0000132
Christian Heimesfe337bf2008-03-23 21:54:12 +0000133One more support function is also defined:
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135.. function:: saferepr(object)
136
137 Return a string representation of *object*, protected against recursive data
138 structures. If the representation of *object* exposes a recursive entry, the
139 recursive reference will be represented as ``<Recursion on typename with
140 id=number>``. The representation is not otherwise formatted.
141
Georg Brandl116aa622007-08-15 14:28:22 +0000142 >>> pprint.saferepr(stuff)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000143 "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
Georg Brandl116aa622007-08-15 14:28:22 +0000144
145
146.. _prettyprinter-objects:
147
148PrettyPrinter Objects
149---------------------
150
151:class:`PrettyPrinter` instances have the following methods:
152
153
154.. method:: PrettyPrinter.pformat(object)
155
156 Return the formatted representation of *object*. This takes into account the
157 options passed to the :class:`PrettyPrinter` constructor.
158
159
160.. method:: PrettyPrinter.pprint(object)
161
162 Print the formatted representation of *object* on the configured stream,
163 followed by a newline.
164
165The following methods provide the implementations for the corresponding
166functions of the same names. Using these methods on an instance is slightly
167more efficient since new :class:`PrettyPrinter` objects don't need to be
168created.
169
170
171.. method:: PrettyPrinter.isreadable(object)
172
173 .. index:: builtin: eval
174
175 Determine if the formatted representation of the object is "readable," or can be
176 used to reconstruct the value using :func:`eval`. Note that this returns
177 ``False`` for recursive objects. If the *depth* parameter of the
178 :class:`PrettyPrinter` is set and the object is deeper than allowed, this
179 returns ``False``.
180
181
182.. method:: PrettyPrinter.isrecursive(object)
183
184 Determine if the object requires a recursive representation.
185
186This method is provided as a hook to allow subclasses to modify the way objects
187are converted to strings. The default implementation uses the internals of the
188:func:`saferepr` implementation.
189
190
191.. method:: PrettyPrinter.format(object, context, maxlevels, level)
192
193 Returns three values: the formatted version of *object* as a string, a flag
194 indicating whether the result is readable, and a flag indicating whether
195 recursion was detected. The first argument is the object to be presented. The
196 second is a dictionary which contains the :func:`id` of objects that are part of
197 the current presentation context (direct and indirect containers for *object*
198 that are affecting the presentation) as the keys; if an object needs to be
199 presented which is already represented in *context*, the third return value
200 should be ``True``. Recursive calls to the :meth:`format` method should add
201 additional entries for containers to this dictionary. The third argument,
202 *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there
203 is no requested limit. This argument should be passed unmodified to recursive
204 calls. The fourth argument, *level*, gives the current level; recursive calls
205 should be passed a value less than that of the current call.
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000206
207
208.. _pprint-example:
209
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200210Example
211-------
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000212
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200213To demonstrate several uses of the :func:`pprint` function and its parameters,
Georg Brandl525d3552014-10-29 10:26:56 +0100214let's fetch information about a project from `PyPI <https://pypi.python.org/pypi>`_::
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000215
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200216 >>> import json
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000217 >>> import pprint
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200218 >>> from urllib.request import urlopen
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100219 >>> with urlopen('http://pypi.python.org/pypi/Twisted/json') as url:
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200220 ... http_info = url.info()
221 ... raw_data = url.read().decode(http_info.get_content_charset())
Éric Araujo6a21f552011-05-29 03:46:31 +0200222 >>> project_info = json.loads(raw_data)
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000223
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200224In its basic form, :func:`pprint` shows the whole object::
225
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100226 >>> pprint.pprint(project_info)
227 {'info': {'_pypi_hidden': False,
228 '_pypi_ordering': 125,
229 'author': 'Glyph Lefkowitz',
230 'author_email': 'glyph@twistedmatrix.com',
231 'bugtrack_url': '',
232 'cheesecake_code_kwalitee_id': None,
233 'cheesecake_documentation_id': None,
234 'cheesecake_installability_id': None,
235 'classifiers': ['Programming Language :: Python :: 2.6',
236 'Programming Language :: Python :: 2.7',
237 'Programming Language :: Python :: 2 :: Only'],
238 'description': 'An extensible framework for Python programming, '
239 'with special focus\r\n'
240 'on event-based network programming and '
241 'multiprotocol integration.',
242 'docs_url': '',
243 'download_url': 'UNKNOWN',
244 'home_page': 'http://twistedmatrix.com/',
245 'keywords': '',
246 'license': 'MIT',
247 'maintainer': '',
248 'maintainer_email': '',
249 'name': 'Twisted',
250 'package_url': 'http://pypi.python.org/pypi/Twisted',
251 'platform': 'UNKNOWN',
252 'release_url': 'http://pypi.python.org/pypi/Twisted/12.3.0',
253 'requires_python': None,
254 'stable_version': None,
255 'summary': 'An asynchronous networking framework written in Python',
256 'version': '12.3.0'},
257 'urls': [{'comment_text': '',
258 'downloads': 71844,
259 'filename': 'Twisted-12.3.0.tar.bz2',
260 'has_sig': False,
261 'md5_digest': '6e289825f3bf5591cfd670874cc0862d',
262 'packagetype': 'sdist',
263 'python_version': 'source',
264 'size': 2615733,
265 'upload_time': '2012-12-26T12:47:03',
266 'url': 'https://pypi.python.org/packages/source/T/Twisted/Twisted-12.3.0.tar.bz2'},
267 {'comment_text': '',
268 'downloads': 5224,
269 'filename': 'Twisted-12.3.0.win32-py2.7.msi',
270 'has_sig': False,
271 'md5_digest': '6b778f5201b622a5519a2aca1a2fe512',
272 'packagetype': 'bdist_msi',
273 'python_version': '2.7',
274 'size': 2916352,
275 'upload_time': '2012-12-26T12:48:15',
276 'url': 'https://pypi.python.org/packages/2.7/T/Twisted/Twisted-12.3.0.win32-py2.7.msi'}]}
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200277
278The result can be limited to a certain *depth* (ellipsis is used for deeper
279contents)::
280
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100281 >>> pprint.pprint(project_info, depth=2)
282 {'info': {'_pypi_hidden': False,
283 '_pypi_ordering': 125,
284 'author': 'Glyph Lefkowitz',
285 'author_email': 'glyph@twistedmatrix.com',
286 'bugtrack_url': '',
287 'cheesecake_code_kwalitee_id': None,
288 'cheesecake_documentation_id': None,
289 'cheesecake_installability_id': None,
290 'classifiers': [...],
291 'description': 'An extensible framework for Python programming, '
292 'with special focus\r\n'
293 'on event-based network programming and '
294 'multiprotocol integration.',
295 'docs_url': '',
296 'download_url': 'UNKNOWN',
297 'home_page': 'http://twistedmatrix.com/',
298 'keywords': '',
299 'license': 'MIT',
300 'maintainer': '',
301 'maintainer_email': '',
302 'name': 'Twisted',
303 'package_url': 'http://pypi.python.org/pypi/Twisted',
304 'platform': 'UNKNOWN',
305 'release_url': 'http://pypi.python.org/pypi/Twisted/12.3.0',
306 'requires_python': None,
307 'stable_version': None,
308 'summary': 'An asynchronous networking framework written in Python',
309 'version': '12.3.0'},
310 'urls': [{...}, {...}]}
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200311
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100312Additionally, maximum character *width* can be suggested. If a long object
313cannot be split, the specified width will be exceeded::
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200314
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100315 >>> pprint.pprint(project_info, depth=2, width=50)
316 {'info': {'_pypi_hidden': False,
317 '_pypi_ordering': 125,
318 'author': 'Glyph Lefkowitz',
319 'author_email': 'glyph@twistedmatrix.com',
320 'bugtrack_url': '',
321 'cheesecake_code_kwalitee_id': None,
322 'cheesecake_documentation_id': None,
323 'cheesecake_installability_id': None,
324 'classifiers': [...],
325 'description': 'An extensible '
326 'framework for '
327 'Python programming, '
328 'with special '
329 'focus\r\n'
330 'on event-based '
331 'network programming '
332 'and multiprotocol '
333 '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',
342 'package_url': 'http://pypi.python.org/pypi/Twisted',
343 'platform': 'UNKNOWN',
344 'release_url': 'http://pypi.python.org/pypi/Twisted/12.3.0',
345 'requires_python': None,
346 'stable_version': None,
347 'summary': 'An asynchronous '
348 'networking framework '
349 'written in Python',
350 'version': '12.3.0'},
351 'urls': [{...}, {...}]}