blob: 2e4f3f22e46aa5a13b47505bf123c11faab1c100 [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
25The :mod:`pprint` module defines one class:
26
27.. % First the implementation class:
28
29
30.. class:: PrettyPrinter(...)
31
32 Construct a :class:`PrettyPrinter` instance. This constructor understands
33 several keyword parameters. An output stream may be set using the *stream*
34 keyword; the only method used on the stream object is the file protocol's
35 :meth:`write` method. If not specified, the :class:`PrettyPrinter` adopts
36 ``sys.stdout``. Three additional parameters may be used to control the
37 formatted representation. The keywords are *indent*, *depth*, and *width*. The
38 amount of indentation added for each recursive level is specified by *indent*;
39 the default is one. Other values can cause output to look a little odd, but can
40 make nesting easier to spot. The number of levels which may be printed is
41 controlled by *depth*; if the data structure being printed is too deep, the next
42 contained level is replaced by ``...``. By default, there is no constraint on
43 the depth of the objects being formatted. The desired output width is
44 constrained using the *width* parameter; the default is 80 characters. If a
45 structure cannot be formatted within the constrained width, a best effort will
46 be made. ::
47
Christian Heimesb9eccbf2007-12-05 20:18:38 +000048 >>> import pprint
49 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +000050 >>> stuff.insert(0, stuff[:])
51 >>> pp = pprint.PrettyPrinter(indent=4)
52 >>> pp.pprint(stuff)
Christian Heimesb9eccbf2007-12-05 20:18:38 +000053 [ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
54 'spam',
55 'eggs',
56 'lumberjack',
57 'knights',
58 'ni']
59 >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
60 ... ('parrot', ('fresh fruit',))))))))
Georg Brandl116aa622007-08-15 14:28:22 +000061 >>> pp = pprint.PrettyPrinter(depth=6)
62 >>> pp.pprint(tup)
Christian Heimesb9eccbf2007-12-05 20:18:38 +000063 ('spam',
64 ('eggs', ('lumberjack', ('knights', ('ni', ('dead', ('parrot', (...,))))))))
Georg Brandl116aa622007-08-15 14:28:22 +000065
66The :class:`PrettyPrinter` class supports several derivative functions:
67
68.. % Now the derivative functions:
69
70
71.. function:: pformat(object[, indent[, width[, depth]]])
72
73 Return the formatted representation of *object* as a string. *indent*, *width*
74 and *depth* will be passed to the :class:`PrettyPrinter` constructor as
75 formatting parameters.
76
Georg Brandl116aa622007-08-15 14:28:22 +000077
78.. function:: pprint(object[, stream[, indent[, width[, depth]]]])
79
80 Prints the formatted representation of *object* on *stream*, followed by a
Georg Brandl6911e3c2007-09-04 07:15:32 +000081 newline. If *stream* is omitted, ``sys.stdout`` is used. This may be used
82 in the interactive interpreter instead of the :func:`print` function for
83 inspecting values (you can even reassign ``print = pprint.pprint`` for use
84 within a scope). *indent*, *width* and *depth* will be passed to the
Georg Brandl116aa622007-08-15 14:28:22 +000085 :class:`PrettyPrinter` constructor as formatting parameters. ::
86
Christian Heimesb9eccbf2007-12-05 20:18:38 +000087 >>> import pprint
88 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl116aa622007-08-15 14:28:22 +000089 >>> stuff.insert(0, stuff)
90 >>> pprint.pprint(stuff)
91 [<Recursion on list with id=869440>,
92 '',
93 '/usr/local/lib/python1.5',
94 '/usr/local/lib/python1.5/test',
95 '/usr/local/lib/python1.5/sunos5',
96 '/usr/local/lib/python1.5/sharedmodules',
97 '/usr/local/lib/python1.5/tkinter']
98
Georg Brandl116aa622007-08-15 14:28:22 +000099
100.. function:: isreadable(object)
101
102 .. index:: builtin: eval
103
104 Determine if the formatted representation of *object* is "readable," or can be
105 used to reconstruct the value using :func:`eval`. This always returns ``False``
106 for recursive objects. ::
107
108 >>> pprint.isreadable(stuff)
109 False
110
111
112.. function:: isrecursive(object)
113
114 Determine if *object* requires a recursive representation.
115
116One more support function is also defined:
117
118
119.. function:: saferepr(object)
120
121 Return a string representation of *object*, protected against recursive data
122 structures. If the representation of *object* exposes a recursive entry, the
123 recursive reference will be represented as ``<Recursion on typename with
124 id=number>``. The representation is not otherwise formatted.
125
126.. % This example is outside the {funcdesc} to keep it from running over
127.. % the right margin.
128
129::
130
131 >>> pprint.saferepr(stuff)
132 "[<Recursion on list with id=682968>, '', '/usr/local/lib/python1.5', '/usr/loca
133 l/lib/python1.5/test', '/usr/local/lib/python1.5/sunos5', '/usr/local/lib/python
134 1.5/sharedmodules', '/usr/local/lib/python1.5/tkinter']"
135
136
137.. _prettyprinter-objects:
138
139PrettyPrinter Objects
140---------------------
141
142:class:`PrettyPrinter` instances have the following methods:
143
144
145.. method:: PrettyPrinter.pformat(object)
146
147 Return the formatted representation of *object*. This takes into account the
148 options passed to the :class:`PrettyPrinter` constructor.
149
150
151.. method:: PrettyPrinter.pprint(object)
152
153 Print the formatted representation of *object* on the configured stream,
154 followed by a newline.
155
156The following methods provide the implementations for the corresponding
157functions of the same names. Using these methods on an instance is slightly
158more efficient since new :class:`PrettyPrinter` objects don't need to be
159created.
160
161
162.. method:: PrettyPrinter.isreadable(object)
163
164 .. index:: builtin: eval
165
166 Determine if the formatted representation of the object is "readable," or can be
167 used to reconstruct the value using :func:`eval`. Note that this returns
168 ``False`` for recursive objects. If the *depth* parameter of the
169 :class:`PrettyPrinter` is set and the object is deeper than allowed, this
170 returns ``False``.
171
172
173.. method:: PrettyPrinter.isrecursive(object)
174
175 Determine if the object requires a recursive representation.
176
177This method is provided as a hook to allow subclasses to modify the way objects
178are converted to strings. The default implementation uses the internals of the
179:func:`saferepr` implementation.
180
181
182.. method:: PrettyPrinter.format(object, context, maxlevels, level)
183
184 Returns three values: the formatted version of *object* as a string, a flag
185 indicating whether the result is readable, and a flag indicating whether
186 recursion was detected. The first argument is the object to be presented. The
187 second is a dictionary which contains the :func:`id` of objects that are part of
188 the current presentation context (direct and indirect containers for *object*
189 that are affecting the presentation) as the keys; if an object needs to be
190 presented which is already represented in *context*, the third return value
191 should be ``True``. Recursive calls to the :meth:`format` method should add
192 additional entries for containers to this dictionary. The third argument,
193 *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there
194 is no requested limit. This argument should be passed unmodified to recursive
195 calls. The fourth argument, *level*, gives the current level; recursive calls
196 should be passed a value less than that of the current call.
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000197
198
199.. _pprint-example:
200
201pprint Example
202--------------
203
204This example demonstrates several uses of the :func:`pprint` function and its parameters.
205
206 >>> import pprint
207 >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
208 ... ('parrot', ('fresh fruit',))))))))
209 >>> stuff = ['a' * 10, tup, ['a' * 30, 'b' * 30], ['c' * 20, 'd' * 20]]
210 >>> pprint.pprint(stuff)
211 ['aaaaaaaaaa',
212 ('spam',
213 ('eggs',
214 ('lumberjack',
215 ('knights', ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
216 ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
217 ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
218 >>> pprint.pprint(stuff, depth=3)
219 ['aaaaaaaaaa',
220 ('spam', ('eggs', ('lumberjack', (...)))),
221 ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
222 ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
223 >>> pprint.pprint(stuff, width=60)
224 ['aaaaaaaaaa',
225 ('spam',
226 ('eggs',
227 ('lumberjack',
228 ('knights',
229 ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
230 ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
231 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
232 ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
233