blob: d7d0405b2282dd815c091ec4f2b11ee6dff82faf [file] [log] [blame]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001# Author: Fred L. Drake, Jr.
Fred Drake3e5e6612001-10-09 20:53:48 +00002# fdrake@acm.org
Guido van Rossum5e92aff1997-04-16 00:49:59 +00003#
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
Thomas Wouters7e474022000-07-16 12:04:32 +00007# tuples with fairly non-descriptive content. This is modeled very much
Guido van Rossum5e92aff1997-04-16 00:49:59 +00008# after Lisp/Scheme - style pretty-printing of lists. If you find it
9# useful, thank small children who sleep at night.
10
11"""Support to pretty-print lists, tuples, & dictionaries recursively.
12
13Very simple, but useful, especially in debugging data structures.
14
Fred Drakea89fda01997-04-16 16:59:30 +000015Classes
16-------
17
18PrettyPrinter()
19 Handle pretty-printing operations onto a stream using a configured
20 set of formatting parameters.
21
Guido van Rossum5e92aff1997-04-16 00:49:59 +000022Functions
23---------
24
25pformat()
26 Format a Python object into a pretty-printed representation.
27
28pprint()
Fred Drakea89fda01997-04-16 16:59:30 +000029 Pretty-print a Python object to a stream [default is sys.sydout].
Guido van Rossum5e92aff1997-04-16 00:49:59 +000030
Fred Drakea89fda01997-04-16 16:59:30 +000031saferepr()
32 Generate a 'standard' repr()-like value, but protect against recursive
33 data structures.
Guido van Rossum5e92aff1997-04-16 00:49:59 +000034
35"""
36
Fred Drake1ef106c2001-09-04 19:43:26 +000037from types import DictType, ListType, TupleType, StringType
38import sys
Guido van Rossum5e92aff1997-04-16 00:49:59 +000039
Fred Drakea89fda01997-04-16 16:59:30 +000040try:
41 from cStringIO import StringIO
42except ImportError:
43 from StringIO import StringIO
Guido van Rossum5e92aff1997-04-16 00:49:59 +000044
Skip Montanaroc62c81e2001-02-12 02:00:42 +000045__all__ = ["pprint","pformat","isreadable","isrecursive","saferepr",
46 "PrettyPrinter"]
Guido van Rossum5e92aff1997-04-16 00:49:59 +000047
Fred Drake49cc01e2001-11-01 17:50:38 +000048# cache these for faster access:
49_commajoin = ", ".join
50_sys_modules = sys.modules
51_id = id
52_len = len
53_type = type
54
55
Fred Drakea89fda01997-04-16 16:59:30 +000056def pprint(object, stream=None):
57 """Pretty-print a Python object to a stream [default is sys.sydout]."""
58 printer = PrettyPrinter(stream=stream)
59 printer.pprint(object)
Guido van Rossum5e92aff1997-04-16 00:49:59 +000060
Fred Drakea89fda01997-04-16 16:59:30 +000061def pformat(object):
62 """Format a Python object into a pretty-printed representation."""
63 return PrettyPrinter().pformat(object)
Guido van Rossum5e92aff1997-04-16 00:49:59 +000064
Fred Drakea89fda01997-04-16 16:59:30 +000065def saferepr(object):
66 """Version of repr() which can handle recursive data structures."""
Fred Drake49cc01e2001-11-01 17:50:38 +000067 return _safe_repr(object, {}, None, 0)[0]
Guido van Rossum5e92aff1997-04-16 00:49:59 +000068
Tim Petersa814db52001-05-14 07:05:58 +000069def isreadable(object):
70 """Determine if saferepr(object) is readable by eval()."""
Fred Drake49cc01e2001-11-01 17:50:38 +000071 return _safe_repr(object, {}, None, 0)[1]
Tim Petersa814db52001-05-14 07:05:58 +000072
73def isrecursive(object):
74 """Determine if object requires a recursive representation."""
Fred Drake49cc01e2001-11-01 17:50:38 +000075 return _safe_repr(object, {}, None, 0)[2]
Guido van Rossum5e92aff1997-04-16 00:49:59 +000076
Fred Drakea89fda01997-04-16 16:59:30 +000077class PrettyPrinter:
78 def __init__(self, indent=1, width=80, depth=None, stream=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000079 """Handle pretty printing operations onto a stream using a set of
80 configured parameters.
Guido van Rossum5e92aff1997-04-16 00:49:59 +000081
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000082 indent
83 Number of spaces to indent for each level of nesting.
Guido van Rossum5e92aff1997-04-16 00:49:59 +000084
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000085 width
86 Attempted maximum number of columns in the output.
Guido van Rossum5e92aff1997-04-16 00:49:59 +000087
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000088 depth
89 The maximum depth to print out nested structures.
Guido van Rossum5e92aff1997-04-16 00:49:59 +000090
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000091 stream
92 The desired output stream. If omitted (or false), the standard
93 output stream available at construction will be used.
Guido van Rossum5e92aff1997-04-16 00:49:59 +000094
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000095 """
96 indent = int(indent)
97 width = int(width)
98 assert indent >= 0
Tim Petersa814db52001-05-14 07:05:58 +000099 assert depth is None or depth > 0, "depth must be > 0"
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000100 assert width
Fred Drakee6691ef2002-07-08 12:28:06 +0000101 self._depth = depth
102 self._indent_per_level = indent
103 self._width = width
Raymond Hettinger16e3c422002-06-01 16:07:16 +0000104 if stream is not None:
Fred Drakee6691ef2002-07-08 12:28:06 +0000105 self._stream = stream
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000106 else:
Fred Drakee6691ef2002-07-08 12:28:06 +0000107 self._stream = sys.stdout
Guido van Rossum5e92aff1997-04-16 00:49:59 +0000108
Fred Drakea89fda01997-04-16 16:59:30 +0000109 def pprint(self, object):
Fred Drakee6691ef2002-07-08 12:28:06 +0000110 self._stream.write(self.pformat(object) + "\n")
Fred Drakea89fda01997-04-16 16:59:30 +0000111
112 def pformat(self, object):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000113 sio = StringIO()
Fred Drakee6691ef2002-07-08 12:28:06 +0000114 self._format(object, sio, 0, 0, {}, 0)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000115 return sio.getvalue()
Fred Drakea89fda01997-04-16 16:59:30 +0000116
Fred Drakee0ffabe1997-07-18 20:42:39 +0000117 def isrecursive(self, object):
Fred Drakeaee113d2002-04-02 05:08:35 +0000118 return self.format(object, {}, 0)[2]
Fred Drakee0ffabe1997-07-18 20:42:39 +0000119
120 def isreadable(self, object):
Fred Drakeaee113d2002-04-02 05:08:35 +0000121 s, readable, recursive = self.format(object, {}, 0)
122 return readable and not recursive
Fred Drakee0ffabe1997-07-18 20:42:39 +0000123
Fred Drakee6691ef2002-07-08 12:28:06 +0000124 def _format(self, object, stream, indent, allowance, context, level):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000125 level = level + 1
Fred Drake49cc01e2001-11-01 17:50:38 +0000126 objid = _id(object)
127 if objid in context:
128 stream.write(_recursion(object))
Fred Drakee6691ef2002-07-08 12:28:06 +0000129 self._recursive = True
130 self._readable = False
Fred Drake49cc01e2001-11-01 17:50:38 +0000131 return
Fred Drakee6691ef2002-07-08 12:28:06 +0000132 rep = self._repr(object, context, level - 1)
Fred Drake49cc01e2001-11-01 17:50:38 +0000133 typ = _type(object)
Fred Drakee6691ef2002-07-08 12:28:06 +0000134 sepLines = _len(rep) > (self._width - 1 - indent - allowance)
Fred Drake49cc01e2001-11-01 17:50:38 +0000135 write = stream.write
Fred Drakea89fda01997-04-16 16:59:30 +0000136
Fred Drake49cc01e2001-11-01 17:50:38 +0000137 if sepLines:
138 if typ is DictType:
139 write('{')
Fred Drakee6691ef2002-07-08 12:28:06 +0000140 if self._indent_per_level > 1:
141 write((self._indent_per_level - 1) * ' ')
Fred Drake49cc01e2001-11-01 17:50:38 +0000142 length = _len(object)
143 if length:
144 context[objid] = 1
Fred Drakee6691ef2002-07-08 12:28:06 +0000145 indent = indent + self._indent_per_level
Fred Drake49cc01e2001-11-01 17:50:38 +0000146 items = object.items()
147 items.sort()
148 key, ent = items[0]
Fred Drakee6691ef2002-07-08 12:28:06 +0000149 rep = self._repr(key, context, level)
Fred Drake49cc01e2001-11-01 17:50:38 +0000150 write(rep)
151 write(': ')
Fred Drakee6691ef2002-07-08 12:28:06 +0000152 self._format(ent, stream, indent + _len(rep) + 2,
Fred Drake49cc01e2001-11-01 17:50:38 +0000153 allowance + 1, context, level)
154 if length > 1:
155 for key, ent in items[1:]:
Fred Drakee6691ef2002-07-08 12:28:06 +0000156 rep = self._repr(key, context, level)
Barry Warsaw00859c02001-11-28 05:49:39 +0000157 write(',\n%s%s: ' % (' '*indent, rep))
Fred Drakee6691ef2002-07-08 12:28:06 +0000158 self._format(ent, stream, indent + _len(rep) + 2,
Fred Drake49cc01e2001-11-01 17:50:38 +0000159 allowance + 1, context, level)
Fred Drakee6691ef2002-07-08 12:28:06 +0000160 indent = indent - self._indent_per_level
Fred Drake49cc01e2001-11-01 17:50:38 +0000161 del context[objid]
162 write('}')
163 return
Fred Drakea89fda01997-04-16 16:59:30 +0000164
Fred Drake49cc01e2001-11-01 17:50:38 +0000165 if typ is ListType or typ is TupleType:
166 if typ is ListType:
167 write('[')
168 endchar = ']'
169 else:
170 write('(')
171 endchar = ')'
Fred Drakee6691ef2002-07-08 12:28:06 +0000172 if self._indent_per_level > 1:
173 write((self._indent_per_level - 1) * ' ')
Fred Drake49cc01e2001-11-01 17:50:38 +0000174 length = _len(object)
175 if length:
176 context[objid] = 1
Fred Drakee6691ef2002-07-08 12:28:06 +0000177 indent = indent + self._indent_per_level
178 self._format(object[0], stream, indent, allowance + 1,
179 context, level)
Fred Drake49cc01e2001-11-01 17:50:38 +0000180 if length > 1:
181 for ent in object[1:]:
182 write(',\n' + ' '*indent)
Fred Drakee6691ef2002-07-08 12:28:06 +0000183 self._format(ent, stream, indent,
Fred Drake49cc01e2001-11-01 17:50:38 +0000184 allowance + 1, context, level)
Fred Drakee6691ef2002-07-08 12:28:06 +0000185 indent = indent - self._indent_per_level
Fred Drake49cc01e2001-11-01 17:50:38 +0000186 del context[objid]
187 if typ is TupleType and length == 1:
188 write(',')
189 write(endchar)
190 return
Fred Drakea89fda01997-04-16 16:59:30 +0000191
Fred Drake49cc01e2001-11-01 17:50:38 +0000192 write(rep)
Guido van Rossum5e92aff1997-04-16 00:49:59 +0000193
Fred Drakee6691ef2002-07-08 12:28:06 +0000194 def _repr(self, object, context, level):
Fred Drakeaee113d2002-04-02 05:08:35 +0000195 repr, readable, recursive = self.format(object, context.copy(),
Fred Drakee6691ef2002-07-08 12:28:06 +0000196 self._depth, level)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000197 if not readable:
Fred Drakee6691ef2002-07-08 12:28:06 +0000198 self._readable = False
Tim Petersa814db52001-05-14 07:05:58 +0000199 if recursive:
Fred Drakee6691ef2002-07-08 12:28:06 +0000200 self._recursive = True
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000201 return repr
Guido van Rossum5e92aff1997-04-16 00:49:59 +0000202
Fred Drakeaee113d2002-04-02 05:08:35 +0000203 def format(self, object, context, maxlevels, level):
204 """Format object for a specific context, returning a string
205 and flags indicating whether the representation is 'readable'
206 and whether the object represents a recursive construct.
207 """
208 return _safe_repr(object, context, maxlevels, level)
209
210
Tim Petersa814db52001-05-14 07:05:58 +0000211# Return triple (repr_string, isreadable, isrecursive).
Guido van Rossum5e92aff1997-04-16 00:49:59 +0000212
Fred Drake49cc01e2001-11-01 17:50:38 +0000213def _safe_repr(object, context, maxlevels, level):
214 typ = _type(object)
215 if typ is StringType:
216 if 'locale' not in _sys_modules:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000217 return `object`, True, False
Fred Drake1ef106c2001-09-04 19:43:26 +0000218 if "'" in object and '"' not in object:
219 closure = '"'
220 quotes = {'"': '\\"'}
221 else:
222 closure = "'"
223 quotes = {"'": "\\'"}
Fred Drake49cc01e2001-11-01 17:50:38 +0000224 qget = quotes.get
Fred Drake1ef106c2001-09-04 19:43:26 +0000225 sio = StringIO()
Fred Drake49cc01e2001-11-01 17:50:38 +0000226 write = sio.write
Fred Drake1ef106c2001-09-04 19:43:26 +0000227 for char in object:
228 if char.isalpha():
Fred Drake49cc01e2001-11-01 17:50:38 +0000229 write(char)
Fred Drake1ef106c2001-09-04 19:43:26 +0000230 else:
Fred Drake49cc01e2001-11-01 17:50:38 +0000231 write(qget(char, `char`[1:-1]))
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000232 return ("%s%s%s" % (closure, sio.getvalue(), closure)), True, False
Tim Peters95b3f782001-05-14 18:39:41 +0000233
Fred Drake49cc01e2001-11-01 17:50:38 +0000234 if typ is DictType:
235 if not object:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000236 return "{}", True, False
Fred Drake49cc01e2001-11-01 17:50:38 +0000237 objid = _id(object)
238 if maxlevels and level > maxlevels:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000239 return "{...}", False, objid in context
Fred Drake49cc01e2001-11-01 17:50:38 +0000240 if objid in context:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000241 return _recursion(object), False, True
Fred Drake49cc01e2001-11-01 17:50:38 +0000242 context[objid] = 1
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000243 readable = True
244 recursive = False
Tim Peters95b3f782001-05-14 18:39:41 +0000245 components = []
Fred Drake49cc01e2001-11-01 17:50:38 +0000246 append = components.append
247 level += 1
248 saferepr = _safe_repr
Tim Peters95b3f782001-05-14 18:39:41 +0000249 for k, v in object.iteritems():
Fred Drake49cc01e2001-11-01 17:50:38 +0000250 krepr, kreadable, krecur = saferepr(k, context, maxlevels, level)
251 vrepr, vreadable, vrecur = saferepr(v, context, maxlevels, level)
252 append("%s: %s" % (krepr, vrepr))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000253 readable = readable and kreadable and vreadable
Fred Drake49cc01e2001-11-01 17:50:38 +0000254 if krecur or vrecur:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000255 recursive = True
Fred Drake49cc01e2001-11-01 17:50:38 +0000256 del context[objid]
257 return "{%s}" % _commajoin(components), readable, recursive
Tim Peters95b3f782001-05-14 18:39:41 +0000258
Fred Drake49cc01e2001-11-01 17:50:38 +0000259 if typ is ListType or typ is TupleType:
260 if typ is ListType:
261 if not object:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000262 return "[]", True, False
Fred Drake49cc01e2001-11-01 17:50:38 +0000263 format = "[%s]"
264 elif _len(object) == 1:
265 format = "(%s,)"
266 else:
267 if not object:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000268 return "()", True, False
Fred Drake49cc01e2001-11-01 17:50:38 +0000269 format = "(%s)"
270 objid = _id(object)
271 if maxlevels and level > maxlevels:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000272 return format % "...", False, objid in context
Fred Drake49cc01e2001-11-01 17:50:38 +0000273 if objid in context:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000274 return _recursion(object), False, True
Fred Drake49cc01e2001-11-01 17:50:38 +0000275 context[objid] = 1
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000276 readable = True
277 recursive = False
Tim Peters95b3f782001-05-14 18:39:41 +0000278 components = []
Fred Drake49cc01e2001-11-01 17:50:38 +0000279 append = components.append
280 level += 1
281 for o in object:
282 orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level)
283 append(orepr)
284 if not oreadable:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000285 readable = False
Fred Drake49cc01e2001-11-01 17:50:38 +0000286 if orecur:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000287 recursive = True
Fred Drake49cc01e2001-11-01 17:50:38 +0000288 del context[objid]
289 return format % _commajoin(components), readable, recursive
Tim Peters88768482001-11-13 21:51:26 +0000290
Fred Drake49cc01e2001-11-01 17:50:38 +0000291 rep = `object`
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000292 return rep, (rep and not rep.startswith('<')), False
Tim Peters95b3f782001-05-14 18:39:41 +0000293
Guido van Rossum5e92aff1997-04-16 00:49:59 +0000294
Fred Drake49cc01e2001-11-01 17:50:38 +0000295def _recursion(object):
296 return ("<Recursion on %s with id=%s>"
297 % (_type(object).__name__, _id(object)))
Fred Drakea89fda01997-04-16 16:59:30 +0000298
Fred Drake49cc01e2001-11-01 17:50:38 +0000299
300def _perfcheck(object=None):
301 import time
302 if object is None:
303 object = [("string", (1, 2), [3, 4], {5: 6, 7: 8})] * 100000
304 p = PrettyPrinter()
305 t1 = time.time()
306 _safe_repr(object, {}, None, 0)
307 t2 = time.time()
308 p.pformat(object)
309 t3 = time.time()
310 print "_safe_repr:", t2 - t1
311 print "pformat:", t3 - t2
312
313if __name__ == "__main__":
314 _perfcheck()