Home | History | Annotate | Download | only in library
      1 :mod:`pprint` --- Data pretty printer
      2 =====================================
      3 
      4 .. module:: pprint
      5    :synopsis: Data pretty printer.
      6 
      7 .. moduleauthor:: Fred L. Drake, Jr. <fdrake (a] acm.org>
      8 .. sectionauthor:: Fred L. Drake, Jr. <fdrake (a] acm.org>
      9 
     10 **Source code:** :source:`Lib/pprint.py`
     11 
     12 --------------
     13 
     14 The :mod:`pprint` module provides a capability to "pretty-print" arbitrary
     15 Python data structures in a form which can be used as input to the interpreter.
     16 If the formatted structures include objects which are not fundamental Python
     17 types, the representation may not be loadable.  This may be the case if objects
     18 such as files, sockets or classes are included, as well as many other
     19 objects which are not representable as Python literals.
     20 
     21 The formatted representation keeps objects on a single line if it can, and
     22 breaks them onto multiple lines if they don't fit within the allowed width.
     23 Construct :class:`PrettyPrinter` objects explicitly if you need to adjust the
     24 width constraint.
     25 
     26 Dictionaries are sorted by key before the display is computed.
     27 
     28 The :mod:`pprint` module defines one class:
     29 
     30 .. First the implementation class:
     31 
     32 
     33 .. index:: single: ...; placeholder
     34 
     35 .. class:: PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, \
     36                          compact=False)
     37 
     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``.  The
     43    amount of indentation added for each recursive level is specified by *indent*;
     44    the default is one.  Other values can cause output to look a little odd, but can
     45    make nesting easier to spot.  The number of levels which may be printed is
     46    controlled by *depth*; if the data structure being printed is too deep, the next
     47    contained level is replaced by ``...``.  By default, there is no constraint on
     48    the depth of the objects being formatted.  The desired output width is
     49    constrained using the *width* parameter; the default is 80 characters.  If a
     50    structure cannot be formatted within the constrained width, a best effort will
     51    be made.  If *compact* is false (the default) each item of a long sequence
     52    will be formatted on a separate line.  If *compact* is true, as many items
     53    as will fit within the *width* will be formatted on each output line.
     54 
     55    .. versionchanged:: 3.4
     56       Added the *compact* parameter.
     57 
     58       >>> import pprint
     59       >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
     60       >>> stuff.insert(0, stuff[:])
     61       >>> pp = pprint.PrettyPrinter(indent=4)
     62       >>> pp.pprint(stuff)
     63       [   ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
     64           'spam',
     65           'eggs',
     66           'lumberjack',
     67           'knights',
     68           'ni']
     69       >>> pp = pprint.PrettyPrinter(width=41, compact=True)
     70       >>> pp.pprint(stuff)
     71       [['spam', 'eggs', 'lumberjack',
     72         'knights', 'ni'],
     73        'spam', 'eggs', 'lumberjack', 'knights',
     74        'ni']
     75       >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
     76       ... ('parrot', ('fresh fruit',))))))))
     77       >>> pp = pprint.PrettyPrinter(depth=6)
     78       >>> pp.pprint(tup)
     79       ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
     80 
     81 
     82 The :mod:`pprint` module also provides several shortcut functions:
     83 
     84 .. function:: pformat(object, indent=1, width=80, depth=None, *, compact=False)
     85 
     86    Return the formatted representation of *object* as a string.  *indent*,
     87    *width*, *depth* and *compact* will be passed to the :class:`PrettyPrinter`
     88    constructor as formatting parameters.
     89 
     90    .. versionchanged:: 3.4
     91       Added the *compact* parameter.
     92 
     93 
     94 .. function:: pprint(object, stream=None, indent=1, width=80, depth=None, *, \
     95                      compact=False)
     96 
     97    Prints the formatted representation of *object* on *stream*, followed by a
     98    newline.  If *stream* is ``None``, ``sys.stdout`` is used.  This may be used
     99    in the interactive interpreter instead of the :func:`print` function for
    100    inspecting values (you can even reassign ``print = pprint.pprint`` for use
    101    within a scope).  *indent*, *width*, *depth* and *compact* will be passed
    102    to the :class:`PrettyPrinter` constructor as formatting parameters.
    103 
    104    .. versionchanged:: 3.4
    105       Added the *compact* parameter.
    106 
    107       >>> import pprint
    108       >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
    109       >>> stuff.insert(0, stuff)
    110       >>> pprint.pprint(stuff)
    111       [<Recursion on list with id=...>,
    112        'spam',
    113        'eggs',
    114        'lumberjack',
    115        'knights',
    116        'ni']
    117 
    118 
    119 .. function:: isreadable(object)
    120 
    121    .. index:: builtin: eval
    122 
    123    Determine if the formatted representation of *object* is "readable," or can be
    124    used to reconstruct the value using :func:`eval`.  This always returns ``False``
    125    for recursive objects.
    126 
    127       >>> pprint.isreadable(stuff)
    128       False
    129 
    130 
    131 .. function:: isrecursive(object)
    132 
    133    Determine if *object* requires a recursive representation.
    134 
    135 
    136 One more support function is also defined:
    137 
    138 .. function:: saferepr(object)
    139 
    140    Return a string representation of *object*, protected against recursive data
    141    structures.  If the representation of *object* exposes a recursive entry, the
    142    recursive reference will be represented as ``<Recursion on typename with
    143    id=number>``.  The representation is not otherwise formatted.
    144 
    145    >>> pprint.saferepr(stuff)
    146    "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
    147 
    148 
    149 .. _prettyprinter-objects:
    150 
    151 PrettyPrinter Objects
    152 ---------------------
    153 
    154 :class:`PrettyPrinter` instances have the following methods:
    155 
    156 
    157 .. method:: PrettyPrinter.pformat(object)
    158 
    159    Return the formatted representation of *object*.  This takes into account the
    160    options passed to the :class:`PrettyPrinter` constructor.
    161 
    162 
    163 .. method:: PrettyPrinter.pprint(object)
    164 
    165    Print the formatted representation of *object* on the configured stream,
    166    followed by a newline.
    167 
    168 The following methods provide the implementations for the corresponding
    169 functions of the same names.  Using these methods on an instance is slightly
    170 more efficient since new :class:`PrettyPrinter` objects don't need to be
    171 created.
    172 
    173 
    174 .. method:: PrettyPrinter.isreadable(object)
    175 
    176    .. index:: builtin: eval
    177 
    178    Determine if the formatted representation of the object is "readable," or can be
    179    used to reconstruct the value using :func:`eval`.  Note that this returns
    180    ``False`` for recursive objects.  If the *depth* parameter of the
    181    :class:`PrettyPrinter` is set and the object is deeper than allowed, this
    182    returns ``False``.
    183 
    184 
    185 .. method:: PrettyPrinter.isrecursive(object)
    186 
    187    Determine if the object requires a recursive representation.
    188 
    189 This method is provided as a hook to allow subclasses to modify the way objects
    190 are converted to strings.  The default implementation uses the internals of the
    191 :func:`saferepr` implementation.
    192 
    193 
    194 .. method:: PrettyPrinter.format(object, context, maxlevels, level)
    195 
    196    Returns three values: the formatted version of *object* as a string, a flag
    197    indicating whether the result is readable, and a flag indicating whether
    198    recursion was detected.  The first argument is the object to be presented.  The
    199    second is a dictionary which contains the :func:`id` of objects that are part of
    200    the current presentation context (direct and indirect containers for *object*
    201    that are affecting the presentation) as the keys; if an object needs to be
    202    presented which is already represented in *context*, the third return value
    203    should be ``True``.  Recursive calls to the :meth:`.format` method should add
    204    additional entries for containers to this dictionary.  The third argument,
    205    *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there
    206    is no requested limit.  This argument should be passed unmodified to recursive
    207    calls. The fourth argument, *level*, gives the current level; recursive calls
    208    should be passed a value less than that of the current call.
    209 
    210 
    211 .. _pprint-example:
    212 
    213 Example
    214 -------
    215 
    216 To demonstrate several uses of the :func:`pprint` function and its parameters,
    217 let's fetch information about a project from `PyPI <https://pypi.org>`_::
    218 
    219    >>> import json
    220    >>> import pprint
    221    >>> from urllib.request import urlopen
    222    >>> with urlopen('https://pypi.org/pypi/sampleproject/json') as resp:
    223    ...     project_info = json.load(resp)['info']
    224 
    225 In its basic form, :func:`pprint` shows the whole object::
    226 
    227    >>> pprint.pprint(project_info)
    228    {'author': 'The Python Packaging Authority',
    229     'author_email': 'pypa-dev (a] googlegroups.com',
    230     'bugtrack_url': None,
    231     'classifiers': ['Development Status :: 3 - Alpha',
    232                     'Intended Audience :: Developers',
    233                     'License :: OSI Approved :: MIT License',
    234                     'Programming Language :: Python :: 2',
    235                     'Programming Language :: Python :: 2.6',
    236                     'Programming Language :: Python :: 2.7',
    237                     'Programming Language :: Python :: 3',
    238                     'Programming Language :: Python :: 3.2',
    239                     'Programming Language :: Python :: 3.3',
    240                     'Programming Language :: Python :: 3.4',
    241                     'Topic :: Software Development :: Build Tools'],
    242     'description': 'A sample Python project\n'
    243                    '=======================\n'
    244                    '\n'
    245                    'This is the description file for the project.\n'
    246                    '\n'
    247                    'The file should use UTF-8 encoding and be written using '
    248                    'ReStructured Text. It\n'
    249                    'will be used to generate the project webpage on PyPI, and '
    250                    'should be written for\n'
    251                    'that purpose.\n'
    252                    '\n'
    253                    'Typical contents for this file would include an overview of '
    254                    'the project, basic\n'
    255                    'usage examples, etc. Generally, including the project '
    256                    'changelog in here is not\n'
    257                    'a good idea, although a simple "What\'s New" section for the '
    258                    'most recent version\n'
    259                    'may be appropriate.',
    260     'description_content_type': None,
    261     'docs_url': None,
    262     'download_url': 'UNKNOWN',
    263     'downloads': {'last_day': -1, 'last_month': -1, 'last_week': -1},
    264     'home_page': 'https://github.com/pypa/sampleproject',
    265     'keywords': 'sample setuptools development',
    266     'license': 'MIT',
    267     'maintainer': None,
    268     'maintainer_email': None,
    269     'name': 'sampleproject',
    270     'package_url': 'https://pypi.org/project/sampleproject/',
    271     'platform': 'UNKNOWN',
    272     'project_url': 'https://pypi.org/project/sampleproject/',
    273     'project_urls': {'Download': 'UNKNOWN',
    274                      'Homepage': 'https://github.com/pypa/sampleproject'},
    275     'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
    276     'requires_dist': None,
    277     'requires_python': None,
    278     'summary': 'A sample Python project',
    279     'version': '1.2.0'}
    280 
    281 The result can be limited to a certain *depth* (ellipsis is used for deeper
    282 contents)::
    283 
    284    >>> pprint.pprint(project_info, depth=1)
    285    {'author': 'The Python Packaging Authority',
    286     'author_email': 'pypa-dev (a] googlegroups.com',
    287     'bugtrack_url': None,
    288     'classifiers': [...],
    289     'description': 'A sample Python project\n'
    290                    '=======================\n'
    291                    '\n'
    292                    'This is the description file for the project.\n'
    293                    '\n'
    294                    'The file should use UTF-8 encoding and be written using '
    295                    'ReStructured Text. It\n'
    296                    'will be used to generate the project webpage on PyPI, and '
    297                    'should be written for\n'
    298                    'that purpose.\n'
    299                    '\n'
    300                    'Typical contents for this file would include an overview of '
    301                    'the project, basic\n'
    302                    'usage examples, etc. Generally, including the project '
    303                    'changelog in here is not\n'
    304                    'a good idea, although a simple "What\'s New" section for the '
    305                    'most recent version\n'
    306                    'may be appropriate.',
    307     'description_content_type': None,
    308     'docs_url': None,
    309     'download_url': 'UNKNOWN',
    310     'downloads': {...},
    311     'home_page': 'https://github.com/pypa/sampleproject',
    312     'keywords': 'sample setuptools development',
    313     'license': 'MIT',
    314     'maintainer': None,
    315     'maintainer_email': None,
    316     'name': 'sampleproject',
    317     'package_url': 'https://pypi.org/project/sampleproject/',
    318     'platform': 'UNKNOWN',
    319     'project_url': 'https://pypi.org/project/sampleproject/',
    320     'project_urls': {...},
    321     'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
    322     'requires_dist': None,
    323     'requires_python': None,
    324     'summary': 'A sample Python project',
    325     'version': '1.2.0'}
    326 
    327 Additionally, maximum character *width* can be suggested. If a long object
    328 cannot be split, the specified width will be exceeded::
    329 
    330    >>> pprint.pprint(project_info, depth=1, width=60)
    331    {'author': 'The Python Packaging Authority',
    332     'author_email': 'pypa-dev (a] googlegroups.com',
    333     'bugtrack_url': None,
    334     'classifiers': [...],
    335     'description': 'A sample Python project\n'
    336                    '=======================\n'
    337                    '\n'
    338                    'This is the description file for the '
    339                    'project.\n'
    340                    '\n'
    341                    'The file should use UTF-8 encoding and be '
    342                    'written using ReStructured Text. It\n'
    343                    'will be used to generate the project '
    344                    'webpage on PyPI, and should be written '
    345                    'for\n'
    346                    'that purpose.\n'
    347                    '\n'
    348                    'Typical contents for this file would '
    349                    'include an overview of the project, '
    350                    'basic\n'
    351                    'usage examples, etc. Generally, including '
    352                    'the project changelog in here is not\n'
    353                    'a good idea, although a simple "What\'s '
    354                    'New" section for the most recent version\n'
    355                    'may be appropriate.',
    356     'description_content_type': None,
    357     'docs_url': None,
    358     'download_url': 'UNKNOWN',
    359     'downloads': {...},
    360     'home_page': 'https://github.com/pypa/sampleproject',
    361     'keywords': 'sample setuptools development',
    362     'license': 'MIT',
    363     'maintainer': None,
    364     'maintainer_email': None,
    365     'name': 'sampleproject',
    366     'package_url': 'https://pypi.org/project/sampleproject/',
    367     'platform': 'UNKNOWN',
    368     'project_url': 'https://pypi.org/project/sampleproject/',
    369     'project_urls': {...},
    370     'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
    371     'requires_dist': None,
    372     'requires_python': None,
    373     'summary': 'A sample Python project',
    374     'version': '1.2.0'}
    375