• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`pprint` --- Data pretty printer
2=====================================
3
4.. module:: pprint
5   :synopsis: Data pretty printer.
6
7.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
8.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
9
10**Source code:** :source:`Lib/pprint.py`
11
12--------------
13
14The :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
18such as files, sockets or classes are included, as well as many other
19objects which are not representable as Python literals.
20
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
26Dictionaries are sorted by key before the display is computed.
27
28The :mod:`pprint` module defines one class:
29
30.. First the implementation class:
31
32
33.. class:: PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, \
34                         compact=False)
35
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
40   ``sys.stdout``.  The
41   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
49   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.
52
53   .. versionchanged:: 3.4
54      Added the *compact* parameter.
55
56      >>> import pprint
57      >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
58      >>> stuff.insert(0, stuff[:])
59      >>> pp = pprint.PrettyPrinter(indent=4)
60      >>> pp.pprint(stuff)
61      [   ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
62          'spam',
63          'eggs',
64          'lumberjack',
65          'knights',
66          'ni']
67      >>> 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']
73      >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
74      ... ('parrot', ('fresh fruit',))))))))
75      >>> pp = pprint.PrettyPrinter(depth=6)
76      >>> pp.pprint(tup)
77      ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
78
79
80The :mod:`pprint` module also provides several shortcut functions:
81
82.. function:: pformat(object, indent=1, width=80, depth=None, *, compact=False)
83
84   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.
87
88   .. versionchanged:: 3.4
89      Added the *compact* parameter.
90
91
92.. function:: pprint(object, stream=None, indent=1, width=80, depth=None, *, \
93                     compact=False)
94
95   Prints the formatted representation of *object* on *stream*, followed by a
96   newline.  If *stream* is ``None``, ``sys.stdout`` is used.  This may be used
97   in the interactive interpreter instead of the :func:`print` function for
98   inspecting values (you can even reassign ``print = pprint.pprint`` for use
99   within a scope).  *indent*, *width*, *depth* and *compact* will be passed
100   to the :class:`PrettyPrinter` constructor as formatting parameters.
101
102   .. versionchanged:: 3.4
103      Added the *compact* parameter.
104
105      >>> import pprint
106      >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
107      >>> stuff.insert(0, stuff)
108      >>> pprint.pprint(stuff)
109      [<Recursion on list with id=...>,
110       'spam',
111       'eggs',
112       'lumberjack',
113       'knights',
114       'ni']
115
116
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``
123   for recursive objects.
124
125      >>> pprint.isreadable(stuff)
126      False
127
128
129.. function:: isrecursive(object)
130
131   Determine if *object* requires a recursive representation.
132
133
134One more support function is also defined:
135
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
143   >>> pprint.saferepr(stuff)
144   "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
145
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
201   should be ``True``.  Recursive calls to the :meth:`.format` method should add
202   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.
207
208
209.. _pprint-example:
210
211Example
212-------
213
214To demonstrate several uses of the :func:`pprint` function and its parameters,
215let's fetch information about a project from `PyPI <https://pypi.python.org/pypi>`_::
216
217   >>> import json
218   >>> import pprint
219   >>> from urllib.request import urlopen
220   >>> with urlopen('http://pypi.python.org/pypi/Twisted/json') as url:
221   ...     http_info = url.info()
222   ...     raw_data = url.read().decode(http_info.get_content_charset())
223   >>> project_info = json.loads(raw_data)
224
225In its basic form, :func:`pprint` shows the whole object::
226
227   >>> 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'],
239             'description': 'An extensible framework for Python programming, with '
240                            'special focus\r\n'
241                            'on event-based network programming and multiprotocol '
242                            'integration.',
243             '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',
251             'package_url': 'http://pypi.python.org/pypi/Twisted',
252             'platform': 'UNKNOWN',
253             'release_url': 'http://pypi.python.org/pypi/Twisted/12.3.0',
254             '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',
267              'url': 'https://pypi.python.org/packages/source/T/Twisted/Twisted-12.3.0.tar.bz2'},
268             {'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',
277              'url': 'https://pypi.python.org/packages/2.7/T/Twisted/Twisted-12.3.0.win32-py2.7.msi'}]}
278
279The result can be limited to a certain *depth* (ellipsis is used for deeper
280contents)::
281
282   >>> 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': [...],
292             'description': 'An extensible framework for Python programming, with '
293                            'special focus\r\n'
294                            'on event-based network programming and multiprotocol '
295                            'integration.',
296             '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',
304             'package_url': 'http://pypi.python.org/pypi/Twisted',
305             'platform': 'UNKNOWN',
306             'release_url': 'http://pypi.python.org/pypi/Twisted/12.3.0',
307             'requires_python': None,
308             'stable_version': None,
309             'summary': 'An asynchronous networking framework written in Python',
310             'version': '12.3.0'},
311    'urls': [{...}, {...}]}
312
313Additionally, maximum character *width* can be suggested. If a long object
314cannot be split, the specified width will be exceeded::
315
316   >>> 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 '
327                            'framework for Python '
328                            'programming, with '
329                            'special focus\r\n'
330                            'on event-based network '
331                            'programming and '
332                            '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 networking '
348                        'framework written in '
349                        'Python',
350             'version': '12.3.0'},
351    'urls': [{...}, {...}]}
352