| 1 |
:mod:`!pprint` --- Data pretty printer |
| 2 |
====================================== |
| 3 |
|
| 4 |
.. module:: pprint |
| 5 |
:synopsis: Data pretty printer. |
| 6 |
|
| 7 |
.. moduleauthor:: Fred L. Drake, Jr. <[email protected]> |
| 8 |
.. sectionauthor:: Fred L. Drake, Jr. <[email protected]> |
| 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 |
adjustable by the *width* parameter defaulting to 80 characters. |
| 24 |
|
| 25 |
.. versionchanged:: 3.9 |
| 26 |
Added support for pretty-printing :class:`types.SimpleNamespace`. |
| 27 |
|
| 28 |
.. versionchanged:: 3.10 |
| 29 |
Added support for pretty-printing :class:`dataclasses.dataclass`. |
| 30 |
|
| 31 |
.. _pprint-functions: |
| 32 |
|
| 33 |
Functions |
| 34 |
--------- |
| 35 |
|
| 36 |
.. function:: pp(object, stream=None, indent=1, width=80, depth=None, *, \ |
| 37 |
compact=False, sort_dicts=False, underscore_numbers=False) |
| 38 |
|
| 39 |
Prints the formatted representation of *object*, followed by a newline. |
| 40 |
This function may be used in the interactive interpreter |
| 41 |
instead of the :func:`print` function for inspecting values. |
| 42 |
Tip: you can reassign ``print = pprint.pp`` for use within a scope. |
| 43 |
|
| 44 |
:param object: |
| 45 |
The object to be printed. |
| 46 |
|
| 47 |
:param stream: |
| 48 |
A file-like object to which the output will be written |
| 49 |
by calling its :meth:`!write` method. |
| 50 |
If ``None`` (the default), :data:`sys.stdout` is used. |
| 51 |
:type stream: :term:`file-like object` | None |
| 52 |
|
| 53 |
:param int indent: |
| 54 |
The amount of indentation added for each nesting level. |
| 55 |
|
| 56 |
:param int width: |
| 57 |
The desired maximum number of characters per line in the output. |
| 58 |
If a structure cannot be formatted within the width constraint, |
| 59 |
a best effort will be made. |
| 60 |
|
| 61 |
:param depth: |
| 62 |
The number of nesting levels which may be printed. |
| 63 |
If the data structure being printed is too deep, |
| 64 |
the next contained level is replaced by ``...``. |
| 65 |
If ``None`` (the default), there is no constraint |
| 66 |
on the depth of the objects being formatted. |
| 67 |
:type depth: int | None |
| 68 |
|
| 69 |
:param bool compact: |
| 70 |
Control the way long :term:`sequences <sequence>` are formatted. |
| 71 |
If ``False`` (the default), |
| 72 |
each item of a sequence will be formatted on a separate line, |
| 73 |
otherwise as many items as will fit within the *width* |
| 74 |
will be formatted on each output line. |
| 75 |
|
| 76 |
:param bool sort_dicts: |
| 77 |
If ``True``, dictionaries will be formatted with |
| 78 |
their keys sorted, otherwise |
| 79 |
they will be displayed in insertion order (the default). |
| 80 |
|
| 81 |
:param bool underscore_numbers: |
| 82 |
If ``True``, |
| 83 |
integers will be formatted with the ``_`` character for a thousands separator, |
| 84 |
otherwise underscores are not displayed (the default). |
| 85 |
|
| 86 |
>>> import pprint |
| 87 |
>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] |
| 88 |
>>> stuff.insert(0, stuff) |
| 89 |
>>> pprint.pp(stuff) |
| 90 |
[<Recursion on list with id=...>, |
| 91 |
'spam', |
| 92 |
'eggs', |
| 93 |
'lumberjack', |
| 94 |
'knights', |
| 95 |
'ni'] |
| 96 |
|
| 97 |
.. versionadded:: 3.8 |
| 98 |
|
| 99 |
|
| 100 |
.. function:: pprint(object, stream=None, indent=1, width=80, depth=None, *, \ |
| 101 |
compact=False, sort_dicts=True, underscore_numbers=False) |
| 102 |
|
| 103 |
Alias for :func:`~pprint.pp` with *sort_dicts* set to ``True`` by default, |
| 104 |
which would automatically sort the dictionaries' keys, |
| 105 |
you might want to use :func:`~pprint.pp` instead where it is ``False`` by default. |
| 106 |
|
| 107 |
|
| 108 |
.. function:: pformat(object, indent=1, width=80, depth=None, *, \ |
| 109 |
compact=False, sort_dicts=True, underscore_numbers=False) |
| 110 |
|
| 111 |
Return the formatted representation of *object* as a string. *indent*, |
| 112 |
*width*, *depth*, *compact*, *sort_dicts* and *underscore_numbers* are |
| 113 |
passed to the :class:`PrettyPrinter` constructor as formatting parameters |
| 114 |
and their meanings are as described in the documentation above. |
| 115 |
|
| 116 |
|
| 117 |
.. function:: isreadable(object) |
| 118 |
|
| 119 |
.. index:: pair: built-in function; eval |
| 120 |
|
| 121 |
Determine if the formatted representation of *object* is "readable", or can be |
| 122 |
used to reconstruct the value using :func:`eval`. This always returns ``False`` |
| 123 |
for recursive objects. |
| 124 |
|
| 125 |
>>> pprint.isreadable(stuff) |
| 126 |
False |
| 127 |
|
| 128 |
|
| 129 |
.. function:: isrecursive(object) |
| 130 |
|
| 131 |
Determine if *object* requires a recursive representation. This function is |
| 132 |
subject to the same limitations as noted in :func:`saferepr` below and may raise an |
| 133 |
:exc:`RecursionError` if it fails to detect a recursive object. |
| 134 |
|
| 135 |
|
| 136 |
.. function:: saferepr(object) |
| 137 |
|
| 138 |
Return a string representation of *object*, protected against recursion in |
| 139 |
some common data structures, namely instances of :class:`dict`, :class:`list` |
| 140 |
and :class:`tuple` or subclasses whose ``__repr__`` has not been overridden. If the |
| 141 |
representation of object exposes a recursive entry, the recursive reference |
| 142 |
will be represented as ``<Recursion on typename with id=number>``. The |
| 143 |
representation is not otherwise formatted. |
| 144 |
|
| 145 |
>>> pprint.saferepr(stuff) |
| 146 |
"[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']" |
| 147 |
|
| 148 |
.. _prettyprinter-objects: |
| 149 |
|
| 150 |
PrettyPrinter Objects |
| 151 |
--------------------- |
| 152 |
|
| 153 |
.. index:: single: ...; placeholder |
| 154 |
|
| 155 |
.. class:: PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, \ |
| 156 |
compact=False, sort_dicts=True, underscore_numbers=False) |
| 157 |
|
| 158 |
Construct a :class:`PrettyPrinter` instance. |
| 159 |
|
| 160 |
Arguments have the same meaning as for :func:`~pprint.pp`. |
| 161 |
Note that they are in a different order, and that *sort_dicts* defaults to ``True``. |
| 162 |
|
| 163 |
>>> import pprint |
| 164 |
>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] |
| 165 |
>>> stuff.insert(0, stuff[:]) |
| 166 |
>>> pp = pprint.PrettyPrinter(indent=4) |
| 167 |
>>> pp.pprint(stuff) |
| 168 |
[ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'], |
| 169 |
'spam', |
| 170 |
'eggs', |
| 171 |
'lumberjack', |
| 172 |
'knights', |
| 173 |
'ni'] |
| 174 |
>>> pp = pprint.PrettyPrinter(width=41, compact=True) |
| 175 |
>>> pp.pprint(stuff) |
| 176 |
[['spam', 'eggs', 'lumberjack', |
| 177 |
'knights', 'ni'], |
| 178 |
'spam', 'eggs', 'lumberjack', 'knights', |
| 179 |
'ni'] |
| 180 |
>>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', |
| 181 |
... ('parrot', ('fresh fruit',)))))))) |
| 182 |
>>> pp = pprint.PrettyPrinter(depth=6) |
| 183 |
>>> pp.pprint(tup) |
| 184 |
('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...))))))) |
| 185 |
|
| 186 |
|
| 187 |
.. versionchanged:: 3.4 |
| 188 |
Added the *compact* parameter. |
| 189 |
|
| 190 |
.. versionchanged:: 3.8 |
| 191 |
Added the *sort_dicts* parameter. |
| 192 |
|
| 193 |
.. versionchanged:: 3.10 |
| 194 |
Added the *underscore_numbers* parameter. |
| 195 |
|
| 196 |
.. versionchanged:: 3.11 |
| 197 |
No longer attempts to write to :data:`!sys.stdout` if it is ``None``. |
| 198 |
|
| 199 |
|
| 200 |
:class:`PrettyPrinter` instances have the following methods: |
| 201 |
|
| 202 |
|
| 203 |
.. method:: PrettyPrinter.pformat(object) |
| 204 |
|
| 205 |
Return the formatted representation of *object*. This takes into account the |
| 206 |
options passed to the :class:`PrettyPrinter` constructor. |
| 207 |
|
| 208 |
|
| 209 |
.. method:: PrettyPrinter.pprint(object) |
| 210 |
|
| 211 |
Print the formatted representation of *object* on the configured stream, |
| 212 |
followed by a newline. |
| 213 |
|
| 214 |
The following methods provide the implementations for the corresponding |
| 215 |
functions of the same names. Using these methods on an instance is slightly |
| 216 |
more efficient since new :class:`PrettyPrinter` objects don't need to be |
| 217 |
created. |
| 218 |
|
| 219 |
|
| 220 |
.. method:: PrettyPrinter.isreadable(object) |
| 221 |
|
| 222 |
.. index:: pair: built-in function; eval |
| 223 |
|
| 224 |
Determine if the formatted representation of the object is "readable," or can be |
| 225 |
used to reconstruct the value using :func:`eval`. Note that this returns |
| 226 |
``False`` for recursive objects. If the *depth* parameter of the |
| 227 |
:class:`PrettyPrinter` is set and the object is deeper than allowed, this |
| 228 |
returns ``False``. |
| 229 |
|
| 230 |
|
| 231 |
.. method:: PrettyPrinter.isrecursive(object) |
| 232 |
|
| 233 |
Determine if the object requires a recursive representation. |
| 234 |
|
| 235 |
This method is provided as a hook to allow subclasses to modify the way objects |
| 236 |
are converted to strings. The default implementation uses the internals of the |
| 237 |
:func:`saferepr` implementation. |
| 238 |
|
| 239 |
|
| 240 |
.. method:: PrettyPrinter.format(object, context, maxlevels, level) |
| 241 |
|
| 242 |
Returns three values: the formatted version of *object* as a string, a flag |
| 243 |
indicating whether the result is readable, and a flag indicating whether |
| 244 |
recursion was detected. The first argument is the object to be presented. The |
| 245 |
second is a dictionary which contains the :func:`id` of objects that are part of |
| 246 |
the current presentation context (direct and indirect containers for *object* |
| 247 |
that are affecting the presentation) as the keys; if an object needs to be |
| 248 |
presented which is already represented in *context*, the third return value |
| 249 |
should be ``True``. Recursive calls to the :meth:`.format` method should add |
| 250 |
additional entries for containers to this dictionary. The third argument, |
| 251 |
*maxlevels*, gives the requested limit to recursion; this will be ``0`` if there |
| 252 |
is no requested limit. This argument should be passed unmodified to recursive |
| 253 |
calls. The fourth argument, *level*, gives the current level; recursive calls |
| 254 |
should be passed a value less than that of the current call. |
| 255 |
|
| 256 |
|
| 257 |
.. _pprint-example: |
| 258 |
|
| 259 |
Example |
| 260 |
------- |
| 261 |
|
| 262 |
To demonstrate several uses of the :func:`~pprint.pp` function and its parameters, |
| 263 |
let's fetch information about a project from `PyPI <https://pypi.org>`_:: |
| 264 |
|
| 265 |
>>> import json |
| 266 |
>>> import pprint |
| 267 |
>>> from urllib.request import urlopen |
| 268 |
>>> with urlopen('https://pypi.org/pypi/sampleproject/1.2.0/json') as resp: |
| 269 |
... project_info = json.load(resp)['info'] |
| 270 |
|
| 271 |
In its basic form, :func:`~pprint.pp` shows the whole object:: |
| 272 |
|
| 273 |
>>> pprint.pp(project_info) |
| 274 |
{'author': 'The Python Packaging Authority', |
| 275 |
'author_email': '[email protected]', |
| 276 |
'bugtrack_url': None, |
| 277 |
'classifiers': ['Development Status :: 3 - Alpha', |
| 278 |
'Intended Audience :: Developers', |
| 279 |
'License :: OSI Approved :: MIT License', |
| 280 |
'Programming Language :: Python :: 2', |
| 281 |
'Programming Language :: Python :: 2.6', |
| 282 |
'Programming Language :: Python :: 2.7', |
| 283 |
'Programming Language :: Python :: 3', |
| 284 |
'Programming Language :: Python :: 3.2', |
| 285 |
'Programming Language :: Python :: 3.3', |
| 286 |
'Programming Language :: Python :: 3.4', |
| 287 |
'Topic :: Software Development :: Build Tools'], |
| 288 |
'description': 'A sample Python project\n' |
| 289 |
'=======================\n' |
| 290 |
'\n' |
| 291 |
'This is the description file for the project.\n' |
| 292 |
'\n' |
| 293 |
'The file should use UTF-8 encoding and be written using ' |
| 294 |
'ReStructured Text. It\n' |
| 295 |
'will be used to generate the project webpage on PyPI, and ' |
| 296 |
'should be written for\n' |
| 297 |
'that purpose.\n' |
| 298 |
'\n' |
| 299 |
'Typical contents for this file would include an overview of ' |
| 300 |
'the project, basic\n' |
| 301 |
'usage examples, etc. Generally, including the project ' |
| 302 |
'changelog in here is not\n' |
| 303 |
'a good idea, although a simple "What\'s New" section for the ' |
| 304 |
'most recent version\n' |
| 305 |
'may be appropriate.', |
| 306 |
'description_content_type': None, |
| 307 |
'docs_url': None, |
| 308 |
'download_url': 'UNKNOWN', |
| 309 |
'downloads': {'last_day': -1, 'last_month': -1, 'last_week': -1}, |
| 310 |
'home_page': 'https://github.com/pypa/sampleproject', |
| 311 |
'keywords': 'sample setuptools development', |
| 312 |
'license': 'MIT', |
| 313 |
'maintainer': None, |
| 314 |
'maintainer_email': None, |
| 315 |
'name': 'sampleproject', |
| 316 |
'package_url': 'https://pypi.org/project/sampleproject/', |
| 317 |
'platform': 'UNKNOWN', |
| 318 |
'project_url': 'https://pypi.org/project/sampleproject/', |
| 319 |
'project_urls': {'Download': 'UNKNOWN', |
| 320 |
'Homepage': 'https://github.com/pypa/sampleproject'}, |
| 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 |
The result can be limited to a certain *depth* (ellipsis is used for deeper |
| 328 |
contents):: |
| 329 |
|
| 330 |
>>> pprint.pp(project_info, depth=1) |
| 331 |
{'author': 'The Python Packaging Authority', |
| 332 |
'author_email': '[email protected]', |
| 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 project.\n' |
| 339 |
'\n' |
| 340 |
'The file should use UTF-8 encoding and be written using ' |
| 341 |
'ReStructured Text. It\n' |
| 342 |
'will be used to generate the project webpage on PyPI, and ' |
| 343 |
'should be written for\n' |
| 344 |
'that purpose.\n' |
| 345 |
'\n' |
| 346 |
'Typical contents for this file would include an overview of ' |
| 347 |
'the project, basic\n' |
| 348 |
'usage examples, etc. Generally, including the project ' |
| 349 |
'changelog in here is not\n' |
| 350 |
'a good idea, although a simple "What\'s New" section for the ' |
| 351 |
'most recent version\n' |
| 352 |
'may be appropriate.', |
| 353 |
'description_content_type': None, |
| 354 |
'docs_url': None, |
| 355 |
'download_url': 'UNKNOWN', |
| 356 |
'downloads': {...}, |
| 357 |
'home_page': 'https://github.com/pypa/sampleproject', |
| 358 |
'keywords': 'sample setuptools development', |
| 359 |
'license': 'MIT', |
| 360 |
'maintainer': None, |
| 361 |
'maintainer_email': None, |
| 362 |
'name': 'sampleproject', |
| 363 |
'package_url': 'https://pypi.org/project/sampleproject/', |
| 364 |
'platform': 'UNKNOWN', |
| 365 |
'project_url': 'https://pypi.org/project/sampleproject/', |
| 366 |
'project_urls': {...}, |
| 367 |
'release_url': 'https://pypi.org/project/sampleproject/1.2.0/', |
| 368 |
'requires_dist': None, |
| 369 |
'requires_python': None, |
| 370 |
'summary': 'A sample Python project', |
| 371 |
'version': '1.2.0'} |
| 372 |
|
| 373 |
Additionally, maximum character *width* can be suggested. If a long object |
| 374 |
cannot be split, the specified width will be exceeded:: |
| 375 |
|
| 376 |
>>> pprint.pp(project_info, depth=1, width=60) |
| 377 |
{'author': 'The Python Packaging Authority', |
| 378 |
'author_email': '[email protected]', |
| 379 |
'bugtrack_url': None, |
| 380 |
'classifiers': [...], |
| 381 |
'description': 'A sample Python project\n' |
| 382 |
'=======================\n' |
| 383 |
'\n' |
| 384 |
'This is the description file for the ' |
| 385 |
'project.\n' |
| 386 |
'\n' |
| 387 |
'The file should use UTF-8 encoding and be ' |
| 388 |
'written using ReStructured Text. It\n' |
| 389 |
'will be used to generate the project ' |
| 390 |
'webpage on PyPI, and should be written ' |
| 391 |
'for\n' |
| 392 |
'that purpose.\n' |
| 393 |
'\n' |
| 394 |
'Typical contents for this file would ' |
| 395 |
'include an overview of the project, ' |
| 396 |
'basic\n' |
| 397 |
'usage examples, etc. Generally, including ' |
| 398 |
'the project changelog in here is not\n' |
| 399 |
'a good idea, although a simple "What\'s ' |
| 400 |
'New" section for the most recent version\n' |
| 401 |
'may be appropriate.', |
| 402 |
'description_content_type': None, |
| 403 |
'docs_url': None, |
| 404 |
'download_url': 'UNKNOWN', |
| 405 |
'downloads': {...}, |
| 406 |
'home_page': 'https://github.com/pypa/sampleproject', |
| 407 |
'keywords': 'sample setuptools development', |
| 408 |
'license': 'MIT', |
| 409 |
'maintainer': None, |
| 410 |
'maintainer_email': None, |
| 411 |
'name': 'sampleproject', |
| 412 |
'package_url': 'https://pypi.org/project/sampleproject/', |
| 413 |
'platform': 'UNKNOWN', |
| 414 |
'project_url': 'https://pypi.org/project/sampleproject/', |
| 415 |
'project_urls': {...}, |
| 416 |
'release_url': 'https://pypi.org/project/sampleproject/1.2.0/', |
| 417 |
'requires_dist': None, |
| 418 |
'requires_python': None, |
| 419 |
'summary': 'A sample Python project', |
| 420 |
'version': '1.2.0'} |