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