blob: 6670cf8dc52680b2fab5b2ec804598ec15815f0d [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl55ac8f02007-09-01 13:51:09 +000023Dictionaries are sorted by key before the display is computed.
Georg Brandl116aa622007-08-15 14:28:22 +000024
Christian Heimes1af737c2008-01-23 08:24:23 +000025.. versionchanged:: 2.6
26 Added support for :class:`set` and :class:`frozenset`.
27
Georg Brandl116aa622007-08-15 14:28:22 +000028The :mod:`pprint` module defines one class:
29
Christian Heimes5b5e81c2007-12-31 16:14:33 +000030.. First the implementation class:
Georg Brandl116aa622007-08-15 14:28:22 +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
Christian Heimesb9eccbf2007-12-05 20:18:38 +000051 >>> import pprint
52 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +000053 >>> stuff.insert(0, stuff[:])
54 >>> pp = pprint.PrettyPrinter(indent=4)
55 >>> pp.pprint(stuff)
Christian Heimesb9eccbf2007-12-05 20:18:38 +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 Brandl116aa622007-08-15 14:28:22 +000064 >>> pp = pprint.PrettyPrinter(depth=6)
65 >>> pp.pprint(tup)
Christian Heimesb9eccbf2007-12-05 20:18:38 +000066 ('spam',
67 ('eggs', ('lumberjack', ('knights', ('ni', ('dead', ('parrot', (...,))))))))
Georg Brandl116aa622007-08-15 14:28:22 +000068
69The :class:`PrettyPrinter` class supports several derivative functions:
70
Christian Heimes5b5e81c2007-12-31 16:14:33 +000071.. Now the derivative functions:
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl116aa622007-08-15 14:28:22 +000079
80.. function:: pprint(object[, stream[, indent[, width[, depth]]]])
81
82 Prints the formatted representation of *object* on *stream*, followed by a
Georg Brandl6911e3c2007-09-04 07:15:32 +000083 newline. If *stream* is omitted, ``sys.stdout`` is used. This may be used
84 in the interactive interpreter instead of the :func:`print` function for
85 inspecting values (you can even reassign ``print = pprint.pprint`` for use
86 within a scope). *indent*, *width* and *depth* will be passed to the
Georg Brandl116aa622007-08-15 14:28:22 +000087 :class:`PrettyPrinter` constructor as formatting parameters. ::
88
Christian Heimesb9eccbf2007-12-05 20:18:38 +000089 >>> import pprint
90 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +000091 >>> stuff.insert(0, stuff)
92 >>> pprint.pprint(stuff)
93 [<Recursion on list with id=869440>,
94 '',
95 '/usr/local/lib/python1.5',
96 '/usr/local/lib/python1.5/test',
97 '/usr/local/lib/python1.5/sunos5',
98 '/usr/local/lib/python1.5/sharedmodules',
99 '/usr/local/lib/python1.5/tkinter']
100
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102.. function:: isreadable(object)
103
104 .. index:: builtin: eval
105
106 Determine if the formatted representation of *object* is "readable," or can be
107 used to reconstruct the value using :func:`eval`. This always returns ``False``
108 for recursive objects. ::
109
110 >>> pprint.isreadable(stuff)
111 False
112
113
114.. function:: isrecursive(object)
115
116 Determine if *object* requires a recursive representation.
117
118One more support function is also defined:
119
120
121.. function:: saferepr(object)
122
123 Return a string representation of *object*, protected against recursive data
124 structures. If the representation of *object* exposes a recursive entry, the
125 recursive reference will be represented as ``<Recursion on typename with
126 id=number>``. The representation is not otherwise formatted.
127
Georg Brandl116aa622007-08-15 14:28:22 +0000128::
129
130 >>> pprint.saferepr(stuff)
131 "[<Recursion on list with id=682968>, '', '/usr/local/lib/python1.5', '/usr/loca
132 l/lib/python1.5/test', '/usr/local/lib/python1.5/sunos5', '/usr/local/lib/python
133 1.5/sharedmodules', '/usr/local/lib/python1.5/tkinter']"
134
135
136.. _prettyprinter-objects:
137
138PrettyPrinter Objects
139---------------------
140
141:class:`PrettyPrinter` instances have the following methods:
142
143
144.. method:: PrettyPrinter.pformat(object)
145
146 Return the formatted representation of *object*. This takes into account the
147 options passed to the :class:`PrettyPrinter` constructor.
148
149
150.. method:: PrettyPrinter.pprint(object)
151
152 Print the formatted representation of *object* on the configured stream,
153 followed by a newline.
154
155The following methods provide the implementations for the corresponding
156functions of the same names. Using these methods on an instance is slightly
157more efficient since new :class:`PrettyPrinter` objects don't need to be
158created.
159
160
161.. method:: PrettyPrinter.isreadable(object)
162
163 .. index:: builtin: eval
164
165 Determine if the formatted representation of the object is "readable," or can be
166 used to reconstruct the value using :func:`eval`. Note that this returns
167 ``False`` for recursive objects. If the *depth* parameter of the
168 :class:`PrettyPrinter` is set and the object is deeper than allowed, this
169 returns ``False``.
170
171
172.. method:: PrettyPrinter.isrecursive(object)
173
174 Determine if the object requires a recursive representation.
175
176This method is provided as a hook to allow subclasses to modify the way objects
177are converted to strings. The default implementation uses the internals of the
178:func:`saferepr` implementation.
179
180
181.. method:: PrettyPrinter.format(object, context, maxlevels, level)
182
183 Returns three values: the formatted version of *object* as a string, a flag
184 indicating whether the result is readable, and a flag indicating whether
185 recursion was detected. The first argument is the object to be presented. The
186 second is a dictionary which contains the :func:`id` of objects that are part of
187 the current presentation context (direct and indirect containers for *object*
188 that are affecting the presentation) as the keys; if an object needs to be
189 presented which is already represented in *context*, the third return value
190 should be ``True``. Recursive calls to the :meth:`format` method should add
191 additional entries for containers to this dictionary. The third argument,
192 *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there
193 is no requested limit. This argument should be passed unmodified to recursive
194 calls. The fourth argument, *level*, gives the current level; recursive calls
195 should be passed a value less than that of the current call.
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000196
197
198.. _pprint-example:
199
200pprint Example
201--------------
202
203This example demonstrates several uses of the :func:`pprint` function and its parameters.
204
205 >>> import pprint
206 >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
207 ... ('parrot', ('fresh fruit',))))))))
208 >>> stuff = ['a' * 10, tup, ['a' * 30, 'b' * 30], ['c' * 20, 'd' * 20]]
209 >>> pprint.pprint(stuff)
210 ['aaaaaaaaaa',
211 ('spam',
212 ('eggs',
213 ('lumberjack',
214 ('knights', ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
215 ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
216 ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
217 >>> pprint.pprint(stuff, depth=3)
218 ['aaaaaaaaaa',
219 ('spam', ('eggs', ('lumberjack', (...)))),
220 ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
221 ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
222 >>> pprint.pprint(stuff, width=60)
223 ['aaaaaaaaaa',
224 ('spam',
225 ('eggs',
226 ('lumberjack',
227 ('knights',
228 ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
229 ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
230 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
231 ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
232