7f13029153949a94e8b66383495ee36c19745cc6
[profile/ivi/python.git] / Doc / library / pprint.rst
1
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
11 The :mod:`pprint` module provides a capability to "pretty-print" arbitrary
12 Python data structures in a form which can be used as input to the interpreter.
13 If the formatted structures include objects which are not fundamental Python
14 types, the representation may not be loadable.  This may be the case if objects
15 such as files, sockets, classes, or instances are included, as well as many
16 other built-in objects which are not representable as Python constants.
17
18 The formatted representation keeps objects on a single line if it can, and
19 breaks them onto multiple lines if they don't fit within the allowed width.
20 Construct :class:`PrettyPrinter` objects explicitly if you need to adjust the
21 width constraint.
22
23 .. versionchanged:: 2.5
24    Dictionaries are sorted by key before the display is computed; before 2.5, a
25    dictionary was sorted only if its display required more than one line, although
26    that wasn't documented.
27
28 .. versionchanged:: 2.6
29    Added support for :class:`set` and :class:`frozenset`.
30
31 .. seealso::
32
33    Latest version of the `pprint module Python source code
34    <http://svn.python.org/view/python/branches/release27-maint/Lib/pprint.py?view=markup>`_
35
36 The :mod:`pprint` module defines one class:
37
38 .. First the implementation class:
39
40
41 .. class:: PrettyPrinter(...)
42
43    Construct a :class:`PrettyPrinter` instance.  This constructor understands
44    several keyword parameters.  An output stream may be set using the *stream*
45    keyword; the only method used on the stream object is the file protocol's
46    :meth:`write` method.  If not specified, the :class:`PrettyPrinter` adopts
47    ``sys.stdout``.  Three additional parameters may be used to control the
48    formatted representation.  The keywords are *indent*, *depth*, and *width*.  The
49    amount of indentation added for each recursive level is specified by *indent*;
50    the default is one.  Other values can cause output to look a little odd, but can
51    make nesting easier to spot.  The number of levels which may be printed is
52    controlled by *depth*; if the data structure being printed is too deep, the next
53    contained level is replaced by ``...``.  By default, there is no constraint on
54    the depth of the objects being formatted.  The desired output width is
55    constrained using the *width* parameter; the default is 80 characters.  If a
56    structure cannot be formatted within the constrained width, a best effort will
57    be made.
58
59       >>> import pprint
60       >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
61       >>> stuff.insert(0, stuff[:])
62       >>> pp = pprint.PrettyPrinter(indent=4)
63       >>> pp.pprint(stuff)
64       [   ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
65           'spam',
66           'eggs',
67           'lumberjack',
68           'knights',
69           'ni']
70       >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
71       ... ('parrot', ('fresh fruit',))))))))
72       >>> pp = pprint.PrettyPrinter(depth=6)
73       >>> pp.pprint(tup)
74       ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
75
76 The :class:`PrettyPrinter` class supports several derivative functions:
77
78 .. Now the derivative functions:
79
80 .. function:: pformat(object[, indent[, width[, depth]]])
81
82    Return the formatted representation of *object* as a string.  *indent*, *width*
83    and *depth* will be passed to the :class:`PrettyPrinter` constructor as
84    formatting parameters.
85
86    .. versionchanged:: 2.4
87       The parameters *indent*, *width* and *depth* were added.
88
89
90 .. function:: pprint(object[, stream[, indent[, width[, depth]]]])
91
92    Prints the formatted representation of *object* on *stream*, followed by a
93    newline.  If *stream* is omitted, ``sys.stdout`` is used.  This may be used in
94    the interactive interpreter instead of a :keyword:`print` statement for
95    inspecting values.    *indent*, *width* and *depth* will be passed to the
96    :class:`PrettyPrinter` constructor as formatting parameters.
97
98       >>> import pprint
99       >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
100       >>> stuff.insert(0, stuff)
101       >>> pprint.pprint(stuff)
102       [<Recursion on list with id=...>,
103        'spam',
104        'eggs',
105        'lumberjack',
106        'knights',
107        'ni']
108
109    .. versionchanged:: 2.4
110       The parameters *indent*, *width* and *depth* were added.
111
112
113 .. function:: isreadable(object)
114
115    .. index:: builtin: eval
116
117    Determine if the formatted representation of *object* is "readable," or can be
118    used to reconstruct the value using :func:`eval`.  This always returns ``False``
119    for recursive objects.
120
121       >>> pprint.isreadable(stuff)
122       False
123
124
125 .. function:: isrecursive(object)
126
127    Determine if *object* requires a recursive representation.
128
129
130 One more support function is also defined:
131
132 .. function:: saferepr(object)
133
134    Return a string representation of *object*, protected against recursive data
135    structures.  If the representation of *object* exposes a recursive entry, the
136    recursive reference will be represented as ``<Recursion on typename with
137    id=number>``.  The representation is not otherwise formatted.
138
139    >>> pprint.saferepr(stuff)
140    "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
141
142
143 .. _prettyprinter-objects:
144
145 PrettyPrinter 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
162 The following methods provide the implementations for the corresponding
163 functions of the same names.  Using these methods on an instance is slightly
164 more efficient since new :class:`PrettyPrinter` objects don't need to be
165 created.
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
183 This method is provided as a hook to allow subclasses to modify the way objects
184 are 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.
203
204    .. versionadded:: 2.3
205
206 .. _pprint-example:
207
208 pprint Example
209 --------------
210
211 This example demonstrates several uses of the :func:`pprint` function and its parameters.
212
213    >>> import pprint
214    >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
215    ... ('parrot', ('fresh fruit',))))))))
216    >>> stuff = ['a' * 10, tup, ['a' * 30, 'b' * 30], ['c' * 20, 'd' * 20]]
217    >>> pprint.pprint(stuff)
218    ['aaaaaaaaaa',
219     ('spam',
220      ('eggs',
221       ('lumberjack',
222        ('knights', ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
223     ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
224     ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
225    >>> pprint.pprint(stuff, depth=3)
226    ['aaaaaaaaaa',
227     ('spam', ('eggs', (...))),
228     ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
229     ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
230    >>> pprint.pprint(stuff, width=60)
231    ['aaaaaaaaaa',
232     ('spam',
233      ('eggs',
234       ('lumberjack',
235        ('knights',
236         ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
237     ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
238      'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
239     ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
240