blob: d00caba4e33e59a574bdf67d3fcf6f85301f8481 [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
48 >>> import pprint, sys
49 >>> stuff = sys.path[:]
50 >>> stuff.insert(0, stuff[:])
51 >>> pp = pprint.PrettyPrinter(indent=4)
52 >>> pp.pprint(stuff)
53 [ [ '',
54 '/usr/local/lib/python1.5',
55 '/usr/local/lib/python1.5/test',
56 '/usr/local/lib/python1.5/sunos5',
57 '/usr/local/lib/python1.5/sharedmodules',
58 '/usr/local/lib/python1.5/tkinter'],
59 '',
60 '/usr/local/lib/python1.5',
61 '/usr/local/lib/python1.5/test',
62 '/usr/local/lib/python1.5/sunos5',
63 '/usr/local/lib/python1.5/sharedmodules',
64 '/usr/local/lib/python1.5/tkinter']
65 >>>
66 >>> import parser
67 >>> tup = parser.ast2tuple(
68 ... parser.suite(open('pprint.py').read()))[1][1][1]
69 >>> pp = pprint.PrettyPrinter(depth=6)
70 >>> pp.pprint(tup)
71 (266, (267, (307, (287, (288, (...))))))
72
73The :class:`PrettyPrinter` class supports several derivative functions:
74
75.. % Now the derivative functions:
76
77
78.. function:: pformat(object[, indent[, width[, depth]]])
79
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.
83
Georg Brandl116aa622007-08-15 14:28:22 +000084
85.. function:: pprint(object[, stream[, indent[, width[, depth]]]])
86
87 Prints the formatted representation of *object* on *stream*, followed by a
Georg Brandl6911e3c2007-09-04 07:15:32 +000088 newline. If *stream* is omitted, ``sys.stdout`` is used. This may be used
89 in the interactive interpreter instead of the :func:`print` function for
90 inspecting values (you can even reassign ``print = pprint.pprint`` for use
91 within a scope). *indent*, *width* and *depth* will be passed to the
Georg Brandl116aa622007-08-15 14:28:22 +000092 :class:`PrettyPrinter` constructor as formatting parameters. ::
93
94 >>> stuff = sys.path[:]
95 >>> stuff.insert(0, stuff)
96 >>> pprint.pprint(stuff)
97 [<Recursion on list with id=869440>,
98 '',
99 '/usr/local/lib/python1.5',
100 '/usr/local/lib/python1.5/test',
101 '/usr/local/lib/python1.5/sunos5',
102 '/usr/local/lib/python1.5/sharedmodules',
103 '/usr/local/lib/python1.5/tkinter']
104
Georg Brandl116aa622007-08-15 14:28:22 +0000105
106.. function:: isreadable(object)
107
108 .. index:: builtin: eval
109
110 Determine if the formatted representation of *object* is "readable," or can be
111 used to reconstruct the value using :func:`eval`. This always returns ``False``
112 for recursive objects. ::
113
114 >>> pprint.isreadable(stuff)
115 False
116
117
118.. function:: isrecursive(object)
119
120 Determine if *object* requires a recursive representation.
121
122One more support function is also defined:
123
124
125.. function:: saferepr(object)
126
127 Return a string representation of *object*, protected against recursive data
128 structures. If the representation of *object* exposes a recursive entry, the
129 recursive reference will be represented as ``<Recursion on typename with
130 id=number>``. The representation is not otherwise formatted.
131
132.. % This example is outside the {funcdesc} to keep it from running over
133.. % the right margin.
134
135::
136
137 >>> pprint.saferepr(stuff)
138 "[<Recursion on list with id=682968>, '', '/usr/local/lib/python1.5', '/usr/loca
139 l/lib/python1.5/test', '/usr/local/lib/python1.5/sunos5', '/usr/local/lib/python
140 1.5/sharedmodules', '/usr/local/lib/python1.5/tkinter']"
141
142
143.. _prettyprinter-objects:
144
145PrettyPrinter Objects
146---------------------
147
148:class:`PrettyPrinter` instances have the following methods:
149
150
151.. method:: PrettyPrinter.pformat(object)
152
153 Return the formatted representation of *object*. This takes into account the
154 options passed to the :class:`PrettyPrinter` constructor.
155
156
157.. method:: PrettyPrinter.pprint(object)
158
159 Print the formatted representation of *object* on the configured stream,
160 followed by a newline.
161
162The following methods provide the implementations for the corresponding
163functions of the same names. Using these methods on an instance is slightly
164more efficient since new :class:`PrettyPrinter` objects don't need to be
165created.
166
167
168.. method:: PrettyPrinter.isreadable(object)
169
170 .. index:: builtin: eval
171
172 Determine if the formatted representation of the object is "readable," or can be
173 used to reconstruct the value using :func:`eval`. Note that this returns
174 ``False`` for recursive objects. If the *depth* parameter of the
175 :class:`PrettyPrinter` is set and the object is deeper than allowed, this
176 returns ``False``.
177
178
179.. method:: PrettyPrinter.isrecursive(object)
180
181 Determine if the object requires a recursive representation.
182
183This method is provided as a hook to allow subclasses to modify the way objects
184are converted to strings. The default implementation uses the internals of the
185:func:`saferepr` implementation.
186
187
188.. method:: PrettyPrinter.format(object, context, maxlevels, level)
189
190 Returns three values: the formatted version of *object* as a string, a flag
191 indicating whether the result is readable, and a flag indicating whether
192 recursion was detected. The first argument is the object to be presented. The
193 second is a dictionary which contains the :func:`id` of objects that are part of
194 the current presentation context (direct and indirect containers for *object*
195 that are affecting the presentation) as the keys; if an object needs to be
196 presented which is already represented in *context*, the third return value
197 should be ``True``. Recursive calls to the :meth:`format` method should add
198 additional entries for containers to this dictionary. The third argument,
199 *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there
200 is no requested limit. This argument should be passed unmodified to recursive
201 calls. The fourth argument, *level*, gives the current level; recursive calls
202 should be passed a value less than that of the current call.