PageRenderTime 52ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/pprint.py

http://github.com/IronLanguages/main
Python | 346 lines | 315 code | 1 blank | 30 comment | 0 complexity | 73f5ad8b26a498bc3ed9fd6d73723b9b MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  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. import warnings
  29. try:
  30. from cStringIO import StringIO as _StringIO
  31. except ImportError:
  32. from StringIO import StringIO as _StringIO
  33. __all__ = ["pprint","pformat","isreadable","isrecursive","saferepr",
  34. "PrettyPrinter"]
  35. # cache these for faster access:
  36. _commajoin = ", ".join
  37. _id = id
  38. _len = len
  39. _type = type
  40. def pprint(object, stream=None, indent=1, width=80, depth=None):
  41. """Pretty-print a Python object to a stream [default is sys.stdout]."""
  42. printer = PrettyPrinter(
  43. stream=stream, indent=indent, width=width, depth=depth)
  44. printer.pprint(object)
  45. def pformat(object, indent=1, width=80, depth=None):
  46. """Format a Python object into a pretty-printed representation."""
  47. return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
  48. def saferepr(object):
  49. """Version of repr() which can handle recursive data structures."""
  50. return _safe_repr(object, {}, None, 0)[0]
  51. def isreadable(object):
  52. """Determine if saferepr(object) is readable by eval()."""
  53. return _safe_repr(object, {}, None, 0)[1]
  54. def isrecursive(object):
  55. """Determine if object requires a recursive representation."""
  56. return _safe_repr(object, {}, None, 0)[2]
  57. def _sorted(iterable):
  58. with warnings.catch_warnings():
  59. if _sys.py3kwarning:
  60. warnings.filterwarnings("ignore", "comparing unequal types "
  61. "not supported", DeprecationWarning)
  62. return sorted(iterable)
  63. class PrettyPrinter:
  64. def __init__(self, indent=1, width=80, depth=None, stream=None):
  65. """Handle pretty printing operations onto a stream using a set of
  66. configured parameters.
  67. indent
  68. Number of spaces to indent for each level of nesting.
  69. width
  70. Attempted maximum number of columns in the output.
  71. depth
  72. The maximum depth to print out nested structures.
  73. stream
  74. The desired output stream. If omitted (or false), the standard
  75. output stream available at construction will be used.
  76. """
  77. indent = int(indent)
  78. width = int(width)
  79. assert indent >= 0, "indent must be >= 0"
  80. assert depth is None or depth > 0, "depth must be > 0"
  81. assert width, "width must be != 0"
  82. self._depth = depth
  83. self._indent_per_level = indent
  84. self._width = width
  85. if stream is not None:
  86. self._stream = stream
  87. else:
  88. self._stream = _sys.stdout
  89. def pprint(self, object):
  90. self._format(object, self._stream, 0, 0, {}, 0)
  91. self._stream.write("\n")
  92. def pformat(self, object):
  93. sio = _StringIO()
  94. self._format(object, sio, 0, 0, {}, 0)
  95. return sio.getvalue()
  96. def isrecursive(self, object):
  97. return self.format(object, {}, 0, 0)[2]
  98. def isreadable(self, object):
  99. s, readable, recursive = self.format(object, {}, 0, 0)
  100. return readable and not recursive
  101. def _format(self, object, stream, indent, allowance, context, level):
  102. level = level + 1
  103. objid = _id(object)
  104. if objid in context:
  105. stream.write(_recursion(object))
  106. self._recursive = True
  107. self._readable = False
  108. return
  109. rep = self._repr(object, context, level - 1)
  110. typ = _type(object)
  111. sepLines = _len(rep) > (self._width - 1 - indent - allowance)
  112. write = stream.write
  113. if self._depth and level > self._depth:
  114. write(rep)
  115. return
  116. r = getattr(typ, "__repr__", None)
  117. if issubclass(typ, dict) and r is dict.__repr__:
  118. write('{')
  119. if self._indent_per_level > 1:
  120. write((self._indent_per_level - 1) * ' ')
  121. length = _len(object)
  122. if length:
  123. context[objid] = 1
  124. indent = indent + self._indent_per_level
  125. items = _sorted(object.items())
  126. key, ent = items[0]
  127. rep = self._repr(key, context, level)
  128. write(rep)
  129. write(': ')
  130. self._format(ent, stream, indent + _len(rep) + 2,
  131. allowance + 1, context, level)
  132. if length > 1:
  133. for key, ent in items[1:]:
  134. rep = self._repr(key, context, level)
  135. if sepLines:
  136. write(',\n%s%s: ' % (' '*indent, rep))
  137. else:
  138. write(', %s: ' % rep)
  139. self._format(ent, stream, indent + _len(rep) + 2,
  140. allowance + 1, context, level)
  141. indent = indent - self._indent_per_level
  142. del context[objid]
  143. write('}')
  144. return
  145. if ((issubclass(typ, list) and r is list.__repr__) or
  146. (issubclass(typ, tuple) and r is tuple.__repr__) or
  147. (issubclass(typ, set) and r is set.__repr__) or
  148. (issubclass(typ, frozenset) and r is frozenset.__repr__)
  149. ):
  150. length = _len(object)
  151. if issubclass(typ, list):
  152. write('[')
  153. endchar = ']'
  154. elif issubclass(typ, tuple):
  155. write('(')
  156. endchar = ')'
  157. else:
  158. if not length:
  159. write(rep)
  160. return
  161. write(typ.__name__)
  162. write('([')
  163. endchar = '])'
  164. indent += len(typ.__name__) + 1
  165. object = _sorted(object)
  166. if self._indent_per_level > 1 and sepLines:
  167. write((self._indent_per_level - 1) * ' ')
  168. if length:
  169. context[objid] = 1
  170. indent = indent + self._indent_per_level
  171. self._format(object[0], stream, indent, allowance + 1,
  172. context, level)
  173. if length > 1:
  174. for ent in object[1:]:
  175. if sepLines:
  176. write(',\n' + ' '*indent)
  177. else:
  178. write(', ')
  179. self._format(ent, stream, indent,
  180. allowance + 1, context, level)
  181. indent = indent - self._indent_per_level
  182. del context[objid]
  183. if issubclass(typ, tuple) and length == 1:
  184. write(',')
  185. write(endchar)
  186. return
  187. write(rep)
  188. def _repr(self, object, context, level):
  189. repr, readable, recursive = self.format(object, context.copy(),
  190. self._depth, level)
  191. if not readable:
  192. self._readable = False
  193. if recursive:
  194. self._recursive = True
  195. return repr
  196. def format(self, object, context, maxlevels, level):
  197. """Format object for a specific context, returning a string
  198. and flags indicating whether the representation is 'readable'
  199. and whether the object represents a recursive construct.
  200. """
  201. return _safe_repr(object, context, maxlevels, level)
  202. # Return triple (repr_string, isreadable, isrecursive).
  203. def _safe_repr(object, context, maxlevels, level):
  204. typ = _type(object)
  205. if typ is str:
  206. if 'locale' not in _sys.modules:
  207. return repr(object), True, False
  208. if "'" in object and '"' not in object:
  209. closure = '"'
  210. quotes = {'"': '\\"'}
  211. else:
  212. closure = "'"
  213. quotes = {"'": "\\'"}
  214. qget = quotes.get
  215. sio = _StringIO()
  216. write = sio.write
  217. for char in object:
  218. if char.isalpha():
  219. write(char)
  220. else:
  221. write(qget(char, repr(char)[1:-1]))
  222. return ("%s%s%s" % (closure, sio.getvalue(), closure)), True, False
  223. r = getattr(typ, "__repr__", None)
  224. if issubclass(typ, dict) and r is dict.__repr__:
  225. if not object:
  226. return "{}", True, False
  227. objid = _id(object)
  228. if maxlevels and level >= maxlevels:
  229. return "{...}", False, objid in context
  230. if objid in context:
  231. return _recursion(object), False, True
  232. context[objid] = 1
  233. readable = True
  234. recursive = False
  235. components = []
  236. append = components.append
  237. level += 1
  238. saferepr = _safe_repr
  239. for k, v in _sorted(object.items()):
  240. krepr, kreadable, krecur = saferepr(k, context, maxlevels, level)
  241. vrepr, vreadable, vrecur = saferepr(v, context, maxlevels, level)
  242. append("%s: %s" % (krepr, vrepr))
  243. readable = readable and kreadable and vreadable
  244. if krecur or vrecur:
  245. recursive = True
  246. del context[objid]
  247. return "{%s}" % _commajoin(components), readable, recursive
  248. if (issubclass(typ, list) and r is list.__repr__) or \
  249. (issubclass(typ, tuple) and r is tuple.__repr__):
  250. if issubclass(typ, list):
  251. if not object:
  252. return "[]", True, False
  253. format = "[%s]"
  254. elif _len(object) == 1:
  255. format = "(%s,)"
  256. else:
  257. if not object:
  258. return "()", True, False
  259. format = "(%s)"
  260. objid = _id(object)
  261. if maxlevels and level >= maxlevels:
  262. return format % "...", False, objid in context
  263. if objid in context:
  264. return _recursion(object), False, True
  265. context[objid] = 1
  266. readable = True
  267. recursive = False
  268. components = []
  269. append = components.append
  270. level += 1
  271. for o in object:
  272. orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level)
  273. append(orepr)
  274. if not oreadable:
  275. readable = False
  276. if orecur:
  277. recursive = True
  278. del context[objid]
  279. return format % _commajoin(components), readable, recursive
  280. rep = repr(object)
  281. return rep, (rep and not rep.startswith('<')), False
  282. def _recursion(object):
  283. return ("<Recursion on %s with id=%s>"
  284. % (_type(object).__name__, _id(object)))
  285. def _perfcheck(object=None):
  286. import time
  287. if object is None:
  288. object = [("string", (1, 2), [3, 4], {5: 6, 7: 8})] * 100000
  289. p = PrettyPrinter()
  290. t1 = time.time()
  291. _safe_repr(object, {}, None, 0)
  292. t2 = time.time()
  293. p.pformat(object)
  294. t3 = time.time()
  295. print "_safe_repr:", t2 - t1
  296. print "pformat:", t3 - t2
  297. if __name__ == "__main__":
  298. _perfcheck()