blob: e9cd1480927e10afc28c048c62b16b7127355545 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`pprint` --- Data pretty printer
3=====================================
4
5.. module:: pprint
6 :synopsis: Data pretty printer.
7.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
8.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
9
10
11The :mod:`pprint` module provides a capability to "pretty-print" arbitrary
12Python data structures in a form which can be used as input to the interpreter.
13If the formatted structures include objects which are not fundamental Python
14types, the representation may not be loadable. This may be the case if objects
15such as files, sockets, classes, or instances are included, as well as many
16other builtin objects which are not representable as Python constants.
17
18The formatted representation keeps objects on a single line if it can, and
19breaks them onto multiple lines if they don't fit within the allowed width.
20Construct :class:`PrettyPrinter` objects explicitly if you need to adjust the
21width constraint.
22
23.. versionchanged:: 2.5
24 Dictionaries are sorted by key before the display is computed; before 2.5, a
25 dictionary was sorted only if its display required more than one line, although
26 that wasn't documented.
27
28The :mod:`pprint` module defines one class:
29
30.. % First the implementation class:
31
32
33.. class:: PrettyPrinter(...)
34
35 Construct a :class:`PrettyPrinter` instance. This constructor understands
36 several keyword parameters. An output stream may be set using the *stream*
37 keyword; the only method used on the stream object is the file protocol's
38 :meth:`write` method. If not specified, the :class:`PrettyPrinter` adopts
39 ``sys.stdout``. Three additional parameters may be used to control the
40 formatted representation. The keywords are *indent*, *depth*, and *width*. 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. ::
50
Georg Brandl722e1012007-12-05 17:56:50 +000051 >>> import pprint
52 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl8ec7f652007-08-15 14:28:01 +000053 >>> stuff.insert(0, stuff[:])
54 >>> pp = pprint.PrettyPrinter(indent=4)
55 >>> pp.pprint(stuff)
Georg Brandl722e1012007-12-05 17:56:50 +000056 [ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
57 'spam',
58 'eggs',
59 'lumberjack',
60 'knights',
61 'ni']
62 >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
63 ... ('parrot', ('fresh fruit',))))))))
Georg Brandl8ec7f652007-08-15 14:28:01 +000064 >>> pp = pprint.PrettyPrinter(depth=6)
65 >>> pp.pprint(tup)
Georg Brandl722e1012007-12-05 17:56:50 +000066 ('spam',
67 ('eggs', ('lumberjack', ('knights', ('ni', ('dead', ('parrot', (...,))))))))
Georg Brandl8ec7f652007-08-15 14:28:01 +000068
69The :class:`PrettyPrinter` class supports several derivative functions:
70
71.. % Now the derivative functions:
72
73
74.. function:: pformat(object[, indent[, width[, depth]]])
75
76 Return the formatted representation of *object* as a string. *indent*, *width*
77 and *depth* will be passed to the :class:`PrettyPrinter` constructor as
78 formatting parameters.
79
80 .. versionchanged:: 2.4
81 The parameters *indent*, *width* and *depth* were added.
82
83
84.. function:: pprint(object[, stream[, indent[, width[, depth]]]])
85
86 Prints the formatted representation of *object* on *stream*, followed by a
87 newline. If *stream* is omitted, ``sys.stdout`` is used. This may be used in
88 the interactive interpreter instead of a :keyword:`print` statement for
89 inspecting values. *indent*, *width* and *depth* will be passed to the
90 :class:`PrettyPrinter` constructor as formatting parameters. ::
91
Georg Brandl722e1012007-12-05 17:56:50 +000092 >>> import pprint
93 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl8ec7f652007-08-15 14:28:01 +000094 >>> stuff.insert(0, stuff)
95 >>> pprint.pprint(stuff)
96 [<Recursion on list with id=869440>,
97 '',
98 '/usr/local/lib/python1.5',
99 '/usr/local/lib/python1.5/test',
100 '/usr/local/lib/python1.5/sunos5',
101 '/usr/local/lib/python1.5/sharedmodules',
102 '/usr/local/lib/python1.5/tkinter']
103
104 .. versionchanged:: 2.4
105 The parameters *indent*, *width* and *depth* were added.
106
107
108.. function:: isreadable(object)
109
110 .. index:: builtin: eval
111
112 Determine if the formatted representation of *object* is "readable," or can be
113 used to reconstruct the value using :func:`eval`. This always returns ``False``
114 for recursive objects. ::
115
116 >>> pprint.isreadable(stuff)
117 False
118
119
120.. function:: isrecursive(object)
121
122 Determine if *object* requires a recursive representation.
123
124One more support function is also defined:
125
126
127.. function:: saferepr(object)
128
129 Return a string representation of *object*, protected against recursive data
130 structures. If the representation of *object* exposes a recursive entry, the
131 recursive reference will be represented as ``<Recursion on typename with
132 id=number>``. The representation is not otherwise formatted.
133
134.. % This example is outside the {funcdesc} to keep it from running over
135.. % the right margin.
136
137::
138
139 >>> pprint.saferepr(stuff)
140 "[<Recursion on list with id=682968>, '', '/usr/local/lib/python1.5', '/usr/loca
141 l/lib/python1.5/test', '/usr/local/lib/python1.5/sunos5', '/usr/local/lib/python
142 1.5/sharedmodules', '/usr/local/lib/python1.5/tkinter']"
143
144
145.. _prettyprinter-objects:
146
147PrettyPrinter Objects
148---------------------
149
150:class:`PrettyPrinter` instances have the following methods:
151
152
153.. method:: PrettyPrinter.pformat(object)
154
155 Return the formatted representation of *object*. This takes into account the
156 options passed to the :class:`PrettyPrinter` constructor.
157
158
159.. method:: PrettyPrinter.pprint(object)
160
161 Print the formatted representation of *object* on the configured stream,
162 followed by a newline.
163
164The following methods provide the implementations for the corresponding
165functions of the same names. Using these methods on an instance is slightly
166more efficient since new :class:`PrettyPrinter` objects don't need to be
167created.
168
169
170.. method:: PrettyPrinter.isreadable(object)
171
172 .. index:: builtin: eval
173
174 Determine if the formatted representation of the object is "readable," or can be
175 used to reconstruct the value using :func:`eval`. Note that this returns
176 ``False`` for recursive objects. If the *depth* parameter of the
177 :class:`PrettyPrinter` is set and the object is deeper than allowed, this
178 returns ``False``.
179
180
181.. method:: PrettyPrinter.isrecursive(object)
182
183 Determine if the object requires a recursive representation.
184
185This method is provided as a hook to allow subclasses to modify the way objects
186are converted to strings. The default implementation uses the internals of the
187:func:`saferepr` implementation.
188
189
190.. method:: PrettyPrinter.format(object, context, maxlevels, level)
191
192 Returns three values: the formatted version of *object* as a string, a flag
193 indicating whether the result is readable, and a flag indicating whether
194 recursion was detected. The first argument is the object to be presented. The
195 second is a dictionary which contains the :func:`id` of objects that are part of
196 the current presentation context (direct and indirect containers for *object*
197 that are affecting the presentation) as the keys; if an object needs to be
198 presented which is already represented in *context*, the third return value
199 should be ``True``. Recursive calls to the :meth:`format` method should add
200 additional entries for containers to this dictionary. The third argument,
201 *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there
202 is no requested limit. This argument should be passed unmodified to recursive
203 calls. The fourth argument, *level*, gives the current level; recursive calls
204 should be passed a value less than that of the current call.
205
206 .. versionadded:: 2.3
207
Georg Brandl722e1012007-12-05 17:56:50 +0000208.. _pprint-example:
209
210pprint Example
211--------------
212
213This example demonstrates several uses of the :func:`pprint` function and its parameters.
214
215 >>> import pprint
216 >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
217 ... ('parrot', ('fresh fruit',))))))))
218 >>> stuff = ['a' * 10, tup, ['a' * 30, 'b' * 30], ['c' * 20, 'd' * 20]]
219 >>> pprint.pprint(stuff)
220 ['aaaaaaaaaa',
221 ('spam',
222 ('eggs',
223 ('lumberjack',
224 ('knights', ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
225 ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
226 ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
227 >>> pprint.pprint(stuff, depth=3)
228 ['aaaaaaaaaa',
229 ('spam', ('eggs', ('lumberjack', (...)))),
230 ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
231 ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
232 >>> pprint.pprint(stuff, width=60)
233 ['aaaaaaaaaa',
234 ('spam',
235 ('eggs',
236 ('lumberjack',
237 ('knights',
238 ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
239 ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
240 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
241 ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
242