Update to 2.7.3
[profile/ivi/python.git] / Doc / library / pprint.rst
1 :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
9 **Source code:** :source:`Lib/pprint.py`
10
11 --------------
12
13 The :mod:`pprint` module provides a capability to "pretty-print" arbitrary
14 Python data structures in a form which can be used as input to the interpreter.
15 If the formatted structures include objects which are not fundamental Python
16 types, the representation may not be loadable.  This may be the case if objects
17 such as files, sockets, classes, or instances are included, as well as many
18 other built-in objects which are not representable as Python constants.
19
20 The formatted representation keeps objects on a single line if it can, and
21 breaks them onto multiple lines if they don't fit within the allowed width.
22 Construct :class:`PrettyPrinter` objects explicitly if you need to adjust the
23 width 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
30 .. versionchanged:: 2.6
31    Added support for :class:`set` and :class:`frozenset`.
32
33
34 The :mod:`pprint` module defines one class:
35
36 .. First the implementation class:
37
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
55    be made.
56
57       >>> import pprint
58       >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
59       >>> stuff.insert(0, stuff[:])
60       >>> pp = pprint.PrettyPrinter(indent=4)
61       >>> pp.pprint(stuff)
62       [   ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
63           'spam',
64           'eggs',
65           'lumberjack',
66           'knights',
67           'ni']
68       >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
69       ... ('parrot', ('fresh fruit',))))))))
70       >>> pp = pprint.PrettyPrinter(depth=6)
71       >>> pp.pprint(tup)
72       ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
73
74 The :class:`PrettyPrinter` class supports several derivative functions:
75
76 .. Now the derivative functions:
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
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
94    :class:`PrettyPrinter` constructor as formatting parameters.
95
96       >>> import pprint
97       >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
98       >>> stuff.insert(0, stuff)
99       >>> pprint.pprint(stuff)
100       [<Recursion on list with id=...>,
101        'spam',
102        'eggs',
103        'lumberjack',
104        'knights',
105        'ni']
106
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``
117    for recursive objects.
118
119       >>> pprint.isreadable(stuff)
120       False
121
122
123 .. function:: isrecursive(object)
124
125    Determine if *object* requires a recursive representation.
126
127
128 One more support function is also defined:
129
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
137    >>> pprint.saferepr(stuff)
138    "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
139
140
141 .. _prettyprinter-objects:
142
143 PrettyPrinter 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
160 The following methods provide the implementations for the corresponding
161 functions of the same names.  Using these methods on an instance is slightly
162 more efficient since new :class:`PrettyPrinter` objects don't need to be
163 created.
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
181 This method is provided as a hook to allow subclasses to modify the way objects
182 are 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
204 .. _pprint-example:
205
206 pprint Example
207 --------------
208
209 This 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',
225     ('spam', ('eggs', (...))),
226     ['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