blob: 3703c1cb3d7b7ef7844155abf44bb77cfe849b87 [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
88 newline. If *stream* is omitted, ``sys.stdout`` is used. This may be used in
89 the interactive interpreter instead of a :keyword:`print` statement for
90 inspecting values. *indent*, *width* and *depth* will be passed to the
91 :class:`PrettyPrinter` constructor as formatting parameters. ::
92
93 >>> stuff = sys.path[:]
94 >>> 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
Georg Brandl116aa622007-08-15 14:28:22 +0000104
105.. function:: isreadable(object)
106
107 .. index:: builtin: eval
108
109 Determine if the formatted representation of *object* is "readable," or can be
110 used to reconstruct the value using :func:`eval`. This always returns ``False``
111 for recursive objects. ::
112
113 >>> pprint.isreadable(stuff)
114 False
115
116
117.. function:: isrecursive(object)
118
119 Determine if *object* requires a recursive representation.
120
121One more support function is also defined:
122
123
124.. function:: saferepr(object)
125
126 Return a string representation of *object*, protected against recursive data
127 structures. If the representation of *object* exposes a recursive entry, the
128 recursive reference will be represented as ``<Recursion on typename with
129 id=number>``. The representation is not otherwise formatted.
130
131.. % This example is outside the {funcdesc} to keep it from running over
132.. % the right margin.
133
134::
135
136 >>> pprint.saferepr(stuff)
137 "[<Recursion on list with id=682968>, '', '/usr/local/lib/python1.5', '/usr/loca
138 l/lib/python1.5/test', '/usr/local/lib/python1.5/sunos5', '/usr/local/lib/python
139 1.5/sharedmodules', '/usr/local/lib/python1.5/tkinter']"
140
141
142.. _prettyprinter-objects:
143
144PrettyPrinter Objects
145---------------------
146
147:class:`PrettyPrinter` instances have the following methods:
148
149
150.. method:: PrettyPrinter.pformat(object)
151
152 Return the formatted representation of *object*. This takes into account the
153 options passed to the :class:`PrettyPrinter` constructor.
154
155
156.. method:: PrettyPrinter.pprint(object)
157
158 Print the formatted representation of *object* on the configured stream,
159 followed by a newline.
160
161The following methods provide the implementations for the corresponding
162functions of the same names. Using these methods on an instance is slightly
163more efficient since new :class:`PrettyPrinter` objects don't need to be
164created.
165
166
167.. method:: PrettyPrinter.isreadable(object)
168
169 .. index:: builtin: eval
170
171 Determine if the formatted representation of the object is "readable," or can be
172 used to reconstruct the value using :func:`eval`. Note that this returns
173 ``False`` for recursive objects. If the *depth* parameter of the
174 :class:`PrettyPrinter` is set and the object is deeper than allowed, this
175 returns ``False``.
176
177
178.. method:: PrettyPrinter.isrecursive(object)
179
180 Determine if the object requires a recursive representation.
181
182This method is provided as a hook to allow subclasses to modify the way objects
183are converted to strings. The default implementation uses the internals of the
184:func:`saferepr` implementation.
185
186
187.. method:: PrettyPrinter.format(object, context, maxlevels, level)
188
189 Returns three values: the formatted version of *object* as a string, a flag
190 indicating whether the result is readable, and a flag indicating whether
191 recursion was detected. The first argument is the object to be presented. The
192 second is a dictionary which contains the :func:`id` of objects that are part of
193 the current presentation context (direct and indirect containers for *object*
194 that are affecting the presentation) as the keys; if an object needs to be
195 presented which is already represented in *context*, the third return value
196 should be ``True``. Recursive calls to the :meth:`format` method should add
197 additional entries for containers to this dictionary. The third argument,
198 *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there
199 is no requested limit. This argument should be passed unmodified to recursive
200 calls. The fourth argument, *level*, gives the current level; recursive calls
201 should be passed a value less than that of the current call.