/Lib/pprint.py

http://unladen-swallow.googlecode.com/ · Python · 343 lines · 312 code · 1 blank · 30 comment · 1 complexity · 9fdf869c0d1381d80f9bef0b4f2bb526 MD5 · raw file

  1. # Author: Fred L. Drake, Jr.
  2. # fdrake@acm.org
  3. #
  4. # This is a simple little module I wrote to make life easier. I didn't
  5. # see anything quite like it in the library, though I may have overlooked
  6. # something. I wrote this when I was trying to read some heavily nested
  7. # tuples with fairly non-descriptive content. This is modeled very much
  8. # after Lisp/Scheme - style pretty-printing of lists. If you find it
  9. # useful, thank small children who sleep at night.
  10. """Support to pretty-print lists, tuples, & dictionaries recursively.
  11. Very simple, but useful, especially in debugging data structures.
  12. Classes
  13. -------
  14. PrettyPrinter()
  15. Handle pretty-printing operations onto a stream using a configured
  16. set of formatting parameters.
  17. Functions
  18. ---------
  19. pformat()
  20. Format a Python object into a pretty-printed representation.
  21. pprint()
  22. Pretty-print a Python object to a stream [default is sys.stdout].
  23. saferepr()
  24. Generate a 'standard' repr()-like value, but protect against recursive
  25. data structures.
  26. """
  27. import sys as _sys
  28. from cStringIO import StringIO as _StringIO
  29. __all__ = ["pprint","pformat","isreadable","isrecursive","saferepr",
  30. "PrettyPrinter"]
  31. # cache these for faster access:
  32. _commajoin = ", ".join
  33. _id = id
  34. _len = len
  35. _type = type
  36. def pprint(object, stream=None, indent=1, width=80, depth=None):
  37. """Pretty-print a Python object to a stream [default is sys.stdout]."""
  38. printer = PrettyPrinter(
  39. stream=stream, indent=indent, width=width, depth=depth)
  40. printer.pprint(object)
  41. def pformat(object, indent=1, width=80, depth=None):
  42. """Format a Python object into a pretty-printed representation."""
  43. return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
  44. def saferepr(object):
  45. """Version of repr() which can handle recursive data structures."""
  46. return _safe_repr(object, {}, None, 0)[0]
  47. def isreadable(object):
  48. """Determine if saferepr(object) is readable by eval()."""
  49. return _safe_repr(object, {}, None, 0)[1]
  50. def isrecursive(object):
  51. """Determine if object requires a recursive representation."""
  52. return _safe_repr(object, {}, None, 0)[2]
  53. class PrettyPrinter:
  54. def __init__(self, indent=1, width=80, depth=None, stream=None):
  55. """Handle pretty printing operations onto a stream using a set of
  56. configured parameters.
  57. indent
  58. Number of spaces to indent for each level of nesting.
  59. width
  60. Attempted maximum number of columns in the output.
  61. depth
  62. The maximum depth to print out nested structures.
  63. stream
  64. The desired output stream. If omitted (or false), the standard
  65. output stream available at construction will be used.
  66. """
  67. indent = int(indent)
  68. width = int(width)
  69. assert indent >= 0, "indent must be >= 0"
  70. assert depth is None or depth > 0, "depth must be > 0"
  71. assert width, "width must be != 0"
  72. self._depth = depth
  73. self._indent_per_level = indent
  74. self._width = width
  75. if stream is not None:
  76. self._stream = stream
  77. else:
  78. self._stream = _sys.stdout
  79. def pprint(self, object):
  80. self._format(object, self._stream, 0, 0, {}, 0)
  81. self._stream.write("\n")
  82. def pformat(self, object):
  83. sio = _StringIO()
  84. self._format(object, sio, 0, 0, {}, 0)
  85. return sio.getvalue()
  86. def isrecursive(self, object):
  87. return self.format(object, {}, 0, 0)[2]
  88. def isreadable(self, object):
  89. s, readable, recursive = self.format(object, {}, 0, 0)
  90. return readable and not recursive
  91. def _format(self, object, stream, indent, allowance, context, level):
  92. level = level + 1
  93. objid = _id(object)
  94. if objid in context:
  95. stream.write(_recursion(object))
  96. self._recursive = True
  97. self._readable = False
  98. return
  99. rep = self._repr(object, context, level - 1)
  100. typ = _type(object)
  101. sepLines = _len(rep) > (self._width - 1 - indent - allowance)
  102. write = stream.write
  103. if self._depth and level > self._depth:
  104. write(rep)
  105. return
  106. r = getattr(typ, "__repr__", None)
  107. if issubclass(typ, dict) and r is dict.__repr__:
  108. write('{')
  109. if self._indent_per_level > 1:
  110. write((self._indent_per_level - 1) * ' ')
  111. length = _len(object)
  112. if length:
  113. context[objid] = 1
  114. indent = indent + self._indent_per_level
  115. items = object.items()
  116. items.sort()
  117. key, ent = items[0]
  118. rep = self._repr(key, context, level)
  119. write(rep)
  120. write(': ')
  121. self._format(ent, stream, indent + _len(rep) + 2,
  122. allowance + 1, context, level)
  123. if length > 1:
  124. for key, ent in items[1:]:
  125. rep = self._repr(key, context, level)
  126. if sepLines:
  127. write(',\n%s%s: ' % (' '*indent, rep))
  128. else:
  129. write(', %s: ' % rep)
  130. self._format(ent, stream, indent + _len(rep) + 2,
  131. allowance + 1, context, level)
  132. indent = indent - self._indent_per_level
  133. del context[objid]
  134. write('}')
  135. return
  136. if ((issubclass(typ, list) and r is list.__repr__) or
  137. (issubclass(typ, tuple) and r is tuple.__repr__) or
  138. (issubclass(typ, set) and r is set.__repr__) or
  139. (issubclass(typ, frozenset) and r is frozenset.__repr__)
  140. ):
  141. length = _len(object)
  142. if issubclass(typ, list):
  143. write('[')
  144. endchar = ']'
  145. elif issubclass(typ, set):
  146. if not length:
  147. write('set()')
  148. return
  149. write('set([')
  150. endchar = '])'
  151. object = sorted(object)
  152. indent += 4
  153. elif issubclass(typ, frozenset):
  154. if not length:
  155. write('frozenset()')
  156. return
  157. write('frozenset([')
  158. endchar = '])'
  159. object = sorted(object)
  160. indent += 10
  161. else:
  162. write('(')
  163. endchar = ')'
  164. if self._indent_per_level > 1 and sepLines:
  165. write((self._indent_per_level - 1) * ' ')
  166. if length:
  167. context[objid] = 1
  168. indent = indent + self._indent_per_level
  169. self._format(object[0], stream, indent, allowance + 1,
  170. context, level)
  171. if length > 1:
  172. for ent in object[1:]:
  173. if sepLines:
  174. write(',\n' + ' '*indent)
  175. else:
  176. write(', ')
  177. self._format(ent, stream, indent,
  178. allowance + 1, context, level)
  179. indent = indent - self._indent_per_level
  180. del context[objid]
  181. if issubclass(typ, tuple) and length == 1:
  182. write(',')
  183. write(endchar)
  184. return
  185. write(rep)
  186. def _repr(self, object, context, level):
  187. repr, readable, recursive = self.format(object, context.copy(),
  188. self._depth, level)
  189. if not readable:
  190. self._readable = False
  191. if recursive:
  192. self._recursive = True
  193. return repr
  194. def format(self, object, context, maxlevels, level):
  195. """Format object for a specific context, returning a string
  196. and flags indicating whether the representation is 'readable'
  197. and whether the object represents a recursive construct.
  198. """
  199. return _safe_repr(object, context, maxlevels, level)
  200. # Return triple (repr_string, isreadable, isrecursive).
  201. def _safe_repr(object, context, maxlevels, level):
  202. typ = _type(object)
  203. if typ is str:
  204. if 'locale' not in _sys.modules:
  205. return repr(object), True, False
  206. if "'" in object and '"' not in object:
  207. closure = '"'
  208. quotes = {'"': '\\"'}
  209. else:
  210. closure = "'"
  211. quotes = {"'": "\\'"}
  212. qget = quotes.get
  213. sio = _StringIO()
  214. write = sio.write
  215. for char in object:
  216. if char.isalpha():
  217. write(char)
  218. else:
  219. write(qget(char, repr(char)[1:-1]))
  220. return ("%s%s%s" % (closure, sio.getvalue(), closure)), True, False
  221. r = getattr(typ, "__repr__", None)
  222. if issubclass(typ, dict) and r is dict.__repr__:
  223. if not object:
  224. return "{}", True, False
  225. objid = _id(object)
  226. if maxlevels and level >= maxlevels:
  227. return "{...}", False, objid in context
  228. if objid in context:
  229. return _recursion(object), False, True
  230. context[objid] = 1
  231. readable = True
  232. recursive = False
  233. components = []
  234. append = components.append
  235. level += 1
  236. saferepr = _safe_repr
  237. for k, v in sorted(object.items()):
  238. krepr, kreadable, krecur = saferepr(k, context, maxlevels, level)
  239. vrepr, vreadable, vrecur = saferepr(v, context, maxlevels, level)
  240. append("%s: %s" % (krepr, vrepr))
  241. readable = readable and kreadable and vreadable
  242. if krecur or vrecur:
  243. recursive = True
  244. del context[objid]
  245. return "{%s}" % _commajoin(components), readable, recursive
  246. if (issubclass(typ, list) and r is list.__repr__) or \
  247. (issubclass(typ, tuple) and r is tuple.__repr__):
  248. if issubclass(typ, list):
  249. if not object:
  250. return "[]", True, False
  251. format = "[%s]"
  252. elif _len(object) == 1:
  253. format = "(%s,)"
  254. else:
  255. if not object:
  256. return "()", True, False
  257. format = "(%s)"
  258. objid = _id(object)
  259. if maxlevels and level >= maxlevels:
  260. return format % "...", False, objid in context
  261. if objid in context:
  262. return _recursion(object), False, True
  263. context[objid] = 1
  264. readable = True
  265. recursive = False
  266. components = []
  267. append = components.append
  268. level += 1
  269. for o in object:
  270. orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level)
  271. append(orepr)
  272. if not oreadable:
  273. readable = False
  274. if orecur:
  275. recursive = True
  276. del context[objid]
  277. return format % _commajoin(components), readable, recursive
  278. rep = repr(object)
  279. return rep, (rep and not rep.startswith('<')), False
  280. def _recursion(object):
  281. return ("<Recursion on %s with id=%s>"
  282. % (_type(object).__name__, _id(object)))
  283. def _perfcheck(object=None):
  284. import time
  285. if object is None:
  286. object = [("string", (1, 2), [3, 4], {5: 6, 7: 8})] * 100000
  287. p = PrettyPrinter()
  288. t1 = time.time()
  289. _safe_repr(object, {}, None, 0)
  290. t2 = time.time()
  291. p.pformat(object)
  292. t3 = time.time()
  293. print "_safe_repr:", t2 - t1
  294. print "pformat:", t3 - t2
  295. if __name__ == "__main__":
  296. _perfcheck()