Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 1 | # Author: Fred L. Drake, Jr. |
Fred Drake | 3e5e661 | 2001-10-09 20:53:48 +0000 | [diff] [blame] | 2 | # fdrake@acm.org |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 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 |
Thomas Wouters | 7e47402 | 2000-07-16 12:04:32 +0000 | [diff] [blame] | 7 | # tuples with fairly non-descriptive content. This is modeled very much |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 8 | # 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 | |
| 13 | Very simple, but useful, especially in debugging data structures. |
| 14 | |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 15 | Classes |
| 16 | ------- |
| 17 | |
| 18 | PrettyPrinter() |
| 19 | Handle pretty-printing operations onto a stream using a configured |
| 20 | set of formatting parameters. |
| 21 | |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 22 | Functions |
| 23 | --------- |
| 24 | |
| 25 | pformat() |
| 26 | Format a Python object into a pretty-printed representation. |
| 27 | |
| 28 | pprint() |
Skip Montanaro | 2dc0c13 | 2004-05-14 16:31:56 +0000 | [diff] [blame] | 29 | Pretty-print a Python object to a stream [default is sys.stdout]. |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 30 | |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 31 | saferepr() |
| 32 | Generate a 'standard' repr()-like value, but protect against recursive |
| 33 | data structures. |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 34 | |
| 35 | """ |
| 36 | |
Antoine Pitrou | 64c16c3 | 2013-03-23 20:30:39 +0100 | [diff] [blame] | 37 | import re |
Fred Drake | 397b615 | 2002-12-31 07:14:18 +0000 | [diff] [blame] | 38 | import sys as _sys |
Raymond Hettinger | bad3c88 | 2010-09-09 12:31:00 +0000 | [diff] [blame] | 39 | from collections import OrderedDict as _OrderedDict |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 40 | from io import StringIO as _StringIO |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 41 | |
Skip Montanaro | c62c81e | 2001-02-12 02:00:42 +0000 | [diff] [blame] | 42 | __all__ = ["pprint","pformat","isreadable","isrecursive","saferepr", |
| 43 | "PrettyPrinter"] |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 44 | |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 45 | |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 46 | def pprint(object, stream=None, indent=1, width=80, depth=None, *, |
| 47 | compact=False): |
Skip Montanaro | 2dc0c13 | 2004-05-14 16:31:56 +0000 | [diff] [blame] | 48 | """Pretty-print a Python object to a stream [default is sys.stdout].""" |
Walter Dörwald | c8de458 | 2003-12-03 20:26:05 +0000 | [diff] [blame] | 49 | printer = PrettyPrinter( |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 50 | stream=stream, indent=indent, width=width, depth=depth, |
| 51 | compact=compact) |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 52 | printer.pprint(object) |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 53 | |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 54 | def pformat(object, indent=1, width=80, depth=None, *, compact=False): |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 55 | """Format a Python object into a pretty-printed representation.""" |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 56 | return PrettyPrinter(indent=indent, width=width, depth=depth, |
| 57 | compact=compact).pformat(object) |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 58 | |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 59 | def saferepr(object): |
| 60 | """Version of repr() which can handle recursive data structures.""" |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 61 | return _safe_repr(object, {}, None, 0)[0] |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 62 | |
Tim Peters | a814db5 | 2001-05-14 07:05:58 +0000 | [diff] [blame] | 63 | def isreadable(object): |
| 64 | """Determine if saferepr(object) is readable by eval().""" |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 65 | return _safe_repr(object, {}, None, 0)[1] |
Tim Peters | a814db5 | 2001-05-14 07:05:58 +0000 | [diff] [blame] | 66 | |
| 67 | def isrecursive(object): |
| 68 | """Determine if object requires a recursive representation.""" |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 69 | return _safe_repr(object, {}, None, 0)[2] |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 70 | |
Raymond Hettinger | a7da166 | 2009-11-19 01:07:05 +0000 | [diff] [blame] | 71 | class _safe_key: |
| 72 | """Helper function for key functions when sorting unorderable objects. |
| 73 | |
| 74 | The wrapped-object will fallback to an Py2.x style comparison for |
| 75 | unorderable types (sorting first comparing the type name and then by |
| 76 | the obj ids). Does not work recursively, so dict.items() must have |
| 77 | _safe_key applied to both the key and the value. |
| 78 | |
| 79 | """ |
| 80 | |
| 81 | __slots__ = ['obj'] |
| 82 | |
| 83 | def __init__(self, obj): |
| 84 | self.obj = obj |
| 85 | |
| 86 | def __lt__(self, other): |
Florent Xicluna | d6da90f | 2012-07-21 11:17:38 +0200 | [diff] [blame] | 87 | try: |
| 88 | rv = self.obj.__lt__(other.obj) |
| 89 | except TypeError: |
| 90 | rv = NotImplemented |
| 91 | |
Raymond Hettinger | a7da166 | 2009-11-19 01:07:05 +0000 | [diff] [blame] | 92 | if rv is NotImplemented: |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 93 | rv = (str(type(self.obj)), id(self.obj)) < \ |
| 94 | (str(type(other.obj)), id(other.obj)) |
Raymond Hettinger | a7da166 | 2009-11-19 01:07:05 +0000 | [diff] [blame] | 95 | return rv |
| 96 | |
| 97 | def _safe_tuple(t): |
| 98 | "Helper function for comparing 2-tuples" |
| 99 | return _safe_key(t[0]), _safe_key(t[1]) |
| 100 | |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 101 | class PrettyPrinter: |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 102 | def __init__(self, indent=1, width=80, depth=None, stream=None, *, |
| 103 | compact=False): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 104 | """Handle pretty printing operations onto a stream using a set of |
| 105 | configured parameters. |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 106 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 107 | indent |
| 108 | Number of spaces to indent for each level of nesting. |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 109 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 110 | width |
| 111 | Attempted maximum number of columns in the output. |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 112 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 113 | depth |
| 114 | The maximum depth to print out nested structures. |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 115 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 116 | stream |
| 117 | The desired output stream. If omitted (or false), the standard |
| 118 | output stream available at construction will be used. |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 119 | |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 120 | compact |
| 121 | If true, several items will be combined in one line. |
| 122 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 123 | """ |
| 124 | indent = int(indent) |
| 125 | width = int(width) |
Walter Dörwald | 7a7ede5 | 2003-12-03 20:15:28 +0000 | [diff] [blame] | 126 | assert indent >= 0, "indent must be >= 0" |
Tim Peters | a814db5 | 2001-05-14 07:05:58 +0000 | [diff] [blame] | 127 | assert depth is None or depth > 0, "depth must be > 0" |
Walter Dörwald | 7a7ede5 | 2003-12-03 20:15:28 +0000 | [diff] [blame] | 128 | assert width, "width must be != 0" |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 129 | self._depth = depth |
| 130 | self._indent_per_level = indent |
| 131 | self._width = width |
Raymond Hettinger | 16e3c42 | 2002-06-01 16:07:16 +0000 | [diff] [blame] | 132 | if stream is not None: |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 133 | self._stream = stream |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 134 | else: |
Fred Drake | 397b615 | 2002-12-31 07:14:18 +0000 | [diff] [blame] | 135 | self._stream = _sys.stdout |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 136 | self._compact = bool(compact) |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 137 | |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 138 | def pprint(self, object): |
Walter Dörwald | e62e936 | 2005-11-11 18:18:51 +0000 | [diff] [blame] | 139 | self._format(object, self._stream, 0, 0, {}, 0) |
| 140 | self._stream.write("\n") |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 141 | |
| 142 | def pformat(self, object): |
Fred Drake | 397b615 | 2002-12-31 07:14:18 +0000 | [diff] [blame] | 143 | sio = _StringIO() |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 144 | self._format(object, sio, 0, 0, {}, 0) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 145 | return sio.getvalue() |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 146 | |
Fred Drake | e0ffabe | 1997-07-18 20:42:39 +0000 | [diff] [blame] | 147 | def isrecursive(self, object): |
Fred Drake | 397b615 | 2002-12-31 07:14:18 +0000 | [diff] [blame] | 148 | return self.format(object, {}, 0, 0)[2] |
Fred Drake | e0ffabe | 1997-07-18 20:42:39 +0000 | [diff] [blame] | 149 | |
| 150 | def isreadable(self, object): |
Fred Drake | 397b615 | 2002-12-31 07:14:18 +0000 | [diff] [blame] | 151 | s, readable, recursive = self.format(object, {}, 0, 0) |
Fred Drake | aee113d | 2002-04-02 05:08:35 +0000 | [diff] [blame] | 152 | return readable and not recursive |
Fred Drake | e0ffabe | 1997-07-18 20:42:39 +0000 | [diff] [blame] | 153 | |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 154 | def _format(self, object, stream, indent, allowance, context, level): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 155 | level = level + 1 |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 156 | objid = id(object) |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 157 | if objid in context: |
| 158 | stream.write(_recursion(object)) |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 159 | self._recursive = True |
| 160 | self._readable = False |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 161 | return |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 162 | rep = self._repr(object, context, level - 1) |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 163 | typ = type(object) |
Antoine Pitrou | 64c16c3 | 2013-03-23 20:30:39 +0100 | [diff] [blame] | 164 | max_width = self._width - 1 - indent - allowance |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 165 | sepLines = len(rep) > max_width |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 166 | write = stream.write |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 167 | |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 168 | if sepLines: |
Walter Dörwald | 1b626ca | 2004-11-15 13:51:41 +0000 | [diff] [blame] | 169 | r = getattr(typ, "__repr__", None) |
Raymond Hettinger | bad3c88 | 2010-09-09 12:31:00 +0000 | [diff] [blame] | 170 | if issubclass(typ, dict): |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 171 | write('{') |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 172 | if self._indent_per_level > 1: |
| 173 | write((self._indent_per_level - 1) * ' ') |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 174 | length = len(object) |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 175 | if length: |
| 176 | context[objid] = 1 |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 177 | indent = indent + self._indent_per_level |
Raymond Hettinger | bad3c88 | 2010-09-09 12:31:00 +0000 | [diff] [blame] | 178 | if issubclass(typ, _OrderedDict): |
| 179 | items = list(object.items()) |
| 180 | else: |
| 181 | items = sorted(object.items(), key=_safe_tuple) |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 182 | key, ent = items[0] |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 183 | rep = self._repr(key, context, level) |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 184 | write(rep) |
| 185 | write(': ') |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 186 | self._format(ent, stream, indent + len(rep) + 2, |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 187 | allowance + 1, context, level) |
| 188 | if length > 1: |
| 189 | for key, ent in items[1:]: |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 190 | rep = self._repr(key, context, level) |
Barry Warsaw | 00859c0 | 2001-11-28 05:49:39 +0000 | [diff] [blame] | 191 | write(',\n%s%s: ' % (' '*indent, rep)) |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 192 | self._format(ent, stream, indent + len(rep) + 2, |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 193 | allowance + 1, context, level) |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 194 | indent = indent - self._indent_per_level |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 195 | del context[objid] |
| 196 | write('}') |
| 197 | return |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 198 | |
Christian Heimes | 1af737c | 2008-01-23 08:24:23 +0000 | [diff] [blame] | 199 | if ((issubclass(typ, list) and r is list.__repr__) or |
| 200 | (issubclass(typ, tuple) and r is tuple.__repr__) or |
| 201 | (issubclass(typ, set) and r is set.__repr__) or |
| 202 | (issubclass(typ, frozenset) and r is frozenset.__repr__) |
| 203 | ): |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 204 | length = len(object) |
Walter Dörwald | 7a7ede5 | 2003-12-03 20:15:28 +0000 | [diff] [blame] | 205 | if issubclass(typ, list): |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 206 | write('[') |
| 207 | endchar = ']' |
Serhiy Storchaka | 5184438 | 2013-10-02 11:40:49 +0300 | [diff] [blame] | 208 | elif issubclass(typ, tuple): |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 209 | write('(') |
| 210 | endchar = ')' |
Serhiy Storchaka | 5184438 | 2013-10-02 11:40:49 +0300 | [diff] [blame] | 211 | else: |
| 212 | if not length: |
| 213 | write(rep) |
| 214 | return |
| 215 | if typ is set: |
| 216 | write('{') |
| 217 | endchar = '}' |
| 218 | else: |
| 219 | write(typ.__name__) |
| 220 | write('({') |
| 221 | endchar = '})' |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 222 | indent += len(typ.__name__) + 1 |
Serhiy Storchaka | 5184438 | 2013-10-02 11:40:49 +0300 | [diff] [blame] | 223 | object = sorted(object, key=_safe_key) |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 224 | if self._indent_per_level > 1: |
| 225 | write((self._indent_per_level - 1) * ' ') |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 226 | if length: |
| 227 | context[objid] = 1 |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 228 | self._format_items(object, stream, |
| 229 | indent + self._indent_per_level, |
| 230 | allowance + 1, context, level) |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 231 | del context[objid] |
Walter Dörwald | 7a7ede5 | 2003-12-03 20:15:28 +0000 | [diff] [blame] | 232 | if issubclass(typ, tuple) and length == 1: |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 233 | write(',') |
| 234 | write(endchar) |
| 235 | return |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 236 | |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 237 | if issubclass(typ, str) and len(object) > 0 and r is str.__repr__: |
Antoine Pitrou | 64c16c3 | 2013-03-23 20:30:39 +0100 | [diff] [blame] | 238 | def _str_parts(s): |
| 239 | """ |
| 240 | Return a list of string literals comprising the repr() |
| 241 | of the given string using literal concatenation. |
| 242 | """ |
| 243 | lines = s.splitlines(True) |
| 244 | for i, line in enumerate(lines): |
| 245 | rep = repr(line) |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 246 | if len(rep) <= max_width: |
Antoine Pitrou | 64c16c3 | 2013-03-23 20:30:39 +0100 | [diff] [blame] | 247 | yield rep |
| 248 | else: |
| 249 | # A list of alternating (non-space, space) strings |
| 250 | parts = re.split(r'(\s+)', line) + [''] |
| 251 | current = '' |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 252 | for i in range(0, len(parts), 2): |
Antoine Pitrou | 64c16c3 | 2013-03-23 20:30:39 +0100 | [diff] [blame] | 253 | part = parts[i] + parts[i+1] |
| 254 | candidate = current + part |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 255 | if len(repr(candidate)) > max_width: |
Antoine Pitrou | 64c16c3 | 2013-03-23 20:30:39 +0100 | [diff] [blame] | 256 | if current: |
| 257 | yield repr(current) |
| 258 | current = part |
| 259 | else: |
| 260 | current = candidate |
| 261 | if current: |
| 262 | yield repr(current) |
| 263 | for i, rep in enumerate(_str_parts(object)): |
| 264 | if i > 0: |
| 265 | write('\n' + ' '*indent) |
| 266 | write(rep) |
| 267 | return |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 268 | write(rep) |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 269 | |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 270 | def _format_items(self, items, stream, indent, allowance, context, level): |
| 271 | write = stream.write |
| 272 | delimnl = ',\n' + ' ' * indent |
| 273 | delim = '' |
| 274 | width = max_width = self._width - indent - allowance + 2 |
| 275 | for ent in items: |
| 276 | if self._compact: |
| 277 | rep = self._repr(ent, context, level) |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 278 | w = len(rep) + 2 |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 279 | if width < w: |
| 280 | width = max_width |
| 281 | if delim: |
| 282 | delim = delimnl |
| 283 | if width >= w: |
| 284 | width -= w |
| 285 | write(delim) |
| 286 | delim = ', ' |
| 287 | write(rep) |
| 288 | continue |
| 289 | write(delim) |
| 290 | delim = delimnl |
| 291 | self._format(ent, stream, indent, allowance, context, level) |
| 292 | |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 293 | def _repr(self, object, context, level): |
Fred Drake | aee113d | 2002-04-02 05:08:35 +0000 | [diff] [blame] | 294 | repr, readable, recursive = self.format(object, context.copy(), |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 295 | self._depth, level) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 296 | if not readable: |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 297 | self._readable = False |
Tim Peters | a814db5 | 2001-05-14 07:05:58 +0000 | [diff] [blame] | 298 | if recursive: |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 299 | self._recursive = True |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 300 | return repr |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 301 | |
Fred Drake | aee113d | 2002-04-02 05:08:35 +0000 | [diff] [blame] | 302 | def format(self, object, context, maxlevels, level): |
| 303 | """Format object for a specific context, returning a string |
| 304 | and flags indicating whether the representation is 'readable' |
| 305 | and whether the object represents a recursive construct. |
| 306 | """ |
| 307 | return _safe_repr(object, context, maxlevels, level) |
| 308 | |
| 309 | |
Tim Peters | a814db5 | 2001-05-14 07:05:58 +0000 | [diff] [blame] | 310 | # Return triple (repr_string, isreadable, isrecursive). |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 311 | |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 312 | def _safe_repr(object, context, maxlevels, level): |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 313 | typ = type(object) |
Martin v. Löwis | d02879d | 2003-06-07 20:47:37 +0000 | [diff] [blame] | 314 | if typ is str: |
Fred Drake | 397b615 | 2002-12-31 07:14:18 +0000 | [diff] [blame] | 315 | if 'locale' not in _sys.modules: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 316 | return repr(object), True, False |
Fred Drake | 1ef106c | 2001-09-04 19:43:26 +0000 | [diff] [blame] | 317 | if "'" in object and '"' not in object: |
| 318 | closure = '"' |
| 319 | quotes = {'"': '\\"'} |
| 320 | else: |
| 321 | closure = "'" |
| 322 | quotes = {"'": "\\'"} |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 323 | qget = quotes.get |
Fred Drake | 397b615 | 2002-12-31 07:14:18 +0000 | [diff] [blame] | 324 | sio = _StringIO() |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 325 | write = sio.write |
Fred Drake | 1ef106c | 2001-09-04 19:43:26 +0000 | [diff] [blame] | 326 | for char in object: |
| 327 | if char.isalpha(): |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 328 | write(char) |
Fred Drake | 1ef106c | 2001-09-04 19:43:26 +0000 | [diff] [blame] | 329 | else: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 330 | write(qget(char, repr(char)[1:-1])) |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 331 | return ("%s%s%s" % (closure, sio.getvalue(), closure)), True, False |
Tim Peters | 95b3f78 | 2001-05-14 18:39:41 +0000 | [diff] [blame] | 332 | |
Walter Dörwald | 1b626ca | 2004-11-15 13:51:41 +0000 | [diff] [blame] | 333 | r = getattr(typ, "__repr__", None) |
Walter Dörwald | 7a7ede5 | 2003-12-03 20:15:28 +0000 | [diff] [blame] | 334 | if issubclass(typ, dict) and r is dict.__repr__: |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 335 | if not object: |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 336 | return "{}", True, False |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 337 | objid = id(object) |
Alexandre Vassalotti | eca20b6 | 2008-05-16 02:54:33 +0000 | [diff] [blame] | 338 | if maxlevels and level >= maxlevels: |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 339 | return "{...}", False, objid in context |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 340 | if objid in context: |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 341 | return _recursion(object), False, True |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 342 | context[objid] = 1 |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 343 | readable = True |
| 344 | recursive = False |
Tim Peters | 95b3f78 | 2001-05-14 18:39:41 +0000 | [diff] [blame] | 345 | components = [] |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 346 | append = components.append |
| 347 | level += 1 |
| 348 | saferepr = _safe_repr |
Raymond Hettinger | a7da166 | 2009-11-19 01:07:05 +0000 | [diff] [blame] | 349 | items = sorted(object.items(), key=_safe_tuple) |
Guido van Rossum | 47b9ff6 | 2006-08-24 00:41:19 +0000 | [diff] [blame] | 350 | for k, v in items: |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 351 | krepr, kreadable, krecur = saferepr(k, context, maxlevels, level) |
| 352 | vrepr, vreadable, vrecur = saferepr(v, context, maxlevels, level) |
| 353 | append("%s: %s" % (krepr, vrepr)) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 354 | readable = readable and kreadable and vreadable |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 355 | if krecur or vrecur: |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 356 | recursive = True |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 357 | del context[objid] |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 358 | return "{%s}" % ", ".join(components), readable, recursive |
Tim Peters | 95b3f78 | 2001-05-14 18:39:41 +0000 | [diff] [blame] | 359 | |
Walter Dörwald | 7a7ede5 | 2003-12-03 20:15:28 +0000 | [diff] [blame] | 360 | if (issubclass(typ, list) and r is list.__repr__) or \ |
| 361 | (issubclass(typ, tuple) and r is tuple.__repr__): |
| 362 | if issubclass(typ, list): |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 363 | if not object: |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 364 | return "[]", True, False |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 365 | format = "[%s]" |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 366 | elif len(object) == 1: |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 367 | format = "(%s,)" |
| 368 | else: |
| 369 | if not object: |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 370 | return "()", True, False |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 371 | format = "(%s)" |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 372 | objid = id(object) |
Alexandre Vassalotti | eca20b6 | 2008-05-16 02:54:33 +0000 | [diff] [blame] | 373 | if maxlevels and level >= maxlevels: |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 374 | return format % "...", False, objid in context |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 375 | if objid in context: |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 376 | return _recursion(object), False, True |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 377 | context[objid] = 1 |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 378 | readable = True |
| 379 | recursive = False |
Tim Peters | 95b3f78 | 2001-05-14 18:39:41 +0000 | [diff] [blame] | 380 | components = [] |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 381 | append = components.append |
| 382 | level += 1 |
| 383 | for o in object: |
| 384 | orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level) |
| 385 | append(orepr) |
| 386 | if not oreadable: |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 387 | readable = False |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 388 | if orecur: |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 389 | recursive = True |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 390 | del context[objid] |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 391 | return format % ", ".join(components), readable, recursive |
Tim Peters | 8876848 | 2001-11-13 21:51:26 +0000 | [diff] [blame] | 392 | |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 393 | rep = repr(object) |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 394 | return rep, (rep and not rep.startswith('<')), False |
Tim Peters | 95b3f78 | 2001-05-14 18:39:41 +0000 | [diff] [blame] | 395 | |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 396 | |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 397 | def _recursion(object): |
| 398 | return ("<Recursion on %s with id=%s>" |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame^] | 399 | % (type(object).__name__, id(object))) |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 400 | |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 401 | |
| 402 | def _perfcheck(object=None): |
| 403 | import time |
| 404 | if object is None: |
| 405 | object = [("string", (1, 2), [3, 4], {5: 6, 7: 8})] * 100000 |
| 406 | p = PrettyPrinter() |
| 407 | t1 = time.time() |
| 408 | _safe_repr(object, {}, None, 0) |
| 409 | t2 = time.time() |
| 410 | p.pformat(object) |
| 411 | t3 = time.time() |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 412 | print("_safe_repr:", t2 - t1) |
| 413 | print("pformat:", t3 - t2) |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 414 | |
| 415 | if __name__ == "__main__": |
| 416 | _perfcheck() |