PageRenderTime 471ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/modified-2.7/pprint.py

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