blob: c48465b8d5855304de91697ef9065e4843bcdfa3 [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()
Skip Montanaro2dc0c132004-05-14 16:31:56 +000029 Pretty-print a Python object to a stream [default is sys.stdout].
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 Drake397b6152002-12-31 07:14:18 +000037import sys as _sys
Guido van Rossum5e92aff1997-04-16 00:49:59 +000038
Fred Drake397b6152002-12-31 07:14:18 +000039from cStringIO import StringIO as _StringIO
Guido van Rossum5e92aff1997-04-16 00:49:59 +000040
Skip Montanaroc62c81e2001-02-12 02:00:42 +000041__all__ = ["pprint","pformat","isreadable","isrecursive","saferepr",
42 "PrettyPrinter"]
Guido van Rossum5e92aff1997-04-16 00:49:59 +000043
Fred Drake49cc01e2001-11-01 17:50:38 +000044# cache these for faster access:
45_commajoin = ", ".join
Fred Drake49cc01e2001-11-01 17:50:38 +000046_id = id
47_len = len
48_type = type
49
50
Walter Dörwaldc8de4582003-12-03 20:26:05 +000051def pprint(object, stream=None, indent=1, width=80, depth=None):
Skip Montanaro2dc0c132004-05-14 16:31:56 +000052 """Pretty-print a Python object to a stream [default is sys.stdout]."""
Walter Dörwaldc8de4582003-12-03 20:26:05 +000053 printer = PrettyPrinter(
54 stream=stream, indent=indent, width=width, depth=depth)
Fred Drakea89fda01997-04-16 16:59:30 +000055 printer.pprint(object)
Guido van Rossum5e92aff1997-04-16 00:49:59 +000056
Walter Dörwaldc8de4582003-12-03 20:26:05 +000057def pformat(object, indent=1, width=80, depth=None):
Fred Drakea89fda01997-04-16 16:59:30 +000058 """Format a Python object into a pretty-printed representation."""
Walter Dörwaldc8de4582003-12-03 20:26:05 +000059 return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
Guido van Rossum5e92aff1997-04-16 00:49:59 +000060
Fred Drakea89fda01997-04-16 16:59:30 +000061def saferepr(object):
62 """Version of repr() which can handle recursive data structures."""
Fred Drake49cc01e2001-11-01 17:50:38 +000063 return _safe_repr(object, {}, None, 0)[0]
Guido van Rossum5e92aff1997-04-16 00:49:59 +000064
Tim Petersa814db52001-05-14 07:05:58 +000065def isreadable(object):
66 """Determine if saferepr(object) is readable by eval()."""
Fred Drake49cc01e2001-11-01 17:50:38 +000067 return _safe_repr(object, {}, None, 0)[1]
Tim Petersa814db52001-05-14 07:05:58 +000068
69def isrecursive(object):
70 """Determine if object requires a recursive representation."""
Fred Drake49cc01e2001-11-01 17:50:38 +000071 return _safe_repr(object, {}, None, 0)[2]
Guido van Rossum5e92aff1997-04-16 00:49:59 +000072
Fred Drakea89fda01997-04-16 16:59:30 +000073class PrettyPrinter:
74 def __init__(self, indent=1, width=80, depth=None, stream=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000075 """Handle pretty printing operations onto a stream using a set of
76 configured parameters.
Guido van Rossum5e92aff1997-04-16 00:49:59 +000077
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000078 indent
79 Number of spaces to indent for each level of nesting.
Guido van Rossum5e92aff1997-04-16 00:49:59 +000080
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000081 width
82 Attempted maximum number of columns in the output.
Guido van Rossum5e92aff1997-04-16 00:49:59 +000083
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000084 depth
85 The maximum depth to print out nested structures.
Guido van Rossum5e92aff1997-04-16 00:49:59 +000086
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000087 stream
88 The desired output stream. If omitted (or false), the standard
89 output stream available at construction will be used.
Guido van Rossum5e92aff1997-04-16 00:49:59 +000090
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000091 """
92 indent = int(indent)
93 width = int(width)
Walter Dörwald7a7ede52003-12-03 20:15:28 +000094 assert indent >= 0, "indent must be >= 0"
Tim Petersa814db52001-05-14 07:05:58 +000095 assert depth is None or depth > 0, "depth must be > 0"
Walter Dörwald7a7ede52003-12-03 20:15:28 +000096 assert width, "width must be != 0"
Fred Drakee6691ef2002-07-08 12:28:06 +000097 self._depth = depth
98 self._indent_per_level = indent
99 self._width = width
Raymond Hettinger16e3c422002-06-01 16:07:16 +0000100 if stream is not None:
Fred Drakee6691ef2002-07-08 12:28:06 +0000101 self._stream = stream
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000102 else:
Fred Drake397b6152002-12-31 07:14:18 +0000103 self._stream = _sys.stdout
Guido van Rossum5e92aff1997-04-16 00:49:59 +0000104
Fred Drakea89fda01997-04-16 16:59:30 +0000105 def pprint(self, object):
Walter Dörwalde62e9362005-11-11 18:18:51 +0000106 self._format(object, self._stream, 0, 0, {}, 0)
107 self._stream.write("\n")
Fred Drakea89fda01997-04-16 16:59:30 +0000108
109 def pformat(self, object):
Fred Drake397b6152002-12-31 07:14:18 +0000110 sio = _StringIO()
Fred Drakee6691ef2002-07-08 12:28:06 +0000111 self._format(object, sio, 0, 0, {}, 0)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000112 return sio.getvalue()
Fred Drakea89fda01997-04-16 16:59:30 +0000113
Fred Drakee0ffabe1997-07-18 20:42:39 +0000114 def isrecursive(self, object):
Fred Drake397b6152002-12-31 07:14:18 +0000115 return self.format(object, {}, 0, 0)[2]
Fred Drakee0ffabe1997-07-18 20:42:39 +0000116
117 def isreadable(self, object):
Fred Drake397b6152002-12-31 07:14:18 +0000118 s, readable, recursive = self.format(object, {}, 0, 0)
Fred Drakeaee113d2002-04-02 05:08:35 +0000119 return readable and not recursive
Fred Drakee0ffabe1997-07-18 20:42:39 +0000120
Fred Drakee6691ef2002-07-08 12:28:06 +0000121 def _format(self, object, stream, indent, allowance, context, level):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000122 level = level + 1
Fred Drake49cc01e2001-11-01 17:50:38 +0000123 objid = _id(object)
124 if objid in context:
125 stream.write(_recursion(object))
Fred Drakee6691ef2002-07-08 12:28:06 +0000126 self._recursive = True
127 self._readable = False
Fred Drake49cc01e2001-11-01 17:50:38 +0000128 return
Fred Drakee6691ef2002-07-08 12:28:06 +0000129 rep = self._repr(object, context, level - 1)
Fred Drake49cc01e2001-11-01 17:50:38 +0000130 typ = _type(object)
Fred Drakee6691ef2002-07-08 12:28:06 +0000131 sepLines = _len(rep) > (self._width - 1 - indent - allowance)
Fred Drake49cc01e2001-11-01 17:50:38 +0000132 write = stream.write
Fred Drakea89fda01997-04-16 16:59:30 +0000133
Georg Brandl23da6e62008-05-12 16:26:52 +0000134 if self._depth and level > self._depth:
135 write(rep)
136 return
137
Georg Brandldcd6b522008-01-20 11:13:29 +0000138 r = getattr(typ, "__repr__", None)
139 if issubclass(typ, dict) and r is dict.__repr__:
140 write('{')
141 if self._indent_per_level > 1:
142 write((self._indent_per_level - 1) * ' ')
143 length = _len(object)
144 if length:
145 context[objid] = 1
146 indent = indent + self._indent_per_level
147 items = object.items()
148 items.sort()
149 key, ent = items[0]
150 rep = self._repr(key, context, level)
151 write(rep)
152 write(': ')
153 self._format(ent, stream, indent + _len(rep) + 2,
154 allowance + 1, context, level)
155 if length > 1:
156 for key, ent in items[1:]:
157 rep = self._repr(key, context, level)
158 if sepLines:
Barry Warsaw00859c02001-11-28 05:49:39 +0000159 write(',\n%s%s: ' % (' '*indent, rep))
Georg Brandldcd6b522008-01-20 11:13:29 +0000160 else:
161 write(', %s: ' % rep)
162 self._format(ent, stream, indent + _len(rep) + 2,
163 allowance + 1, context, level)
164 indent = indent - self._indent_per_level
165 del context[objid]
166 write('}')
167 return
Fred Drakea89fda01997-04-16 16:59:30 +0000168
Raymond Hettingerc226c312008-01-23 00:04:40 +0000169 if ((issubclass(typ, list) and r is list.__repr__) or
170 (issubclass(typ, tuple) and r is tuple.__repr__) or
171 (issubclass(typ, set) and r is set.__repr__) or
172 (issubclass(typ, frozenset) and r is frozenset.__repr__)
173 ):
Raymond Hettinger5310b692008-01-24 21:47:56 +0000174 length = _len(object)
Georg Brandldcd6b522008-01-20 11:13:29 +0000175 if issubclass(typ, list):
176 write('[')
177 endchar = ']'
Raymond Hettingerc226c312008-01-23 00:04:40 +0000178 elif issubclass(typ, set):
Raymond Hettinger5310b692008-01-24 21:47:56 +0000179 if not length:
180 write('set()')
181 return
Raymond Hettingerc226c312008-01-23 00:04:40 +0000182 write('set([')
183 endchar = '])'
184 object = sorted(object)
185 indent += 4
186 elif issubclass(typ, frozenset):
Raymond Hettinger5310b692008-01-24 21:47:56 +0000187 if not length:
188 write('frozenset()')
189 return
Raymond Hettingerc226c312008-01-23 00:04:40 +0000190 write('frozenset([')
191 endchar = '])'
192 object = sorted(object)
Raymond Hettinger5310b692008-01-24 21:47:56 +0000193 indent += 10
Georg Brandldcd6b522008-01-20 11:13:29 +0000194 else:
195 write('(')
196 endchar = ')'
Facundo Batista2da91c32008-06-21 17:43:56 +0000197 if self._indent_per_level > 1 and sepLines:
Georg Brandldcd6b522008-01-20 11:13:29 +0000198 write((self._indent_per_level - 1) * ' ')
Georg Brandldcd6b522008-01-20 11:13:29 +0000199 if length:
200 context[objid] = 1
201 indent = indent + self._indent_per_level
202 self._format(object[0], stream, indent, allowance + 1,
203 context, level)
204 if length > 1:
205 for ent in object[1:]:
206 if sepLines:
Fred Drake49cc01e2001-11-01 17:50:38 +0000207 write(',\n' + ' '*indent)
Georg Brandldcd6b522008-01-20 11:13:29 +0000208 else:
209 write(', ')
210 self._format(ent, stream, indent,
211 allowance + 1, context, level)
212 indent = indent - self._indent_per_level
213 del context[objid]
214 if issubclass(typ, tuple) and length == 1:
215 write(',')
216 write(endchar)
217 return
Guido van Rossum5e92aff1997-04-16 00:49:59 +0000218
Georg Brandl23da6e62008-05-12 16:26:52 +0000219 write(rep)
Georg Brandldcd6b522008-01-20 11:13:29 +0000220
Fred Drakee6691ef2002-07-08 12:28:06 +0000221 def _repr(self, object, context, level):
Fred Drakeaee113d2002-04-02 05:08:35 +0000222 repr, readable, recursive = self.format(object, context.copy(),
Fred Drakee6691ef2002-07-08 12:28:06 +0000223 self._depth, level)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000224 if not readable:
Fred Drakee6691ef2002-07-08 12:28:06 +0000225 self._readable = False
Tim Petersa814db52001-05-14 07:05:58 +0000226 if recursive:
Fred Drakee6691ef2002-07-08 12:28:06 +0000227 self._recursive = True
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000228 return repr
Guido van Rossum5e92aff1997-04-16 00:49:59 +0000229
Fred Drakeaee113d2002-04-02 05:08:35 +0000230 def format(self, object, context, maxlevels, level):
231 """Format object for a specific context, returning a string
232 and flags indicating whether the representation is 'readable'
233 and whether the object represents a recursive construct.
234 """
235 return _safe_repr(object, context, maxlevels, level)
236
237
Tim Petersa814db52001-05-14 07:05:58 +0000238# Return triple (repr_string, isreadable, isrecursive).
Guido van Rossum5e92aff1997-04-16 00:49:59 +0000239
Fred Drake49cc01e2001-11-01 17:50:38 +0000240def _safe_repr(object, context, maxlevels, level):
241 typ = _type(object)
Martin v. Löwisd02879d2003-06-07 20:47:37 +0000242 if typ is str:
Fred Drake397b6152002-12-31 07:14:18 +0000243 if 'locale' not in _sys.modules:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000244 return repr(object), True, False
Fred Drake1ef106c2001-09-04 19:43:26 +0000245 if "'" in object and '"' not in object:
246 closure = '"'
247 quotes = {'"': '\\"'}
248 else:
249 closure = "'"
250 quotes = {"'": "\\'"}
Fred Drake49cc01e2001-11-01 17:50:38 +0000251 qget = quotes.get
Fred Drake397b6152002-12-31 07:14:18 +0000252 sio = _StringIO()
Fred Drake49cc01e2001-11-01 17:50:38 +0000253 write = sio.write
Fred Drake1ef106c2001-09-04 19:43:26 +0000254 for char in object:
255 if char.isalpha():
Fred Drake49cc01e2001-11-01 17:50:38 +0000256 write(char)
Fred Drake1ef106c2001-09-04 19:43:26 +0000257 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000258 write(qget(char, repr(char)[1:-1]))
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000259 return ("%s%s%s" % (closure, sio.getvalue(), closure)), True, False
Tim Peters95b3f782001-05-14 18:39:41 +0000260
Walter Dörwald1b626ca2004-11-15 13:51:41 +0000261 r = getattr(typ, "__repr__", None)
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000262 if issubclass(typ, dict) and r is dict.__repr__:
Fred Drake49cc01e2001-11-01 17:50:38 +0000263 if not object:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000264 return "{}", True, False
Fred Drake49cc01e2001-11-01 17:50:38 +0000265 objid = _id(object)
Georg Brandl23da6e62008-05-12 16:26:52 +0000266 if maxlevels and level >= maxlevels:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000267 return "{...}", False, objid in context
Fred Drake49cc01e2001-11-01 17:50:38 +0000268 if objid in context:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000269 return _recursion(object), False, True
Fred Drake49cc01e2001-11-01 17:50:38 +0000270 context[objid] = 1
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000271 readable = True
272 recursive = False
Tim Peters95b3f782001-05-14 18:39:41 +0000273 components = []
Fred Drake49cc01e2001-11-01 17:50:38 +0000274 append = components.append
275 level += 1
276 saferepr = _safe_repr
Tim Petersd609b1a2006-06-02 23:22:51 +0000277 for k, v in sorted(object.items()):
Fred Drake49cc01e2001-11-01 17:50:38 +0000278 krepr, kreadable, krecur = saferepr(k, context, maxlevels, level)
279 vrepr, vreadable, vrecur = saferepr(v, context, maxlevels, level)
280 append("%s: %s" % (krepr, vrepr))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000281 readable = readable and kreadable and vreadable
Fred Drake49cc01e2001-11-01 17:50:38 +0000282 if krecur or vrecur:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000283 recursive = True
Fred Drake49cc01e2001-11-01 17:50:38 +0000284 del context[objid]
285 return "{%s}" % _commajoin(components), readable, recursive
Tim Peters95b3f782001-05-14 18:39:41 +0000286
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000287 if (issubclass(typ, list) and r is list.__repr__) or \
288 (issubclass(typ, tuple) and r is tuple.__repr__):
289 if issubclass(typ, list):
Fred Drake49cc01e2001-11-01 17:50:38 +0000290 if not object:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000291 return "[]", True, False
Fred Drake49cc01e2001-11-01 17:50:38 +0000292 format = "[%s]"
293 elif _len(object) == 1:
294 format = "(%s,)"
295 else:
296 if not object:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000297 return "()", True, False
Fred Drake49cc01e2001-11-01 17:50:38 +0000298 format = "(%s)"
299 objid = _id(object)
Georg Brandl23da6e62008-05-12 16:26:52 +0000300 if maxlevels and level >= maxlevels:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000301 return format % "...", False, objid in context
Fred Drake49cc01e2001-11-01 17:50:38 +0000302 if objid in context:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000303 return _recursion(object), False, True
Fred Drake49cc01e2001-11-01 17:50:38 +0000304 context[objid] = 1
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000305 readable = True
306 recursive = False
Tim Peters95b3f782001-05-14 18:39:41 +0000307 components = []
Fred Drake49cc01e2001-11-01 17:50:38 +0000308 append = components.append
309 level += 1
310 for o in object:
311 orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level)
312 append(orepr)
313 if not oreadable:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000314 readable = False
Fred Drake49cc01e2001-11-01 17:50:38 +0000315 if orecur:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000316 recursive = True
Fred Drake49cc01e2001-11-01 17:50:38 +0000317 del context[objid]
318 return format % _commajoin(components), readable, recursive
Tim Peters88768482001-11-13 21:51:26 +0000319
Walter Dörwald70a6b492004-02-12 17:35:32 +0000320 rep = repr(object)
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000321 return rep, (rep and not rep.startswith('<')), False
Tim Peters95b3f782001-05-14 18:39:41 +0000322
Guido van Rossum5e92aff1997-04-16 00:49:59 +0000323
Fred Drake49cc01e2001-11-01 17:50:38 +0000324def _recursion(object):
325 return ("<Recursion on %s with id=%s>"
326 % (_type(object).__name__, _id(object)))
Fred Drakea89fda01997-04-16 16:59:30 +0000327
Fred Drake49cc01e2001-11-01 17:50:38 +0000328
329def _perfcheck(object=None):
330 import time
331 if object is None:
332 object = [("string", (1, 2), [3, 4], {5: 6, 7: 8})] * 100000
333 p = PrettyPrinter()
334 t1 = time.time()
335 _safe_repr(object, {}, None, 0)
336 t2 = time.time()
337 p.pformat(object)
338 t3 = time.time()
339 print "_safe_repr:", t2 - t1
340 print "pformat:", t3 - t2
341
342if __name__ == "__main__":
343 _perfcheck()