/Doc/library/pprint.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 235 lines · 171 code · 64 blank · 0 comment · 0 complexity · c4874c9e67424edcd26d25e56988cd6a MD5 · raw file

  1. :mod:`pprint` --- Data pretty printer
  2. =====================================
  3. .. module:: pprint
  4. :synopsis: Data pretty printer.
  5. .. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
  6. .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
  7. The :mod:`pprint` module provides a capability to "pretty-print" arbitrary
  8. Python data structures in a form which can be used as input to the interpreter.
  9. If the formatted structures include objects which are not fundamental Python
  10. types, the representation may not be loadable. This may be the case if objects
  11. such as files, sockets, classes, or instances are included, as well as many
  12. other builtin objects which are not representable as Python constants.
  13. The formatted representation keeps objects on a single line if it can, and
  14. breaks them onto multiple lines if they don't fit within the allowed width.
  15. Construct :class:`PrettyPrinter` objects explicitly if you need to adjust the
  16. width constraint.
  17. .. versionchanged:: 2.5
  18. Dictionaries are sorted by key before the display is computed; before 2.5, a
  19. dictionary was sorted only if its display required more than one line, although
  20. that wasn't documented.
  21. .. versionchanged:: 2.6
  22. Added support for :class:`set` and :class:`frozenset`.
  23. The :mod:`pprint` module defines one class:
  24. .. First the implementation class:
  25. .. class:: PrettyPrinter(...)
  26. Construct a :class:`PrettyPrinter` instance. This constructor understands
  27. several keyword parameters. An output stream may be set using the *stream*
  28. keyword; the only method used on the stream object is the file protocol's
  29. :meth:`write` method. If not specified, the :class:`PrettyPrinter` adopts
  30. ``sys.stdout``. Three additional parameters may be used to control the
  31. formatted representation. The keywords are *indent*, *depth*, and *width*. The
  32. amount of indentation added for each recursive level is specified by *indent*;
  33. the default is one. Other values can cause output to look a little odd, but can
  34. make nesting easier to spot. The number of levels which may be printed is
  35. controlled by *depth*; if the data structure being printed is too deep, the next
  36. contained level is replaced by ``...``. By default, there is no constraint on
  37. the depth of the objects being formatted. The desired output width is
  38. constrained using the *width* parameter; the default is 80 characters. If a
  39. structure cannot be formatted within the constrained width, a best effort will
  40. be made.
  41. >>> import pprint
  42. >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
  43. >>> stuff.insert(0, stuff[:])
  44. >>> pp = pprint.PrettyPrinter(indent=4)
  45. >>> pp.pprint(stuff)
  46. [ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
  47. 'spam',
  48. 'eggs',
  49. 'lumberjack',
  50. 'knights',
  51. 'ni']
  52. >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
  53. ... ('parrot', ('fresh fruit',))))))))
  54. >>> pp = pprint.PrettyPrinter(depth=6)
  55. >>> pp.pprint(tup)
  56. ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
  57. The :class:`PrettyPrinter` class supports several derivative functions:
  58. .. Now the derivative functions:
  59. .. function:: pformat(object[, indent[, width[, depth]]])
  60. Return the formatted representation of *object* as a string. *indent*, *width*
  61. and *depth* will be passed to the :class:`PrettyPrinter` constructor as
  62. formatting parameters.
  63. .. versionchanged:: 2.4
  64. The parameters *indent*, *width* and *depth* were added.
  65. .. function:: pprint(object[, stream[, indent[, width[, depth]]]])
  66. Prints the formatted representation of *object* on *stream*, followed by a
  67. newline. If *stream* is omitted, ``sys.stdout`` is used. This may be used in
  68. the interactive interpreter instead of a :keyword:`print` statement for
  69. inspecting values. *indent*, *width* and *depth* will be passed to the
  70. :class:`PrettyPrinter` constructor as formatting parameters.
  71. >>> import pprint
  72. >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
  73. >>> stuff.insert(0, stuff)
  74. >>> pprint.pprint(stuff)
  75. [<Recursion on list with id=...>,
  76. 'spam',
  77. 'eggs',
  78. 'lumberjack',
  79. 'knights',
  80. 'ni']
  81. .. versionchanged:: 2.4
  82. The parameters *indent*, *width* and *depth* were added.
  83. .. function:: isreadable(object)
  84. .. index:: builtin: eval
  85. Determine if the formatted representation of *object* is "readable," or can be
  86. used to reconstruct the value using :func:`eval`. This always returns ``False``
  87. for recursive objects.
  88. >>> pprint.isreadable(stuff)
  89. False
  90. .. function:: isrecursive(object)
  91. Determine if *object* requires a recursive representation.
  92. One more support function is also defined:
  93. .. function:: saferepr(object)
  94. Return a string representation of *object*, protected against recursive data
  95. structures. If the representation of *object* exposes a recursive entry, the
  96. recursive reference will be represented as ``<Recursion on typename with
  97. id=number>``. The representation is not otherwise formatted.
  98. >>> pprint.saferepr(stuff)
  99. "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
  100. .. _prettyprinter-objects:
  101. PrettyPrinter Objects
  102. ---------------------
  103. :class:`PrettyPrinter` instances have the following methods:
  104. .. method:: PrettyPrinter.pformat(object)
  105. Return the formatted representation of *object*. This takes into account the
  106. options passed to the :class:`PrettyPrinter` constructor.
  107. .. method:: PrettyPrinter.pprint(object)
  108. Print the formatted representation of *object* on the configured stream,
  109. followed by a newline.
  110. The following methods provide the implementations for the corresponding
  111. functions of the same names. Using these methods on an instance is slightly
  112. more efficient since new :class:`PrettyPrinter` objects don't need to be
  113. created.
  114. .. method:: PrettyPrinter.isreadable(object)
  115. .. index:: builtin: eval
  116. Determine if the formatted representation of the object is "readable," or can be
  117. used to reconstruct the value using :func:`eval`. Note that this returns
  118. ``False`` for recursive objects. If the *depth* parameter of the
  119. :class:`PrettyPrinter` is set and the object is deeper than allowed, this
  120. returns ``False``.
  121. .. method:: PrettyPrinter.isrecursive(object)
  122. Determine if the object requires a recursive representation.
  123. This method is provided as a hook to allow subclasses to modify the way objects
  124. are converted to strings. The default implementation uses the internals of the
  125. :func:`saferepr` implementation.
  126. .. method:: PrettyPrinter.format(object, context, maxlevels, level)
  127. Returns three values: the formatted version of *object* as a string, a flag
  128. indicating whether the result is readable, and a flag indicating whether
  129. recursion was detected. The first argument is the object to be presented. The
  130. second is a dictionary which contains the :func:`id` of objects that are part of
  131. the current presentation context (direct and indirect containers for *object*
  132. that are affecting the presentation) as the keys; if an object needs to be
  133. presented which is already represented in *context*, the third return value
  134. should be ``True``. Recursive calls to the :meth:`format` method should add
  135. additional entries for containers to this dictionary. The third argument,
  136. *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there
  137. is no requested limit. This argument should be passed unmodified to recursive
  138. calls. The fourth argument, *level*, gives the current level; recursive calls
  139. should be passed a value less than that of the current call.
  140. .. versionadded:: 2.3
  141. .. _pprint-example:
  142. pprint Example
  143. --------------
  144. This example demonstrates several uses of the :func:`pprint` function and its parameters.
  145. >>> import pprint
  146. >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
  147. ... ('parrot', ('fresh fruit',))))))))
  148. >>> stuff = ['a' * 10, tup, ['a' * 30, 'b' * 30], ['c' * 20, 'd' * 20]]
  149. >>> pprint.pprint(stuff)
  150. ['aaaaaaaaaa',
  151. ('spam',
  152. ('eggs',
  153. ('lumberjack',
  154. ('knights', ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
  155. ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
  156. ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
  157. >>> pprint.pprint(stuff, depth=3)
  158. ['aaaaaaaaaa',
  159. ('spam', ('eggs', (...))),
  160. ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
  161. ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
  162. >>> pprint.pprint(stuff, width=60)
  163. ['aaaaaaaaaa',
  164. ('spam',
  165. ('eggs',
  166. ('lumberjack',
  167. ('knights',
  168. ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
  169. ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
  170. 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
  171. ['cccccccccccccccccccc', 'dddddddddddddddddddd']]