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