1 :mod:`pprint` --- Data pretty printer
2 =====================================
5 :synopsis: Data pretty printer.
6 .. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
7 .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
9 **Source code:** :source:`Lib/pprint.py`
13 The :mod:`pprint` module provides a capability to "pretty-print" arbitrary
14 Python data structures in a form which can be used as input to the interpreter.
15 If the formatted structures include objects which are not fundamental Python
16 types, the representation may not be loadable. This may be the case if objects
17 such as files, sockets, classes, or instances are included, as well as many
18 other built-in objects which are not representable as Python constants.
20 The formatted representation keeps objects on a single line if it can, and
21 breaks them onto multiple lines if they don't fit within the allowed width.
22 Construct :class:`PrettyPrinter` objects explicitly if you need to adjust the
25 .. versionchanged:: 2.5
26 Dictionaries are sorted by key before the display is computed; before 2.5, a
27 dictionary was sorted only if its display required more than one line, although
28 that wasn't documented.
30 .. versionchanged:: 2.6
31 Added support for :class:`set` and :class:`frozenset`.
34 The :mod:`pprint` module defines one class:
36 .. First the implementation class:
39 .. class:: PrettyPrinter(...)
41 Construct a :class:`PrettyPrinter` instance. This constructor understands
42 several keyword parameters. An output stream may be set using the *stream*
43 keyword; the only method used on the stream object is the file protocol's
44 :meth:`write` method. If not specified, the :class:`PrettyPrinter` adopts
45 ``sys.stdout``. Three additional parameters may be used to control the
46 formatted representation. The keywords are *indent*, *depth*, and *width*. The
47 amount of indentation added for each recursive level is specified by *indent*;
48 the default is one. Other values can cause output to look a little odd, but can
49 make nesting easier to spot. The number of levels which may be printed is
50 controlled by *depth*; if the data structure being printed is too deep, the next
51 contained level is replaced by ``...``. By default, there is no constraint on
52 the depth of the objects being formatted. The desired output width is
53 constrained using the *width* parameter; the default is 80 characters. If a
54 structure cannot be formatted within the constrained width, a best effort will
58 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
59 >>> stuff.insert(0, stuff[:])
60 >>> pp = pprint.PrettyPrinter(indent=4)
62 [ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
68 >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
69 ... ('parrot', ('fresh fruit',))))))))
70 >>> pp = pprint.PrettyPrinter(depth=6)
72 ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
74 The :class:`PrettyPrinter` class supports several derivative functions:
76 .. Now the derivative functions:
78 .. function:: pformat(object[, indent[, width[, depth]]])
80 Return the formatted representation of *object* as a string. *indent*, *width*
81 and *depth* will be passed to the :class:`PrettyPrinter` constructor as
82 formatting parameters.
84 .. versionchanged:: 2.4
85 The parameters *indent*, *width* and *depth* were added.
88 .. function:: pprint(object[, stream[, indent[, width[, depth]]]])
90 Prints the formatted representation of *object* on *stream*, followed by a
91 newline. If *stream* is omitted, ``sys.stdout`` is used. This may be used in
92 the interactive interpreter instead of a :keyword:`print` statement for
93 inspecting values. *indent*, *width* and *depth* will be passed to the
94 :class:`PrettyPrinter` constructor as formatting parameters.
97 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
98 >>> stuff.insert(0, stuff)
99 >>> pprint.pprint(stuff)
100 [<Recursion on list with id=...>,
107 .. versionchanged:: 2.4
108 The parameters *indent*, *width* and *depth* were added.
111 .. function:: isreadable(object)
113 .. index:: builtin: eval
115 Determine if the formatted representation of *object* is "readable," or can be
116 used to reconstruct the value using :func:`eval`. This always returns ``False``
117 for recursive objects.
119 >>> pprint.isreadable(stuff)
123 .. function:: isrecursive(object)
125 Determine if *object* requires a recursive representation.
128 One more support function is also defined:
130 .. function:: saferepr(object)
132 Return a string representation of *object*, protected against recursive data
133 structures. If the representation of *object* exposes a recursive entry, the
134 recursive reference will be represented as ``<Recursion on typename with
135 id=number>``. The representation is not otherwise formatted.
137 >>> pprint.saferepr(stuff)
138 "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
141 .. _prettyprinter-objects:
143 PrettyPrinter Objects
144 ---------------------
146 :class:`PrettyPrinter` instances have the following methods:
149 .. method:: PrettyPrinter.pformat(object)
151 Return the formatted representation of *object*. This takes into account the
152 options passed to the :class:`PrettyPrinter` constructor.
155 .. method:: PrettyPrinter.pprint(object)
157 Print the formatted representation of *object* on the configured stream,
158 followed by a newline.
160 The following methods provide the implementations for the corresponding
161 functions of the same names. Using these methods on an instance is slightly
162 more efficient since new :class:`PrettyPrinter` objects don't need to be
166 .. method:: PrettyPrinter.isreadable(object)
168 .. index:: builtin: eval
170 Determine if the formatted representation of the object is "readable," or can be
171 used to reconstruct the value using :func:`eval`. Note that this returns
172 ``False`` for recursive objects. If the *depth* parameter of the
173 :class:`PrettyPrinter` is set and the object is deeper than allowed, this
177 .. method:: PrettyPrinter.isrecursive(object)
179 Determine if the object requires a recursive representation.
181 This method is provided as a hook to allow subclasses to modify the way objects
182 are converted to strings. The default implementation uses the internals of the
183 :func:`saferepr` implementation.
186 .. method:: PrettyPrinter.format(object, context, maxlevels, level)
188 Returns three values: the formatted version of *object* as a string, a flag
189 indicating whether the result is readable, and a flag indicating whether
190 recursion was detected. The first argument is the object to be presented. The
191 second is a dictionary which contains the :func:`id` of objects that are part of
192 the current presentation context (direct and indirect containers for *object*
193 that are affecting the presentation) as the keys; if an object needs to be
194 presented which is already represented in *context*, the third return value
195 should be ``True``. Recursive calls to the :meth:`format` method should add
196 additional entries for containers to this dictionary. The third argument,
197 *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there
198 is no requested limit. This argument should be passed unmodified to recursive
199 calls. The fourth argument, *level*, gives the current level; recursive calls
200 should be passed a value less than that of the current call.
202 .. versionadded:: 2.3
209 This example demonstrates several uses of the :func:`pprint` function and its parameters.
212 >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
213 ... ('parrot', ('fresh fruit',))))))))
214 >>> stuff = ['a' * 10, tup, ['a' * 30, 'b' * 30], ['c' * 20, 'd' * 20]]
215 >>> pprint.pprint(stuff)
220 ('knights', ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
221 ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
222 ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
223 >>> pprint.pprint(stuff, depth=3)
225 ('spam', ('eggs', (...))),
226 ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
227 ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
228 >>> pprint.pprint(stuff, width=60)
234 ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
235 ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
236 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
237 ['cccccccccccccccccccc', 'dddddddddddddddddddd']]