blob: 910283e60913e3c209d0d9d4ed799796155bad31 [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
Antoine Pitroub9d49632010-01-04 23:22:44 +000038import warnings
Guido van Rossum5e92aff1997-04-16 00:49:59 +000039
Fred Drake397b6152002-12-31 07:14:18 +000040from cStringIO import StringIO as _StringIO
Guido van Rossum5e92aff1997-04-16 00:49:59 +000041
Skip Montanaroc62c81e2001-02-12 02:00:42 +000042__all__ = ["pprint","pformat","isreadable","isrecursive","saferepr",
43 "PrettyPrinter"]
Guido van Rossum5e92aff1997-04-16 00:49:59 +000044
Fred Drake49cc01e2001-11-01 17:50:38 +000045# cache these for faster access:
46_commajoin = ", ".join
Fred Drake49cc01e2001-11-01 17:50:38 +000047_id = id
48_len = len
49_type = type
50
51
Walter Dörwaldc8de4582003-12-03 20:26:05 +000052def pprint(object, stream=None, indent=1, width=80, depth=None):
Skip Montanaro2dc0c132004-05-14 16:31:56 +000053 """Pretty-print a Python object to a stream [default is sys.stdout]."""
Walter Dörwaldc8de4582003-12-03 20:26:05 +000054 printer = PrettyPrinter(
55 stream=stream, indent=indent, width=width, depth=depth)
Fred Drakea89fda01997-04-16 16:59:30 +000056 printer.pprint(object)
Guido van Rossum5e92aff1997-04-16 00:49:59 +000057
Walter Dörwaldc8de4582003-12-03 20:26:05 +000058def pformat(object, indent=1, width=80, depth=None):
Fred Drakea89fda01997-04-16 16:59:30 +000059 """Format a Python object into a pretty-printed representation."""
Walter Dörwaldc8de4582003-12-03 20:26:05 +000060 return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
Guido van Rossum5e92aff1997-04-16 00:49:59 +000061
Fred Drakea89fda01997-04-16 16:59:30 +000062def saferepr(object):
63 """Version of repr() which can handle recursive data structures."""
Fred Drake49cc01e2001-11-01 17:50:38 +000064 return _safe_repr(object, {}, None, 0)[0]
Guido van Rossum5e92aff1997-04-16 00:49:59 +000065
Tim Petersa814db52001-05-14 07:05:58 +000066def isreadable(object):
67 """Determine if saferepr(object) is readable by eval()."""
Fred Drake49cc01e2001-11-01 17:50:38 +000068 return _safe_repr(object, {}, None, 0)[1]
Tim Petersa814db52001-05-14 07:05:58 +000069
70def isrecursive(object):
71 """Determine if object requires a recursive representation."""
Fred Drake49cc01e2001-11-01 17:50:38 +000072 return _safe_repr(object, {}, None, 0)[2]
Guido van Rossum5e92aff1997-04-16 00:49:59 +000073
Antoine Pitroub9d49632010-01-04 23:22:44 +000074def _sorted(iterable):
75 with warnings.catch_warnings():
76 if _sys.py3kwarning:
77 warnings.filterwarnings("ignore", "comparing unequal types "
78 "not supported", DeprecationWarning)
79 return sorted(iterable)
80
Fred Drakea89fda01997-04-16 16:59:30 +000081class PrettyPrinter:
82 def __init__(self, indent=1, width=80, depth=None, stream=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000083 """Handle pretty printing operations onto a stream using a set of
84 configured parameters.
Guido van Rossum5e92aff1997-04-16 00:49:59 +000085
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000086 indent
87 Number of spaces to indent for each level of nesting.
Guido van Rossum5e92aff1997-04-16 00:49:59 +000088
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000089 width
90 Attempted maximum number of columns in the output.
Guido van Rossum5e92aff1997-04-16 00:49:59 +000091
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000092 depth
93 The maximum depth to print out nested structures.
Guido van Rossum5e92aff1997-04-16 00:49:59 +000094
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000095 stream
96 The desired output stream. If omitted (or false), the standard
97 output stream available at construction will be used.
Guido van Rossum5e92aff1997-04-16 00:49:59 +000098
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000099 """
100 indent = int(indent)
101 width = int(width)
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000102 assert indent >= 0, "indent must be >= 0"
Tim Petersa814db52001-05-14 07:05:58 +0000103 assert depth is None or depth > 0, "depth must be > 0"
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000104 assert width, "width must be != 0"
Fred Drakee6691ef2002-07-08 12:28:06 +0000105 self._depth = depth
106 self._indent_per_level = indent
107 self._width = width
Raymond Hettinger16e3c422002-06-01 16:07:16 +0000108 if stream is not None:
Fred Drakee6691ef2002-07-08 12:28:06 +0000109 self._stream = stream
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000110 else:
Fred Drake397b6152002-12-31 07:14:18 +0000111 self._stream = _sys.stdout
Guido van Rossum5e92aff1997-04-16 00:49:59 +0000112
Fred Drakea89fda01997-04-16 16:59:30 +0000113 def pprint(self, object):
Walter Dörwalde62e9362005-11-11 18:18:51 +0000114 self._format(object, self._stream, 0, 0, {}, 0)
115 self._stream.write("\n")
Fred Drakea89fda01997-04-16 16:59:30 +0000116
117 def pformat(self, object):
Fred Drake397b6152002-12-31 07:14:18 +0000118 sio = _StringIO()
Fred Drakee6691ef2002-07-08 12:28:06 +0000119 self._format(object, sio, 0, 0, {}, 0)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000120 return sio.getvalue()
Fred Drakea89fda01997-04-16 16:59:30 +0000121
Fred Drakee0ffabe1997-07-18 20:42:39 +0000122 def isrecursive(self, object):
Fred Drake397b6152002-12-31 07:14:18 +0000123 return self.format(object, {}, 0, 0)[2]
Fred Drakee0ffabe1997-07-18 20:42:39 +0000124
125 def isreadable(self, object):
Fred Drake397b6152002-12-31 07:14:18 +0000126 s, readable, recursive = self.format(object, {}, 0, 0)
Fred Drakeaee113d2002-04-02 05:08:35 +0000127 return readable and not recursive
Fred Drakee0ffabe1997-07-18 20:42:39 +0000128
Fred Drakee6691ef2002-07-08 12:28:06 +0000129 def _format(self, object, stream, indent, allowance, context, level):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000130 level = level + 1
Fred Drake49cc01e2001-11-01 17:50:38 +0000131 objid = _id(object)
132 if objid in context:
133 stream.write(_recursion(object))
Fred Drakee6691ef2002-07-08 12:28:06 +0000134 self._recursive = True
135 self._readable = False
Fred Drake49cc01e2001-11-01 17:50:38 +0000136 return
Fred Drakee6691ef2002-07-08 12:28:06 +0000137 rep = self._repr(object, context, level - 1)
Fred Drake49cc01e2001-11-01 17:50:38 +0000138 typ = _type(object)
Fred Drakee6691ef2002-07-08 12:28:06 +0000139 sepLines = _len(rep) > (self._width - 1 - indent - allowance)
Fred Drake49cc01e2001-11-01 17:50:38 +0000140 write = stream.write
Fred Drakea89fda01997-04-16 16:59:30 +0000141
Georg Brandl23da6e62008-05-12 16:26:52 +0000142 if self._depth and level > self._depth:
143 write(rep)
144 return
145
Georg Brandldcd6b522008-01-20 11:13:29 +0000146 r = getattr(typ, "__repr__", None)
147 if issubclass(typ, dict) and r is dict.__repr__:
148 write('{')
149 if self._indent_per_level > 1:
150 write((self._indent_per_level - 1) * ' ')
151 length = _len(object)
152 if length:
153 context[objid] = 1
154 indent = indent + self._indent_per_level
Antoine Pitroub9d49632010-01-04 23:22:44 +0000155 items = _sorted(object.items())
Georg Brandldcd6b522008-01-20 11:13:29 +0000156 key, ent = items[0]
157 rep = self._repr(key, context, level)
158 write(rep)
159 write(': ')
160 self._format(ent, stream, indent + _len(rep) + 2,
161 allowance + 1, context, level)
162 if length > 1:
163 for key, ent in items[1:]:
164 rep = self._repr(key, context, level)
165 if sepLines:
Barry Warsaw00859c02001-11-28 05:49:39 +0000166 write(',\n%s%s: ' % (' '*indent, rep))
Georg Brandldcd6b522008-01-20 11:13:29 +0000167 else:
168 write(', %s: ' % rep)
169 self._format(ent, stream, indent + _len(rep) + 2,
170 allowance + 1, context, level)
171 indent = indent - self._indent_per_level
172 del context[objid]
173 write('}')
174 return
Fred Drakea89fda01997-04-16 16:59:30 +0000175
Raymond Hettingerc226c312008-01-23 00:04:40 +0000176 if ((issubclass(typ, list) and r is list.__repr__) or
177 (issubclass(typ, tuple) and r is tuple.__repr__) or
178 (issubclass(typ, set) and r is set.__repr__) or
179 (issubclass(typ, frozenset) and r is frozenset.__repr__)
180 ):
Raymond Hettinger5310b692008-01-24 21:47:56 +0000181 length = _len(object)
Georg Brandldcd6b522008-01-20 11:13:29 +0000182 if issubclass(typ, list):
183 write('[')
184 endchar = ']'
Raymond Hettingerc226c312008-01-23 00:04:40 +0000185 elif issubclass(typ, set):
Raymond Hettinger5310b692008-01-24 21:47:56 +0000186 if not length:
187 write('set()')
188 return
Raymond Hettingerc226c312008-01-23 00:04:40 +0000189 write('set([')
190 endchar = '])'
Antoine Pitroub9d49632010-01-04 23:22:44 +0000191 object = _sorted(object)
Raymond Hettingerc226c312008-01-23 00:04:40 +0000192 indent += 4
193 elif issubclass(typ, frozenset):
Raymond Hettinger5310b692008-01-24 21:47:56 +0000194 if not length:
195 write('frozenset()')
196 return
Raymond Hettingerc226c312008-01-23 00:04:40 +0000197 write('frozenset([')
198 endchar = '])'
Antoine Pitroub9d49632010-01-04 23:22:44 +0000199 object = _sorted(object)
Raymond Hettinger5310b692008-01-24 21:47:56 +0000200 indent += 10
Georg Brandldcd6b522008-01-20 11:13:29 +0000201 else:
202 write('(')
203 endchar = ')'
Facundo Batista2da91c32008-06-21 17:43:56 +0000204 if self._indent_per_level > 1 and sepLines:
Georg Brandldcd6b522008-01-20 11:13:29 +0000205 write((self._indent_per_level - 1) * ' ')
Georg Brandldcd6b522008-01-20 11:13:29 +0000206 if length:
207 context[objid] = 1
208 indent = indent + self._indent_per_level
209 self._format(object[0], stream, indent, allowance + 1,
210 context, level)
211 if length > 1:
212 for ent in object[1:]:
213 if sepLines:
Fred Drake49cc01e2001-11-01 17:50:38 +0000214 write(',\n' + ' '*indent)
Georg Brandldcd6b522008-01-20 11:13:29 +0000215 else:
216 write(', ')
217 self._format(ent, stream, indent,
218 allowance + 1, context, level)
219 indent = indent - self._indent_per_level
220 del context[objid]
221 if issubclass(typ, tuple) and length == 1:
222 write(',')
223 write(endchar)
224 return
Guido van Rossum5e92aff1997-04-16 00:49:59 +0000225
Georg Brandl23da6e62008-05-12 16:26:52 +0000226 write(rep)
Georg Brandldcd6b522008-01-20 11:13:29 +0000227
Fred Drakee6691ef2002-07-08 12:28:06 +0000228 def _repr(self, object, context, level):
Fred Drakeaee113d2002-04-02 05:08:35 +0000229 repr, readable, recursive = self.format(object, context.copy(),
Fred Drakee6691ef2002-07-08 12:28:06 +0000230 self._depth, level)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000231 if not readable:
Fred Drakee6691ef2002-07-08 12:28:06 +0000232 self._readable = False
Tim Petersa814db52001-05-14 07:05:58 +0000233 if recursive:
Fred Drakee6691ef2002-07-08 12:28:06 +0000234 self._recursive = True
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000235 return repr
Guido van Rossum5e92aff1997-04-16 00:49:59 +0000236
Fred Drakeaee113d2002-04-02 05:08:35 +0000237 def format(self, object, context, maxlevels, level):
238 """Format object for a specific context, returning a string
239 and flags indicating whether the representation is 'readable'
240 and whether the object represents a recursive construct.
241 """
242 return _safe_repr(object, context, maxlevels, level)
243
244
Tim Petersa814db52001-05-14 07:05:58 +0000245# Return triple (repr_string, isreadable, isrecursive).
Guido van Rossum5e92aff1997-04-16 00:49:59 +0000246
Fred Drake49cc01e2001-11-01 17:50:38 +0000247def _safe_repr(object, context, maxlevels, level):
248 typ = _type(object)
Martin v. Löwisd02879d2003-06-07 20:47:37 +0000249 if typ is str:
Fred Drake397b6152002-12-31 07:14:18 +0000250 if 'locale' not in _sys.modules:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000251 return repr(object), True, False
Fred Drake1ef106c2001-09-04 19:43:26 +0000252 if "'" in object and '"' not in object:
253 closure = '"'
254 quotes = {'"': '\\"'}
255 else:
256 closure = "'"
257 quotes = {"'": "\\'"}
Fred Drake49cc01e2001-11-01 17:50:38 +0000258 qget = quotes.get
Fred Drake397b6152002-12-31 07:14:18 +0000259 sio = _StringIO()
Fred Drake49cc01e2001-11-01 17:50:38 +0000260 write = sio.write
Fred Drake1ef106c2001-09-04 19:43:26 +0000261 for char in object:
262 if char.isalpha():
Fred Drake49cc01e2001-11-01 17:50:38 +0000263 write(char)
Fred Drake1ef106c2001-09-04 19:43:26 +0000264 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000265 write(qget(char, repr(char)[1:-1]))
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000266 return ("%s%s%s" % (closure, sio.getvalue(), closure)), True, False
Tim Peters95b3f782001-05-14 18:39:41 +0000267
Walter Dörwald1b626ca2004-11-15 13:51:41 +0000268 r = getattr(typ, "__repr__", None)
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000269 if issubclass(typ, dict) and r is dict.__repr__:
Fred Drake49cc01e2001-11-01 17:50:38 +0000270 if not object:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000271 return "{}", True, False
Fred Drake49cc01e2001-11-01 17:50:38 +0000272 objid = _id(object)
Georg Brandl23da6e62008-05-12 16:26:52 +0000273 if maxlevels and level >= maxlevels:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000274 return "{...}", False, objid in context
Fred Drake49cc01e2001-11-01 17:50:38 +0000275 if objid in context:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000276 return _recursion(object), False, True
Fred Drake49cc01e2001-11-01 17:50:38 +0000277 context[objid] = 1
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000278 readable = True
279 recursive = False
Tim Peters95b3f782001-05-14 18:39:41 +0000280 components = []
Fred Drake49cc01e2001-11-01 17:50:38 +0000281 append = components.append
282 level += 1
283 saferepr = _safe_repr
Antoine Pitroub9d49632010-01-04 23:22:44 +0000284 for k, v in _sorted(object.items()):
Fred Drake49cc01e2001-11-01 17:50:38 +0000285 krepr, kreadable, krecur = saferepr(k, context, maxlevels, level)
286 vrepr, vreadable, vrecur = saferepr(v, context, maxlevels, level)
287 append("%s: %s" % (krepr, vrepr))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000288 readable = readable and kreadable and vreadable
Fred Drake49cc01e2001-11-01 17:50:38 +0000289 if krecur or vrecur:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000290 recursive = True
Fred Drake49cc01e2001-11-01 17:50:38 +0000291 del context[objid]
292 return "{%s}" % _commajoin(components), readable, recursive
Tim Peters95b3f782001-05-14 18:39:41 +0000293
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000294 if (issubclass(typ, list) and r is list.__repr__) or \
295 (issubclass(typ, tuple) and r is tuple.__repr__):
296 if issubclass(typ, list):
Fred Drake49cc01e2001-11-01 17:50:38 +0000297 if not object:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000298 return "[]", True, False
Fred Drake49cc01e2001-11-01 17:50:38 +0000299 format = "[%s]"
300 elif _len(object) == 1:
301 format = "(%s,)"
302 else:
303 if not object:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000304 return "()", True, False
Fred Drake49cc01e2001-11-01 17:50:38 +0000305 format = "(%s)"
306 objid = _id(object)
Georg Brandl23da6e62008-05-12 16:26:52 +0000307 if maxlevels and level >= maxlevels:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000308 return format % "...", False, objid in context
Fred Drake49cc01e2001-11-01 17:50:38 +0000309 if objid in context:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000310 return _recursion(object), False, True
Fred Drake49cc01e2001-11-01 17:50:38 +0000311 context[objid] = 1
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000312 readable = True
313 recursive = False
Tim Peters95b3f782001-05-14 18:39:41 +0000314 components = []
Fred Drake49cc01e2001-11-01 17:50:38 +0000315 append = components.append
316 level += 1
317 for o in object:
318 orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level)
319 append(orepr)
320 if not oreadable:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000321 readable = False
Fred Drake49cc01e2001-11-01 17:50:38 +0000322 if orecur:
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000323 recursive = True
Fred Drake49cc01e2001-11-01 17:50:38 +0000324 del context[objid]
325 return format % _commajoin(components), readable, recursive
Tim Peters88768482001-11-13 21:51:26 +0000326
Walter Dörwald70a6b492004-02-12 17:35:32 +0000327 rep = repr(object)
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000328 return rep, (rep and not rep.startswith('<')), False
Tim Peters95b3f782001-05-14 18:39:41 +0000329
Guido van Rossum5e92aff1997-04-16 00:49:59 +0000330
Fred Drake49cc01e2001-11-01 17:50:38 +0000331def _recursion(object):
332 return ("<Recursion on %s with id=%s>"
333 % (_type(object).__name__, _id(object)))
Fred Drakea89fda01997-04-16 16:59:30 +0000334
Fred Drake49cc01e2001-11-01 17:50:38 +0000335
336def _perfcheck(object=None):
337 import time
338 if object is None:
339 object = [("string", (1, 2), [3, 4], {5: 6, 7: 8})] * 100000
340 p = PrettyPrinter()
341 t1 = time.time()
342 _safe_repr(object, {}, None, 0)
343 t2 = time.time()
344 p.pformat(object)
345 t3 = time.time()
346 print "_safe_repr:", t2 - t1
347 print "pformat:", t3 - t2
348
349if __name__ == "__main__":
350 _perfcheck()