Issue 2188: Documentation hint about disabling proxy detection.
[python.git] / Doc / library / pprint.rst
blobae9677f9bfaf46872ce3d4ef15b49ff61032aff8
2 :mod:`pprint` --- Data pretty printer
3 =====================================
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>
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 builtin objects which are not representable as Python constants.
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.
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.
28 .. versionchanged:: 2.6
29    Added support for :class:`set` and :class:`frozenset`.
31 The :mod:`pprint` module defines one class:
33 .. First the implementation class:
36 .. class:: PrettyPrinter(...)
38    Construct a :class:`PrettyPrinter` instance.  This constructor understands
39    several keyword parameters.  An output stream may be set using the *stream*
40    keyword; the only method used on the stream object is the file protocol's
41    :meth:`write` method.  If not specified, the :class:`PrettyPrinter` adopts
42    ``sys.stdout``.  Three additional parameters may be used to control the
43    formatted representation.  The keywords are *indent*, *depth*, and *width*.  The
44    amount of indentation added for each recursive level is specified by *indent*;
45    the default is one.  Other values can cause output to look a little odd, but can
46    make nesting easier to spot.  The number of levels which may be printed is
47    controlled by *depth*; if the data structure being printed is too deep, the next
48    contained level is replaced by ``...``.  By default, there is no constraint on
49    the depth of the objects being formatted.  The desired output width is
50    constrained using the *width* parameter; the default is 80 characters.  If a
51    structure cannot be formatted within the constrained width, a best effort will
52    be made. ::
54       >>> import pprint
55       >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
56       >>> stuff.insert(0, stuff[:])
57       >>> pp = pprint.PrettyPrinter(indent=4)
58       >>> pp.pprint(stuff)
59       [   ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
60           'spam',
61           'eggs',
62           'lumberjack',
63           'knights',
64           'ni']
65       >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
66       ... ('parrot', ('fresh fruit',))))))))
67       >>> pp = pprint.PrettyPrinter(depth=6)
68       >>> pp.pprint(tup)
69       ('spam',
70        ('eggs', ('lumberjack', ('knights', ('ni', ('dead', ('parrot', (...,))))))))
72 The :class:`PrettyPrinter` class supports several derivative functions:
74 .. Now the derivative functions:
76 .. function:: pformat(object[, indent[, width[, depth]]])
78    Return the formatted representation of *object* as a string.  *indent*, *width*
79    and *depth* will be passed to the :class:`PrettyPrinter` constructor as
80    formatting parameters.
82    .. versionchanged:: 2.4
83       The parameters *indent*, *width* and *depth* were added.
86 .. function:: pprint(object[, stream[, indent[, width[, depth]]]])
88    Prints the formatted representation of *object* on *stream*, followed by a
89    newline.  If *stream* is omitted, ``sys.stdout`` is used.  This may be used in
90    the interactive interpreter instead of a :keyword:`print` statement for
91    inspecting values.    *indent*, *width* and *depth* will be passed to the
92    :class:`PrettyPrinter` constructor as formatting parameters. ::
94       >>> import pprint
95       >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
96       >>> stuff.insert(0, stuff)
97       >>> pprint.pprint(stuff)
98       [<Recursion on list with id=869440>,
99        '',
100        '/usr/local/lib/python1.5',
101        '/usr/local/lib/python1.5/test',
102        '/usr/local/lib/python1.5/sunos5',
103        '/usr/local/lib/python1.5/sharedmodules',
104        '/usr/local/lib/python1.5/tkinter']
106    .. versionchanged:: 2.4
107       The parameters *indent*, *width* and *depth* were added.
110 .. function:: isreadable(object)
112    .. index:: builtin: eval
114    Determine if the formatted representation of *object* is "readable," or can be
115    used to reconstruct the value using :func:`eval`.  This always returns ``False``
116    for recursive objects. ::
118       >>> pprint.isreadable(stuff)
119       False
122 .. function:: isrecursive(object)
124    Determine if *object* requires a recursive representation.
126 One more support function is also defined:
129 .. function:: saferepr(object)
131    Return a string representation of *object*, protected against recursive data
132    structures.  If the representation of *object* exposes a recursive entry, the
133    recursive reference will be represented as ``<Recursion on typename with
134    id=number>``.  The representation is not otherwise formatted.
138    >>> pprint.saferepr(stuff)
139    "[<Recursion on list with id=682968>, '', '/usr/local/lib/python1.5', '/usr/loca
140    l/lib/python1.5/test', '/usr/local/lib/python1.5/sunos5', '/usr/local/lib/python
141    1.5/sharedmodules', '/usr/local/lib/python1.5/tkinter']"
144 .. _prettyprinter-objects:
146 PrettyPrinter Objects
147 ---------------------
149 :class:`PrettyPrinter` instances have the following methods:
152 .. method:: PrettyPrinter.pformat(object)
154    Return the formatted representation of *object*.  This takes into account the
155    options passed to the :class:`PrettyPrinter` constructor.
158 .. method:: PrettyPrinter.pprint(object)
160    Print the formatted representation of *object* on the configured stream,
161    followed by a newline.
163 The following methods provide the implementations for the corresponding
164 functions of the same names.  Using these methods on an instance is slightly
165 more efficient since new :class:`PrettyPrinter` objects don't need to be
166 created.
169 .. method:: PrettyPrinter.isreadable(object)
171    .. index:: builtin: eval
173    Determine if the formatted representation of the object is "readable," or can be
174    used to reconstruct the value using :func:`eval`.  Note that this returns
175    ``False`` for recursive objects.  If the *depth* parameter of the
176    :class:`PrettyPrinter` is set and the object is deeper than allowed, this
177    returns ``False``.
180 .. method:: PrettyPrinter.isrecursive(object)
182    Determine if the object requires a recursive representation.
184 This method is provided as a hook to allow subclasses to modify the way objects
185 are converted to strings.  The default implementation uses the internals of the
186 :func:`saferepr` implementation.
189 .. method:: PrettyPrinter.format(object, context, maxlevels, level)
191    Returns three values: the formatted version of *object* as a string, a flag
192    indicating whether the result is readable, and a flag indicating whether
193    recursion was detected.  The first argument is the object to be presented.  The
194    second is a dictionary which contains the :func:`id` of objects that are part of
195    the current presentation context (direct and indirect containers for *object*
196    that are affecting the presentation) as the keys; if an object needs to be
197    presented which is already represented in *context*, the third return value
198    should be ``True``.  Recursive calls to the :meth:`format` method should add
199    additional entries for containers to this dictionary.  The third argument,
200    *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there
201    is no requested limit.  This argument should be passed unmodified to recursive
202    calls. The fourth argument, *level*, gives the current level; recursive calls
203    should be passed a value less than that of the current call.
205    .. versionadded:: 2.3
207 .. _pprint-example:
209 pprint Example
210 --------------
212 This example demonstrates several uses of the :func:`pprint` function and its parameters.
214    >>> import pprint
215    >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
216    ... ('parrot', ('fresh fruit',))))))))
217    >>> stuff = ['a' * 10, tup, ['a' * 30, 'b' * 30], ['c' * 20, 'd' * 20]]
218    >>> pprint.pprint(stuff)
219    ['aaaaaaaaaa',
220     ('spam',
221      ('eggs',
222       ('lumberjack',
223        ('knights', ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
224     ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
225     ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
226    >>> pprint.pprint(stuff, depth=3)
227    ['aaaaaaaaaa',
228     ('spam', ('eggs', ('lumberjack', (...)))),
229     ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
230     ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
231    >>> pprint.pprint(stuff, width=60)
232    ['aaaaaaaaaa',
233     ('spam',
234      ('eggs',
235       ('lumberjack',
236        ('knights',
237         ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
238     ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
239      'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
240     ['cccccccccccccccccccc', 'dddddddddddddddddddd']]