• 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
28.. versionchanged:: 3.9
29   Added support for pretty-printing :class:`types.SimpleNamespace`.
30
31.. versionchanged:: 3.10
32   Added support for pretty-printing :class:`dataclasses.dataclass`.
33
34The :mod:`pprint` module defines one class:
35
36.. First the implementation class:
37
38
39.. index:: single: ...; placeholder
40
41.. class:: PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, \
42                         compact=False, sort_dicts=True, underscore_numbers=False)
43
44   Construct a :class:`PrettyPrinter` instance.  This constructor understands
45   several keyword parameters.
46
47   *stream* (default ``sys.stdout``) is a :term:`file-like object` to
48   which the output will be written by calling its :meth:`write` method.
49
50   Other values configure the manner in which nesting of complex data
51   structures is displayed.
52
53   *indent* (default 1) specifies the amount of indentation added for
54   each nesting level.
55
56   *depth* controls the number of nesting levels which may be printed; if
57   the data structure being printed is too deep, the next contained level
58   is replaced by ``...``.  By default, there is no constraint on the
59   depth of the objects being formatted.
60
61   *width* (default 80) specifies the desired maximum number of characters per
62   line in the output. If a structure cannot be formatted within the width
63   constraint, a best effort will be made.
64
65   *compact* impacts the way that long sequences (lists, tuples, sets, etc)
66   are formatted. If *compact* is false (the default) then each item of a
67   sequence will be formatted on a separate line.  If *compact* is true, as
68   many items as will fit within the *width* will be formatted on each output
69   line.
70
71   If *sort_dicts* is true (the default), dictionaries will be formatted with
72   their keys sorted, otherwise they will display in insertion order.
73
74   If *underscore_numbers* is true, integers will be formatted with the
75   ``_`` character for a thousands separator, otherwise underscores are not
76   displayed (the default).
77
78   .. versionchanged:: 3.4
79      Added the *compact* parameter.
80
81   .. versionchanged:: 3.8
82      Added the *sort_dicts* parameter.
83
84   .. versionchanged:: 3.10
85      Added the *underscore_numbers* parameter.
86
87      >>> import pprint
88      >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
89      >>> stuff.insert(0, stuff[:])
90      >>> pp = pprint.PrettyPrinter(indent=4)
91      >>> pp.pprint(stuff)
92      [   ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
93          'spam',
94          'eggs',
95          'lumberjack',
96          'knights',
97          'ni']
98      >>> pp = pprint.PrettyPrinter(width=41, compact=True)
99      >>> pp.pprint(stuff)
100      [['spam', 'eggs', 'lumberjack',
101        'knights', 'ni'],
102       'spam', 'eggs', 'lumberjack', 'knights',
103       'ni']
104      >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
105      ... ('parrot', ('fresh fruit',))))))))
106      >>> pp = pprint.PrettyPrinter(depth=6)
107      >>> pp.pprint(tup)
108      ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
109
110
111The :mod:`pprint` module also provides several shortcut functions:
112
113.. function:: pformat(object, indent=1, width=80, depth=None, *, \
114                      compact=False, sort_dicts=True, underscore_numbers=False)
115
116   Return the formatted representation of *object* as a string.  *indent*,
117   *width*, *depth*, *compact*, *sort_dicts* and *underscore_numbers* will be passed to the
118   :class:`PrettyPrinter` constructor as formatting parameters.
119
120   .. versionchanged:: 3.4
121      Added the *compact* parameter.
122
123   .. versionchanged:: 3.8
124      Added the *sort_dicts* parameter.
125
126   .. versionchanged:: 3.10
127      Added the *underscore_numbers* parameter.
128
129
130.. function:: pp(object, *args, sort_dicts=False, **kwargs)
131
132   Prints the formatted representation of *object* followed by a newline.
133   If *sort_dicts* is false (the default), dictionaries will be displayed with
134   their keys in insertion order, otherwise the dict keys will be sorted.
135   *args* and *kwargs* will be passed to :func:`pprint` as formatting
136   parameters.
137
138   .. versionadded:: 3.8
139
140
141.. function:: pprint(object, stream=None, indent=1, width=80, depth=None, *, \
142                     compact=False, sort_dicts=True, underscore_numbers=False)
143
144   Prints the formatted representation of *object* on *stream*, followed by a
145   newline.  If *stream* is ``None``, ``sys.stdout`` is used.  This may be used
146   in the interactive interpreter instead of the :func:`print` function for
147   inspecting values (you can even reassign ``print = pprint.pprint`` for use
148   within a scope).  *indent*, *width*, *depth*, *compact*, *sort_dicts* and *underscore_numbers* will
149   be passed to the :class:`PrettyPrinter` constructor as formatting parameters.
150
151   .. versionchanged:: 3.4
152      Added the *compact* parameter.
153
154   .. versionchanged:: 3.8
155      Added the *sort_dicts* parameter.
156
157   .. versionchanged:: 3.10
158      Added the *underscore_numbers* parameter.
159
160      >>> import pprint
161      >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
162      >>> stuff.insert(0, stuff)
163      >>> pprint.pprint(stuff)
164      [<Recursion on list with id=...>,
165       'spam',
166       'eggs',
167       'lumberjack',
168       'knights',
169       'ni']
170
171
172.. function:: isreadable(object)
173
174   .. index:: builtin: eval
175
176   Determine if the formatted representation of *object* is "readable", or can be
177   used to reconstruct the value using :func:`eval`.  This always returns ``False``
178   for recursive objects.
179
180      >>> pprint.isreadable(stuff)
181      False
182
183
184.. function:: isrecursive(object)
185
186   Determine if *object* requires a recursive representation.
187
188
189One more support function is also defined:
190
191.. function:: saferepr(object)
192
193   Return a string representation of *object*, protected against recursive data
194   structures.  If the representation of *object* exposes a recursive entry, the
195   recursive reference will be represented as ``<Recursion on typename with
196   id=number>``.  The representation is not otherwise formatted.
197
198   >>> pprint.saferepr(stuff)
199   "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
200
201
202.. _prettyprinter-objects:
203
204PrettyPrinter Objects
205---------------------
206
207:class:`PrettyPrinter` instances have the following methods:
208
209
210.. method:: PrettyPrinter.pformat(object)
211
212   Return the formatted representation of *object*.  This takes into account the
213   options passed to the :class:`PrettyPrinter` constructor.
214
215
216.. method:: PrettyPrinter.pprint(object)
217
218   Print the formatted representation of *object* on the configured stream,
219   followed by a newline.
220
221The following methods provide the implementations for the corresponding
222functions of the same names.  Using these methods on an instance is slightly
223more efficient since new :class:`PrettyPrinter` objects don't need to be
224created.
225
226
227.. method:: PrettyPrinter.isreadable(object)
228
229   .. index:: builtin: eval
230
231   Determine if the formatted representation of the object is "readable," or can be
232   used to reconstruct the value using :func:`eval`.  Note that this returns
233   ``False`` for recursive objects.  If the *depth* parameter of the
234   :class:`PrettyPrinter` is set and the object is deeper than allowed, this
235   returns ``False``.
236
237
238.. method:: PrettyPrinter.isrecursive(object)
239
240   Determine if the object requires a recursive representation.
241
242This method is provided as a hook to allow subclasses to modify the way objects
243are converted to strings.  The default implementation uses the internals of the
244:func:`saferepr` implementation.
245
246
247.. method:: PrettyPrinter.format(object, context, maxlevels, level)
248
249   Returns three values: the formatted version of *object* as a string, a flag
250   indicating whether the result is readable, and a flag indicating whether
251   recursion was detected.  The first argument is the object to be presented.  The
252   second is a dictionary which contains the :func:`id` of objects that are part of
253   the current presentation context (direct and indirect containers for *object*
254   that are affecting the presentation) as the keys; if an object needs to be
255   presented which is already represented in *context*, the third return value
256   should be ``True``.  Recursive calls to the :meth:`.format` method should add
257   additional entries for containers to this dictionary.  The third argument,
258   *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there
259   is no requested limit.  This argument should be passed unmodified to recursive
260   calls. The fourth argument, *level*, gives the current level; recursive calls
261   should be passed a value less than that of the current call.
262
263
264.. _pprint-example:
265
266Example
267-------
268
269To demonstrate several uses of the :func:`pprint` function and its parameters,
270let's fetch information about a project from `PyPI <https://pypi.org>`_::
271
272   >>> import json
273   >>> import pprint
274   >>> from urllib.request import urlopen
275   >>> with urlopen('https://pypi.org/pypi/sampleproject/json') as resp:
276   ...     project_info = json.load(resp)['info']
277
278In its basic form, :func:`pprint` shows the whole object::
279
280   >>> pprint.pprint(project_info)
281   {'author': 'The Python Packaging Authority',
282    'author_email': 'pypa-dev@googlegroups.com',
283    'bugtrack_url': None,
284    'classifiers': ['Development Status :: 3 - Alpha',
285                    'Intended Audience :: Developers',
286                    'License :: OSI Approved :: MIT License',
287                    'Programming Language :: Python :: 2',
288                    'Programming Language :: Python :: 2.6',
289                    'Programming Language :: Python :: 2.7',
290                    'Programming Language :: Python :: 3',
291                    'Programming Language :: Python :: 3.2',
292                    'Programming Language :: Python :: 3.3',
293                    'Programming Language :: Python :: 3.4',
294                    'Topic :: Software Development :: Build Tools'],
295    'description': 'A sample Python project\n'
296                   '=======================\n'
297                   '\n'
298                   'This is the description file for the project.\n'
299                   '\n'
300                   'The file should use UTF-8 encoding and be written using '
301                   'ReStructured Text. It\n'
302                   'will be used to generate the project webpage on PyPI, and '
303                   'should be written for\n'
304                   'that purpose.\n'
305                   '\n'
306                   'Typical contents for this file would include an overview of '
307                   'the project, basic\n'
308                   'usage examples, etc. Generally, including the project '
309                   'changelog in here is not\n'
310                   'a good idea, although a simple "What\'s New" section for the '
311                   'most recent version\n'
312                   'may be appropriate.',
313    'description_content_type': None,
314    'docs_url': None,
315    'download_url': 'UNKNOWN',
316    'downloads': {'last_day': -1, 'last_month': -1, 'last_week': -1},
317    'home_page': 'https://github.com/pypa/sampleproject',
318    'keywords': 'sample setuptools development',
319    'license': 'MIT',
320    'maintainer': None,
321    'maintainer_email': None,
322    'name': 'sampleproject',
323    'package_url': 'https://pypi.org/project/sampleproject/',
324    'platform': 'UNKNOWN',
325    'project_url': 'https://pypi.org/project/sampleproject/',
326    'project_urls': {'Download': 'UNKNOWN',
327                     'Homepage': 'https://github.com/pypa/sampleproject'},
328    'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
329    'requires_dist': None,
330    'requires_python': None,
331    'summary': 'A sample Python project',
332    'version': '1.2.0'}
333
334The result can be limited to a certain *depth* (ellipsis is used for deeper
335contents)::
336
337   >>> pprint.pprint(project_info, depth=1)
338   {'author': 'The Python Packaging Authority',
339    'author_email': 'pypa-dev@googlegroups.com',
340    'bugtrack_url': None,
341    'classifiers': [...],
342    'description': 'A sample Python project\n'
343                   '=======================\n'
344                   '\n'
345                   'This is the description file for the project.\n'
346                   '\n'
347                   'The file should use UTF-8 encoding and be written using '
348                   'ReStructured Text. It\n'
349                   'will be used to generate the project webpage on PyPI, and '
350                   'should be written for\n'
351                   'that purpose.\n'
352                   '\n'
353                   'Typical contents for this file would include an overview of '
354                   'the project, basic\n'
355                   'usage examples, etc. Generally, including the project '
356                   'changelog in here is not\n'
357                   'a good idea, although a simple "What\'s New" section for the '
358                   'most recent version\n'
359                   'may be appropriate.',
360    'description_content_type': None,
361    'docs_url': None,
362    'download_url': 'UNKNOWN',
363    'downloads': {...},
364    'home_page': 'https://github.com/pypa/sampleproject',
365    'keywords': 'sample setuptools development',
366    'license': 'MIT',
367    'maintainer': None,
368    'maintainer_email': None,
369    'name': 'sampleproject',
370    'package_url': 'https://pypi.org/project/sampleproject/',
371    'platform': 'UNKNOWN',
372    'project_url': 'https://pypi.org/project/sampleproject/',
373    'project_urls': {...},
374    'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
375    'requires_dist': None,
376    'requires_python': None,
377    'summary': 'A sample Python project',
378    'version': '1.2.0'}
379
380Additionally, maximum character *width* can be suggested. If a long object
381cannot be split, the specified width will be exceeded::
382
383   >>> pprint.pprint(project_info, depth=1, width=60)
384   {'author': 'The Python Packaging Authority',
385    'author_email': 'pypa-dev@googlegroups.com',
386    'bugtrack_url': None,
387    'classifiers': [...],
388    'description': 'A sample Python project\n'
389                   '=======================\n'
390                   '\n'
391                   'This is the description file for the '
392                   'project.\n'
393                   '\n'
394                   'The file should use UTF-8 encoding and be '
395                   'written using ReStructured Text. It\n'
396                   'will be used to generate the project '
397                   'webpage on PyPI, and should be written '
398                   'for\n'
399                   'that purpose.\n'
400                   '\n'
401                   'Typical contents for this file would '
402                   'include an overview of the project, '
403                   'basic\n'
404                   'usage examples, etc. Generally, including '
405                   'the project changelog in here is not\n'
406                   'a good idea, although a simple "What\'s '
407                   'New" section for the most recent version\n'
408                   'may be appropriate.',
409    'description_content_type': None,
410    'docs_url': None,
411    'download_url': 'UNKNOWN',
412    'downloads': {...},
413    'home_page': 'https://github.com/pypa/sampleproject',
414    'keywords': 'sample setuptools development',
415    'license': 'MIT',
416    'maintainer': None,
417    'maintainer_email': None,
418    'name': 'sampleproject',
419    'package_url': 'https://pypi.org/project/sampleproject/',
420    'platform': 'UNKNOWN',
421    'project_url': 'https://pypi.org/project/sampleproject/',
422    'project_urls': {...},
423    'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
424    'requires_dist': None,
425    'requires_python': None,
426    'summary': 'A sample Python project',
427    'version': '1.2.0'}
428