blob: a0a72005c1feb5cc34a5010fc59d3a71e8f43ca0 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`pprint` --- Data pretty printer
2=====================================
3
4.. module:: pprint
5 :synopsis: Data pretty printer.
6.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
7.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
8
Éric Araujo29a0b572011-08-19 02:14:03 +02009**Source code:** :source:`Lib/pprint.py`
10
11--------------
Georg Brandl8ec7f652007-08-15 14:28:01 +000012
13The :mod:`pprint` module provides a capability to "pretty-print" arbitrary
14Python data structures in a form which can be used as input to the interpreter.
15If the formatted structures include objects which are not fundamental Python
16types, the representation may not be loadable. This may be the case if objects
17such as files, sockets, classes, or instances are included, as well as many
Georg Brandld7d4fd72009-07-26 14:37:28 +000018other built-in objects which are not representable as Python constants.
Georg Brandl8ec7f652007-08-15 14:28:01 +000019
20The formatted representation keeps objects on a single line if it can, and
21breaks them onto multiple lines if they don't fit within the allowed width.
22Construct :class:`PrettyPrinter` objects explicitly if you need to adjust the
23width constraint.
24
25.. versionchanged:: 2.5
26 Dictionaries are sorted by key before the display is computed; before 2.5, a
27 dictionary was sorted only if its display required more than one line, although
28 that wasn't documented.
29
Raymond Hettingerc226c312008-01-23 00:04:40 +000030.. versionchanged:: 2.6
31 Added support for :class:`set` and :class:`frozenset`.
32
Raymond Hettingere0e08222010-11-06 07:10:31 +000033
Georg Brandl8ec7f652007-08-15 14:28:01 +000034The :mod:`pprint` module defines one class:
35
Georg Brandlb19be572007-12-29 10:57:00 +000036.. First the implementation class:
Georg Brandl8ec7f652007-08-15 14:28:01 +000037
38
39.. class:: PrettyPrinter(...)
40
41 Construct a :class:`PrettyPrinter` instance. This constructor understands
42 several keyword parameters. An output stream may be set using the *stream*
43 keyword; the only method used on the stream object is the file protocol's
44 :meth:`write` method. If not specified, the :class:`PrettyPrinter` adopts
45 ``sys.stdout``. Three additional parameters may be used to control the
46 formatted representation. The keywords are *indent*, *depth*, and *width*. The
47 amount of indentation added for each recursive level is specified by *indent*;
48 the default is one. Other values can cause output to look a little odd, but can
49 make nesting easier to spot. The number of levels which may be printed is
50 controlled by *depth*; if the data structure being printed is too deep, the next
51 contained level is replaced by ``...``. By default, there is no constraint on
52 the depth of the objects being formatted. The desired output width is
53 constrained using the *width* parameter; the default is 80 characters. If a
54 structure cannot be formatted within the constrained width, a best effort will
Georg Brandl473f1642008-03-22 12:59:37 +000055 be made.
Georg Brandl8ec7f652007-08-15 14:28:01 +000056
Georg Brandl722e1012007-12-05 17:56:50 +000057 >>> import pprint
58 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl8ec7f652007-08-15 14:28:01 +000059 >>> stuff.insert(0, stuff[:])
60 >>> pp = pprint.PrettyPrinter(indent=4)
61 >>> pp.pprint(stuff)
Facundo Batista2da91c32008-06-21 17:43:56 +000062 [ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
Georg Brandl722e1012007-12-05 17:56:50 +000063 'spam',
64 'eggs',
65 'lumberjack',
66 'knights',
67 'ni']
68 >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
69 ... ('parrot', ('fresh fruit',))))))))
Georg Brandl8ec7f652007-08-15 14:28:01 +000070 >>> pp = pprint.PrettyPrinter(depth=6)
71 >>> pp.pprint(tup)
Georg Brandl23da6e62008-05-12 16:26:52 +000072 ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
Georg Brandl8ec7f652007-08-15 14:28:01 +000073
74The :class:`PrettyPrinter` class supports several derivative functions:
75
Georg Brandlb19be572007-12-29 10:57:00 +000076.. Now the derivative functions:
Georg Brandl8ec7f652007-08-15 14:28:01 +000077
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
84 .. versionchanged:: 2.4
85 The parameters *indent*, *width* and *depth* were added.
86
87
88.. function:: pprint(object[, stream[, indent[, width[, depth]]]])
89
90 Prints the formatted representation of *object* on *stream*, followed by a
91 newline. If *stream* is omitted, ``sys.stdout`` is used. This may be used in
92 the interactive interpreter instead of a :keyword:`print` statement for
93 inspecting values. *indent*, *width* and *depth* will be passed to the
Georg Brandl473f1642008-03-22 12:59:37 +000094 :class:`PrettyPrinter` constructor as formatting parameters.
Georg Brandl8ec7f652007-08-15 14:28:01 +000095
Georg Brandl722e1012007-12-05 17:56:50 +000096 >>> import pprint
97 >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
Georg Brandl8ec7f652007-08-15 14:28:01 +000098 >>> stuff.insert(0, stuff)
99 >>> pprint.pprint(stuff)
Georg Brandl473f1642008-03-22 12:59:37 +0000100 [<Recursion on list with id=...>,
101 'spam',
102 'eggs',
103 'lumberjack',
104 'knights',
105 'ni']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000106
107 .. versionchanged:: 2.4
108 The parameters *indent*, *width* and *depth* were added.
109
110
111.. function:: isreadable(object)
112
113 .. index:: builtin: eval
114
115 Determine if the formatted representation of *object* is "readable," or can be
116 used to reconstruct the value using :func:`eval`. This always returns ``False``
Georg Brandl473f1642008-03-22 12:59:37 +0000117 for recursive objects.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000118
119 >>> pprint.isreadable(stuff)
120 False
121
122
123.. function:: isrecursive(object)
124
125 Determine if *object* requires a recursive representation.
126
Georg Brandl8ec7f652007-08-15 14:28:01 +0000127
Georg Brandl473f1642008-03-22 12:59:37 +0000128One more support function is also defined:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000129
130.. function:: saferepr(object)
131
132 Return a string representation of *object*, protected against recursive data
133 structures. If the representation of *object* exposes a recursive entry, the
134 recursive reference will be represented as ``<Recursion on typename with
135 id=number>``. The representation is not otherwise formatted.
136
Georg Brandl8ec7f652007-08-15 14:28:01 +0000137 >>> pprint.saferepr(stuff)
Georg Brandl473f1642008-03-22 12:59:37 +0000138 "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000139
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',
Georg Brandl23da6e62008-05-12 16:26:52 +0000225 ('spam', ('eggs', (...))),
Georg Brandl722e1012007-12-05 17:56:50 +0000226 ['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