blob: 8d57c5d4ed843773c16b5bcdd02577023bcea7e1 [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
Georg Brandl18244152009-09-02 20:34:52 +000032.. class:: PrettyPrinter(indent=1, width=80, depth=None, stream=None)
Georg Brandl116aa622007-08-15 14:28:22 +000033
34 Construct a :class:`PrettyPrinter` instance. This constructor understands
35 several keyword parameters. An output stream may be set using the *stream*
36 keyword; the only method used on the stream object is the file protocol's
37 :meth:`write` method. If not specified, the :class:`PrettyPrinter` adopts
38 ``sys.stdout``. Three additional parameters may be used to control the
39 formatted representation. The keywords are *indent*, *depth*, and *width*. The
40 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
Christian Heimesfe337bf2008-03-23 21:54:12 +000048 be made.
Georg Brandl116aa622007-08-15 14:28:22 +000049
Christian Heimesb9eccbf2007-12-05 20:18:38 +000050 >>> import pprint
51 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +000052 >>> stuff.insert(0, stuff[:])
53 >>> pp = pprint.PrettyPrinter(indent=4)
54 >>> pp.pprint(stuff)
Georg Brandl3ccb7872008-07-16 03:00:45 +000055 [ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
Christian Heimesb9eccbf2007-12-05 20:18:38 +000056 'spam',
57 'eggs',
58 'lumberjack',
59 'knights',
60 'ni']
61 >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
62 ... ('parrot', ('fresh fruit',))))))))
Georg Brandl116aa622007-08-15 14:28:22 +000063 >>> pp = pprint.PrettyPrinter(depth=6)
64 >>> pp.pprint(tup)
Alexandre Vassalottieca20b62008-05-16 02:54:33 +000065 ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
Georg Brandl116aa622007-08-15 14:28:22 +000066
Georg Brandl18244152009-09-02 20:34:52 +000067
Antoine Pitrou64c16c32013-03-23 20:30:39 +010068The :mod:`pprint` module also provides several shortcut functions:
Georg Brandl116aa622007-08-15 14:28:22 +000069
Georg Brandl18244152009-09-02 20:34:52 +000070.. function:: pformat(object, indent=1, width=80, depth=None)
Georg Brandl116aa622007-08-15 14:28:22 +000071
72 Return the formatted representation of *object* as a string. *indent*, *width*
73 and *depth* will be passed to the :class:`PrettyPrinter` constructor as
74 formatting parameters.
75
Georg Brandl116aa622007-08-15 14:28:22 +000076
Georg Brandl18244152009-09-02 20:34:52 +000077.. function:: pprint(object, stream=None, indent=1, width=80, depth=None)
Georg Brandl116aa622007-08-15 14:28:22 +000078
79 Prints the formatted representation of *object* on *stream*, followed by a
Georg Brandl18244152009-09-02 20:34:52 +000080 newline. If *stream* is ``None``, ``sys.stdout`` is used. This may be used
Georg Brandl6911e3c2007-09-04 07:15:32 +000081 in the interactive interpreter instead of the :func:`print` function for
82 inspecting values (you can even reassign ``print = pprint.pprint`` for use
83 within a scope). *indent*, *width* and *depth* will be passed to the
Christian Heimesfe337bf2008-03-23 21:54:12 +000084 :class:`PrettyPrinter` constructor as formatting parameters.
Georg Brandl116aa622007-08-15 14:28:22 +000085
Christian Heimesb9eccbf2007-12-05 20:18:38 +000086 >>> import pprint
87 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +000088 >>> stuff.insert(0, stuff)
89 >>> pprint.pprint(stuff)
Christian Heimesfe337bf2008-03-23 21:54:12 +000090 [<Recursion on list with id=...>,
91 'spam',
92 'eggs',
93 'lumberjack',
94 'knights',
95 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +000096
Georg Brandl116aa622007-08-15 14:28:22 +000097
98.. function:: isreadable(object)
99
100 .. index:: builtin: eval
101
102 Determine if the formatted representation of *object* is "readable," or can be
103 used to reconstruct the value using :func:`eval`. This always returns ``False``
Christian Heimesfe337bf2008-03-23 21:54:12 +0000104 for recursive objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000105
106 >>> pprint.isreadable(stuff)
107 False
108
109
110.. function:: isrecursive(object)
111
112 Determine if *object* requires a recursive representation.
113
Georg Brandl116aa622007-08-15 14:28:22 +0000114
Christian Heimesfe337bf2008-03-23 21:54:12 +0000115One more support function is also defined:
Georg Brandl116aa622007-08-15 14:28:22 +0000116
117.. function:: saferepr(object)
118
119 Return a string representation of *object*, protected against recursive data
120 structures. If the representation of *object* exposes a recursive entry, the
121 recursive reference will be represented as ``<Recursion on typename with
122 id=number>``. The representation is not otherwise formatted.
123
Georg Brandl116aa622007-08-15 14:28:22 +0000124 >>> pprint.saferepr(stuff)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000125 "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
Georg Brandl116aa622007-08-15 14:28:22 +0000126
127
128.. _prettyprinter-objects:
129
130PrettyPrinter Objects
131---------------------
132
133:class:`PrettyPrinter` instances have the following methods:
134
135
136.. method:: PrettyPrinter.pformat(object)
137
138 Return the formatted representation of *object*. This takes into account the
139 options passed to the :class:`PrettyPrinter` constructor.
140
141
142.. method:: PrettyPrinter.pprint(object)
143
144 Print the formatted representation of *object* on the configured stream,
145 followed by a newline.
146
147The following methods provide the implementations for the corresponding
148functions of the same names. Using these methods on an instance is slightly
149more efficient since new :class:`PrettyPrinter` objects don't need to be
150created.
151
152
153.. method:: PrettyPrinter.isreadable(object)
154
155 .. index:: builtin: eval
156
157 Determine if the formatted representation of the object is "readable," or can be
158 used to reconstruct the value using :func:`eval`. Note that this returns
159 ``False`` for recursive objects. If the *depth* parameter of the
160 :class:`PrettyPrinter` is set and the object is deeper than allowed, this
161 returns ``False``.
162
163
164.. method:: PrettyPrinter.isrecursive(object)
165
166 Determine if the object requires a recursive representation.
167
168This method is provided as a hook to allow subclasses to modify the way objects
169are converted to strings. The default implementation uses the internals of the
170:func:`saferepr` implementation.
171
172
173.. method:: PrettyPrinter.format(object, context, maxlevels, level)
174
175 Returns three values: the formatted version of *object* as a string, a flag
176 indicating whether the result is readable, and a flag indicating whether
177 recursion was detected. The first argument is the object to be presented. The
178 second is a dictionary which contains the :func:`id` of objects that are part of
179 the current presentation context (direct and indirect containers for *object*
180 that are affecting the presentation) as the keys; if an object needs to be
181 presented which is already represented in *context*, the third return value
182 should be ``True``. Recursive calls to the :meth:`format` method should add
183 additional entries for containers to this dictionary. The third argument,
184 *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there
185 is no requested limit. This argument should be passed unmodified to recursive
186 calls. The fourth argument, *level*, gives the current level; recursive calls
187 should be passed a value less than that of the current call.
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000188
189
190.. _pprint-example:
191
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200192Example
193-------
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000194
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200195To demonstrate several uses of the :func:`pprint` function and its parameters,
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100196let's fetch information about a project from `PyPI <https://pypi.python.org>`_::
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000197
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200198 >>> import json
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000199 >>> import pprint
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200200 >>> from urllib.request import urlopen
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100201 >>> with urlopen('http://pypi.python.org/pypi/Twisted/json') as url:
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200202 ... http_info = url.info()
203 ... raw_data = url.read().decode(http_info.get_content_charset())
Éric Araujo6a21f552011-05-29 03:46:31 +0200204 >>> project_info = json.loads(raw_data)
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000205
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200206In its basic form, :func:`pprint` shows the whole object::
207
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100208 >>> pprint.pprint(project_info)
209 {'info': {'_pypi_hidden': False,
210 '_pypi_ordering': 125,
211 'author': 'Glyph Lefkowitz',
212 'author_email': 'glyph@twistedmatrix.com',
213 'bugtrack_url': '',
214 'cheesecake_code_kwalitee_id': None,
215 'cheesecake_documentation_id': None,
216 'cheesecake_installability_id': None,
217 'classifiers': ['Programming Language :: Python :: 2.6',
218 'Programming Language :: Python :: 2.7',
219 'Programming Language :: Python :: 2 :: Only'],
220 'description': 'An extensible framework for Python programming, '
221 'with special focus\r\n'
222 'on event-based network programming and '
223 'multiprotocol integration.',
224 'docs_url': '',
225 'download_url': 'UNKNOWN',
226 'home_page': 'http://twistedmatrix.com/',
227 'keywords': '',
228 'license': 'MIT',
229 'maintainer': '',
230 'maintainer_email': '',
231 'name': 'Twisted',
232 'package_url': 'http://pypi.python.org/pypi/Twisted',
233 'platform': 'UNKNOWN',
234 'release_url': 'http://pypi.python.org/pypi/Twisted/12.3.0',
235 'requires_python': None,
236 'stable_version': None,
237 'summary': 'An asynchronous networking framework written in Python',
238 'version': '12.3.0'},
239 'urls': [{'comment_text': '',
240 'downloads': 71844,
241 'filename': 'Twisted-12.3.0.tar.bz2',
242 'has_sig': False,
243 'md5_digest': '6e289825f3bf5591cfd670874cc0862d',
244 'packagetype': 'sdist',
245 'python_version': 'source',
246 'size': 2615733,
247 'upload_time': '2012-12-26T12:47:03',
248 'url': 'https://pypi.python.org/packages/source/T/Twisted/Twisted-12.3.0.tar.bz2'},
249 {'comment_text': '',
250 'downloads': 5224,
251 'filename': 'Twisted-12.3.0.win32-py2.7.msi',
252 'has_sig': False,
253 'md5_digest': '6b778f5201b622a5519a2aca1a2fe512',
254 'packagetype': 'bdist_msi',
255 'python_version': '2.7',
256 'size': 2916352,
257 'upload_time': '2012-12-26T12:48:15',
258 '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 +0200259
260The result can be limited to a certain *depth* (ellipsis is used for deeper
261contents)::
262
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100263 >>> pprint.pprint(project_info, depth=2)
264 {'info': {'_pypi_hidden': False,
265 '_pypi_ordering': 125,
266 'author': 'Glyph Lefkowitz',
267 'author_email': 'glyph@twistedmatrix.com',
268 'bugtrack_url': '',
269 'cheesecake_code_kwalitee_id': None,
270 'cheesecake_documentation_id': None,
271 'cheesecake_installability_id': None,
272 'classifiers': [...],
273 'description': 'An extensible framework for Python programming, '
274 'with special focus\r\n'
275 'on event-based network programming and '
276 'multiprotocol integration.',
277 'docs_url': '',
278 'download_url': 'UNKNOWN',
279 'home_page': 'http://twistedmatrix.com/',
280 'keywords': '',
281 'license': 'MIT',
282 'maintainer': '',
283 'maintainer_email': '',
284 'name': 'Twisted',
285 'package_url': 'http://pypi.python.org/pypi/Twisted',
286 'platform': 'UNKNOWN',
287 'release_url': 'http://pypi.python.org/pypi/Twisted/12.3.0',
288 'requires_python': None,
289 'stable_version': None,
290 'summary': 'An asynchronous networking framework written in Python',
291 'version': '12.3.0'},
292 'urls': [{...}, {...}]}
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200293
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100294Additionally, maximum character *width* can be suggested. If a long object
295cannot be split, the specified width will be exceeded::
Łukasz Langa4ad78ab2011-05-14 22:43:44 +0200296
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100297 >>> pprint.pprint(project_info, depth=2, width=50)
298 {'info': {'_pypi_hidden': False,
299 '_pypi_ordering': 125,
300 'author': 'Glyph Lefkowitz',
301 'author_email': 'glyph@twistedmatrix.com',
302 'bugtrack_url': '',
303 'cheesecake_code_kwalitee_id': None,
304 'cheesecake_documentation_id': None,
305 'cheesecake_installability_id': None,
306 'classifiers': [...],
307 'description': 'An extensible '
308 'framework for '
309 'Python programming, '
310 'with special '
311 'focus\r\n'
312 'on event-based '
313 'network programming '
314 'and multiprotocol '
315 'integration.',
316 'docs_url': '',
317 'download_url': 'UNKNOWN',
318 'home_page': 'http://twistedmatrix.com/',
319 'keywords': '',
320 'license': 'MIT',
321 'maintainer': '',
322 'maintainer_email': '',
323 'name': 'Twisted',
324 'package_url': 'http://pypi.python.org/pypi/Twisted',
325 'platform': 'UNKNOWN',
326 'release_url': 'http://pypi.python.org/pypi/Twisted/12.3.0',
327 'requires_python': None,
328 'stable_version': None,
329 'summary': 'An asynchronous '
330 'networking framework '
331 'written in Python',
332 'version': '12.3.0'},
333 'urls': [{...}, {...}]}