blob: d07371462f87e3a60ef8dc91db7f3690eb3056a9 [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
Georg Brandlb19be572007-12-29 10:57:00 +000030.. First the implementation class:
Georg Brandl8ec7f652007-08-15 14:28:01 +000031
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
Georg Brandlb19be572007-12-29 10:57:00 +000071.. Now the derivative functions:
Georg Brandl8ec7f652007-08-15 14:28:01 +000072
73.. function:: pformat(object[, indent[, width[, depth]]])
74
75 Return the formatted representation of *object* as a string. *indent*, *width*
76 and *depth* will be passed to the :class:`PrettyPrinter` constructor as
77 formatting parameters.
78
79 .. versionchanged:: 2.4
80 The parameters *indent*, *width* and *depth* were added.
81
82
83.. function:: pprint(object[, stream[, indent[, width[, depth]]]])
84
85 Prints the formatted representation of *object* on *stream*, followed by a
86 newline. If *stream* is omitted, ``sys.stdout`` is used. This may be used in
87 the interactive interpreter instead of a :keyword:`print` statement for
88 inspecting values. *indent*, *width* and *depth* will be passed to the
89 :class:`PrettyPrinter` constructor as formatting parameters. ::
90
Georg Brandl722e1012007-12-05 17:56:50 +000091 >>> import pprint
92 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl8ec7f652007-08-15 14:28:01 +000093 >>> stuff.insert(0, stuff)
94 >>> pprint.pprint(stuff)
95 [<Recursion on list with id=869440>,
96 '',
97 '/usr/local/lib/python1.5',
98 '/usr/local/lib/python1.5/test',
99 '/usr/local/lib/python1.5/sunos5',
100 '/usr/local/lib/python1.5/sharedmodules',
101 '/usr/local/lib/python1.5/tkinter']
102
103 .. versionchanged:: 2.4
104 The parameters *indent*, *width* and *depth* were added.
105
106
107.. function:: isreadable(object)
108
109 .. index:: builtin: eval
110
111 Determine if the formatted representation of *object* is "readable," or can be
112 used to reconstruct the value using :func:`eval`. This always returns ``False``
113 for recursive objects. ::
114
115 >>> pprint.isreadable(stuff)
116 False
117
118
119.. function:: isrecursive(object)
120
121 Determine if *object* requires a recursive representation.
122
123One more support function is also defined:
124
125
126.. function:: saferepr(object)
127
128 Return a string representation of *object*, protected against recursive data
129 structures. If the representation of *object* exposes a recursive entry, the
130 recursive reference will be represented as ``<Recursion on typename with
131 id=number>``. The representation is not otherwise formatted.
132
Georg Brandl8ec7f652007-08-15 14:28:01 +0000133::
134
135 >>> pprint.saferepr(stuff)
136 "[<Recursion on list with id=682968>, '', '/usr/local/lib/python1.5', '/usr/loca
137 l/lib/python1.5/test', '/usr/local/lib/python1.5/sunos5', '/usr/local/lib/python
138 1.5/sharedmodules', '/usr/local/lib/python1.5/tkinter']"
139
140
141.. _prettyprinter-objects:
142
143PrettyPrinter Objects
144---------------------
145
146:class:`PrettyPrinter` instances have the following methods:
147
148
149.. method:: PrettyPrinter.pformat(object)
150
151 Return the formatted representation of *object*. This takes into account the
152 options passed to the :class:`PrettyPrinter` constructor.
153
154
155.. method:: PrettyPrinter.pprint(object)
156
157 Print the formatted representation of *object* on the configured stream,
158 followed by a newline.
159
160The following methods provide the implementations for the corresponding
161functions of the same names. Using these methods on an instance is slightly
162more efficient since new :class:`PrettyPrinter` objects don't need to be
163created.
164
165
166.. method:: PrettyPrinter.isreadable(object)
167
168 .. index:: builtin: eval
169
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
174 returns ``False``.
175
176
177.. method:: PrettyPrinter.isrecursive(object)
178
179 Determine if the object requires a recursive representation.
180
181This method is provided as a hook to allow subclasses to modify the way objects
182are converted to strings. The default implementation uses the internals of the
183:func:`saferepr` implementation.
184
185
186.. method:: PrettyPrinter.format(object, context, maxlevels, level)
187
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.
201
202 .. versionadded:: 2.3
203
Georg Brandl722e1012007-12-05 17:56:50 +0000204.. _pprint-example:
205
206pprint Example
207--------------
208
209This example demonstrates several uses of the :func:`pprint` function and its parameters.
210
211 >>> import pprint
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)
216 ['aaaaaaaaaa',
217 ('spam',
218 ('eggs',
219 ('lumberjack',
220 ('knights', ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
221 ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
222 ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
223 >>> pprint.pprint(stuff, depth=3)
224 ['aaaaaaaaaa',
225 ('spam', ('eggs', ('lumberjack', (...)))),
226 ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
227 ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
228 >>> pprint.pprint(stuff, width=60)
229 ['aaaaaaaaaa',
230 ('spam',
231 ('eggs',
232 ('lumberjack',
233 ('knights',
234 ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
235 ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
236 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
237 ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
238