Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 | |
Raymond Hettinger | 1048094 | 2011-01-10 03:26:08 +0000 | [diff] [blame] | 9 | **Source code:** :source:`Lib/pprint.py` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 10 | |
Raymond Hettinger | 4f707fd | 2011-01-10 19:54:11 +0000 | [diff] [blame] | 11 | -------------- |
| 12 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 |
Georg Brandl | 22b3431 | 2009-07-26 14:54:51 +0000 | [diff] [blame] | 18 | other built-in objects which are not representable as Python constants. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 | |
Georg Brandl | 55ac8f0 | 2007-09-01 13:51:09 +0000 | [diff] [blame] | 25 | Dictionaries are sorted by key before the display is computed. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 26 | |
| 27 | The :mod:`pprint` module defines one class: |
| 28 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 29 | .. First the implementation class: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 30 | |
| 31 | |
Georg Brandl | 1824415 | 2009-09-02 20:34:52 +0000 | [diff] [blame] | 32 | .. class:: PrettyPrinter(indent=1, width=80, depth=None, stream=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 33 | |
| 34 | Construct a :class:`PrettyPrinter` instance. This constructor understands |
| 35 | several keyword parameters. An output stream may be set using the *stream* |
| 36 | keyword; the only method used on the stream object is the file protocol's |
| 37 | :meth:`write` method. If not specified, the :class:`PrettyPrinter` adopts |
| 38 | ``sys.stdout``. Three additional parameters may be used to control the |
| 39 | formatted representation. The keywords are *indent*, *depth*, and *width*. The |
| 40 | amount of indentation added for each recursive level is specified by *indent*; |
| 41 | the default is one. Other values can cause output to look a little odd, but can |
| 42 | make nesting easier to spot. The number of levels which may be printed is |
| 43 | controlled by *depth*; if the data structure being printed is too deep, the next |
| 44 | contained level is replaced by ``...``. By default, there is no constraint on |
| 45 | the depth of the objects being formatted. The desired output width is |
| 46 | constrained using the *width* parameter; the default is 80 characters. If a |
| 47 | structure cannot be formatted within the constrained width, a best effort will |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 48 | be made. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 49 | |
Christian Heimes | b9eccbf | 2007-12-05 20:18:38 +0000 | [diff] [blame] | 50 | >>> import pprint |
| 51 | >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 52 | >>> stuff.insert(0, stuff[:]) |
| 53 | >>> pp = pprint.PrettyPrinter(indent=4) |
| 54 | >>> pp.pprint(stuff) |
Georg Brandl | 3ccb787 | 2008-07-16 03:00:45 +0000 | [diff] [blame] | 55 | [ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'], |
Christian Heimes | b9eccbf | 2007-12-05 20:18:38 +0000 | [diff] [blame] | 56 | 'spam', |
| 57 | 'eggs', |
| 58 | 'lumberjack', |
| 59 | 'knights', |
| 60 | 'ni'] |
| 61 | >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', |
| 62 | ... ('parrot', ('fresh fruit',)))))))) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 63 | >>> pp = pprint.PrettyPrinter(depth=6) |
| 64 | >>> pp.pprint(tup) |
Alexandre Vassalotti | eca20b6 | 2008-05-16 02:54:33 +0000 | [diff] [blame] | 65 | ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...))))))) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 66 | |
Georg Brandl | 1824415 | 2009-09-02 20:34:52 +0000 | [diff] [blame] | 67 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 68 | The :class:`PrettyPrinter` class supports several derivative functions: |
| 69 | |
Georg Brandl | 1824415 | 2009-09-02 20:34:52 +0000 | [diff] [blame] | 70 | .. function:: pformat(object, indent=1, width=80, depth=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 71 | |
| 72 | Return the formatted representation of *object* as a string. *indent*, *width* |
| 73 | and *depth* will be passed to the :class:`PrettyPrinter` constructor as |
| 74 | formatting parameters. |
| 75 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 76 | |
Georg Brandl | 1824415 | 2009-09-02 20:34:52 +0000 | [diff] [blame] | 77 | .. function:: pprint(object, stream=None, indent=1, width=80, depth=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 78 | |
| 79 | Prints the formatted representation of *object* on *stream*, followed by a |
Georg Brandl | 1824415 | 2009-09-02 20:34:52 +0000 | [diff] [blame] | 80 | newline. If *stream* is ``None``, ``sys.stdout`` is used. This may be used |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 81 | in the interactive interpreter instead of the :func:`print` function for |
| 82 | inspecting values (you can even reassign ``print = pprint.pprint`` for use |
| 83 | within a scope). *indent*, *width* and *depth* will be passed to the |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 84 | :class:`PrettyPrinter` constructor as formatting parameters. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 85 | |
Christian Heimes | b9eccbf | 2007-12-05 20:18:38 +0000 | [diff] [blame] | 86 | >>> import pprint |
| 87 | >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 88 | >>> stuff.insert(0, stuff) |
| 89 | >>> pprint.pprint(stuff) |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 90 | [<Recursion on list with id=...>, |
| 91 | 'spam', |
| 92 | 'eggs', |
| 93 | 'lumberjack', |
| 94 | 'knights', |
| 95 | 'ni'] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 96 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 97 | |
| 98 | .. function:: isreadable(object) |
| 99 | |
| 100 | .. index:: builtin: eval |
| 101 | |
| 102 | Determine if the formatted representation of *object* is "readable," or can be |
| 103 | used to reconstruct the value using :func:`eval`. This always returns ``False`` |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 104 | for recursive objects. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 105 | |
| 106 | >>> pprint.isreadable(stuff) |
| 107 | False |
| 108 | |
| 109 | |
| 110 | .. function:: isrecursive(object) |
| 111 | |
| 112 | Determine if *object* requires a recursive representation. |
| 113 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 114 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 115 | One more support function is also defined: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 116 | |
| 117 | .. function:: saferepr(object) |
| 118 | |
| 119 | Return a string representation of *object*, protected against recursive data |
| 120 | structures. If the representation of *object* exposes a recursive entry, the |
| 121 | recursive reference will be represented as ``<Recursion on typename with |
| 122 | id=number>``. The representation is not otherwise formatted. |
| 123 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 124 | >>> pprint.saferepr(stuff) |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 125 | "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']" |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 126 | |
| 127 | |
| 128 | .. _prettyprinter-objects: |
| 129 | |
| 130 | PrettyPrinter Objects |
| 131 | --------------------- |
| 132 | |
| 133 | :class:`PrettyPrinter` instances have the following methods: |
| 134 | |
| 135 | |
| 136 | .. method:: PrettyPrinter.pformat(object) |
| 137 | |
| 138 | Return the formatted representation of *object*. This takes into account the |
| 139 | options passed to the :class:`PrettyPrinter` constructor. |
| 140 | |
| 141 | |
| 142 | .. method:: PrettyPrinter.pprint(object) |
| 143 | |
| 144 | Print the formatted representation of *object* on the configured stream, |
| 145 | followed by a newline. |
| 146 | |
| 147 | The following methods provide the implementations for the corresponding |
| 148 | functions of the same names. Using these methods on an instance is slightly |
| 149 | more efficient since new :class:`PrettyPrinter` objects don't need to be |
| 150 | created. |
| 151 | |
| 152 | |
| 153 | .. method:: PrettyPrinter.isreadable(object) |
| 154 | |
| 155 | .. index:: builtin: eval |
| 156 | |
| 157 | Determine if the formatted representation of the object is "readable," or can be |
| 158 | used to reconstruct the value using :func:`eval`. Note that this returns |
| 159 | ``False`` for recursive objects. If the *depth* parameter of the |
| 160 | :class:`PrettyPrinter` is set and the object is deeper than allowed, this |
| 161 | returns ``False``. |
| 162 | |
| 163 | |
| 164 | .. method:: PrettyPrinter.isrecursive(object) |
| 165 | |
| 166 | Determine if the object requires a recursive representation. |
| 167 | |
| 168 | This method is provided as a hook to allow subclasses to modify the way objects |
| 169 | are converted to strings. The default implementation uses the internals of the |
| 170 | :func:`saferepr` implementation. |
| 171 | |
| 172 | |
| 173 | .. method:: PrettyPrinter.format(object, context, maxlevels, level) |
| 174 | |
| 175 | Returns three values: the formatted version of *object* as a string, a flag |
| 176 | indicating whether the result is readable, and a flag indicating whether |
| 177 | recursion was detected. The first argument is the object to be presented. The |
| 178 | second is a dictionary which contains the :func:`id` of objects that are part of |
| 179 | the current presentation context (direct and indirect containers for *object* |
| 180 | that are affecting the presentation) as the keys; if an object needs to be |
| 181 | presented which is already represented in *context*, the third return value |
| 182 | should be ``True``. Recursive calls to the :meth:`format` method should add |
| 183 | additional entries for containers to this dictionary. The third argument, |
| 184 | *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there |
| 185 | is no requested limit. This argument should be passed unmodified to recursive |
| 186 | calls. The fourth argument, *level*, gives the current level; recursive calls |
| 187 | should be passed a value less than that of the current call. |
Christian Heimes | b9eccbf | 2007-12-05 20:18:38 +0000 | [diff] [blame] | 188 | |
| 189 | |
| 190 | .. _pprint-example: |
| 191 | |
Łukasz Langa | 4ad78ab | 2011-05-14 22:43:44 +0200 | [diff] [blame] | 192 | Example |
| 193 | ------- |
Christian Heimes | b9eccbf | 2007-12-05 20:18:38 +0000 | [diff] [blame] | 194 | |
Łukasz Langa | 4ad78ab | 2011-05-14 22:43:44 +0200 | [diff] [blame] | 195 | To demonstrate several uses of the :func:`pprint` function and its parameters, |
| 196 | let's fetch information about a package from PyPI:: |
Christian Heimes | b9eccbf | 2007-12-05 20:18:38 +0000 | [diff] [blame] | 197 | |
Łukasz Langa | 4ad78ab | 2011-05-14 22:43:44 +0200 | [diff] [blame] | 198 | >>> import json |
Christian Heimes | b9eccbf | 2007-12-05 20:18:38 +0000 | [diff] [blame] | 199 | >>> import pprint |
Łukasz Langa | 4ad78ab | 2011-05-14 22:43:44 +0200 | [diff] [blame] | 200 | >>> from urllib.request import urlopen |
| 201 | >>> with urlopen('http://pypi.python.org/pypi/configparser/json') as url: |
| 202 | ... http_info = url.info() |
| 203 | ... raw_data = url.read().decode(http_info.get_content_charset()) |
| 204 | >>> package_data = json.loads(raw_data) |
| 205 | >>> result = {'headers': http_info.items(), 'body': package_data} |
Christian Heimes | b9eccbf | 2007-12-05 20:18:38 +0000 | [diff] [blame] | 206 | |
Łukasz Langa | 4ad78ab | 2011-05-14 22:43:44 +0200 | [diff] [blame] | 207 | In its basic form, :func:`pprint` shows the whole object:: |
| 208 | |
| 209 | >>> pprint.pprint(result) |
| 210 | {'body': {'info': {'_pypi_hidden': False, |
| 211 | '_pypi_ordering': 12, |
| 212 | 'classifiers': ['Development Status :: 4 - Beta', |
| 213 | 'Intended Audience :: Developers', |
| 214 | 'License :: OSI Approved :: MIT License', |
| 215 | 'Natural Language :: English', |
| 216 | 'Operating System :: OS Independent', |
| 217 | 'Programming Language :: Python', |
| 218 | 'Programming Language :: Python :: 2', |
| 219 | 'Programming Language :: Python :: 2.6', |
| 220 | 'Programming Language :: Python :: 2.7', |
| 221 | 'Topic :: Software Development :: Libraries', |
| 222 | 'Topic :: Software Development :: Libraries :: Python Modules'], |
| 223 | 'download_url': 'UNKNOWN', |
| 224 | 'home_page': 'http://docs.python.org/py3k/library/configparser.html', |
| 225 | 'keywords': 'configparser ini parsing conf cfg configuration file', |
| 226 | 'license': 'MIT', |
| 227 | 'name': 'configparser', |
| 228 | 'package_url': 'http://pypi.python.org/pypi/configparser', |
| 229 | 'platform': 'any', |
| 230 | 'release_url': 'http://pypi.python.org/pypi/configparser/3.2.0r3', |
| 231 | 'requires_python': None, |
| 232 | 'stable_version': None, |
| 233 | 'summary': 'This library brings the updated configparser from Python 3.2+ to Python 2.6-2.7.', |
| 234 | 'version': '3.2.0r3'}, |
| 235 | 'urls': [{'comment_text': '', |
| 236 | 'downloads': 47, |
| 237 | 'filename': 'configparser-3.2.0r3.tar.gz', |
| 238 | 'has_sig': False, |
| 239 | 'md5_digest': '8500fd87c61ac0de328fc996fce69b96', |
| 240 | 'packagetype': 'sdist', |
| 241 | 'python_version': 'source', |
| 242 | 'size': 32281, |
| 243 | 'upload_time': '2011-05-10T16:28:50', |
| 244 | 'url': 'http://pypi.python.org/packages/source/c/configparser/configparser-3.2.0r3.tar.gz'}]}, |
| 245 | 'headers': [('Date', 'Sat, 14 May 2011 12:48:52 GMT'), |
| 246 | ('Server', 'Apache/2.2.16 (Debian)'), |
| 247 | ('Content-Disposition', 'inline'), |
| 248 | ('Connection', 'close'), |
| 249 | ('Transfer-Encoding', 'chunked'), |
| 250 | ('Content-Type', 'application/json; charset="UTF-8"')]} |
| 251 | |
| 252 | The result can be limited to a certain *depth* (ellipsis is used for deeper |
| 253 | contents):: |
| 254 | |
| 255 | >>> pprint.pprint(result, depth=3) |
| 256 | {'body': {'info': {'_pypi_hidden': False, |
| 257 | '_pypi_ordering': 12, |
| 258 | 'classifiers': [...], |
| 259 | 'download_url': 'UNKNOWN', |
| 260 | 'home_page': 'http://docs.python.org/py3k/library/configparser.html', |
| 261 | 'keywords': 'configparser ini parsing conf cfg configuration file', |
| 262 | 'license': 'MIT', |
| 263 | 'name': 'configparser', |
| 264 | 'package_url': 'http://pypi.python.org/pypi/configparser', |
| 265 | 'platform': 'any', |
| 266 | 'release_url': 'http://pypi.python.org/pypi/configparser/3.2.0r3', |
| 267 | 'requires_python': None, |
| 268 | 'stable_version': None, |
| 269 | 'summary': 'This library brings the updated configparser from Python 3.2+ to Python 2.6-2.7.', |
| 270 | 'version': '3.2.0r3'}, |
| 271 | 'urls': [{...}]}, |
| 272 | 'headers': [('Date', 'Sat, 14 May 2011 12:48:52 GMT'), |
| 273 | ('Server', 'Apache/2.2.16 (Debian)'), |
| 274 | ('Content-Disposition', 'inline'), |
| 275 | ('Connection', 'close'), |
| 276 | ('Transfer-Encoding', 'chunked'), |
| 277 | ('Content-Type', 'application/json; charset="UTF-8"')]} |
| 278 | |
| 279 | Additionally, maximum *width* can be suggested. If a long object cannot be |
| 280 | split, the specified width will be exceeded:: |
| 281 | |
| 282 | >>> pprint.pprint(result['headers'], width=30) |
| 283 | [('Date', |
| 284 | 'Sat, 14 May 2011 12:48:52 GMT'), |
| 285 | ('Server', |
| 286 | 'Apache/2.2.16 (Debian)'), |
| 287 | ('Content-Disposition', |
| 288 | 'inline'), |
| 289 | ('Connection', 'close'), |
| 290 | ('Transfer-Encoding', |
| 291 | 'chunked'), |
| 292 | ('Content-Type', |
| 293 | 'application/json; charset="UTF-8"')] |