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 | |
Serhiy Storchaka | aa4c36f | 2015-03-26 08:51:33 +0200 | [diff] [blame] | 37 | import collections as _collections |
Antoine Pitrou | 64c16c3 | 2013-03-23 20:30:39 +0100 | [diff] [blame] | 38 | import re |
Fred Drake | 397b615 | 2002-12-31 07:14:18 +0000 | [diff] [blame] | 39 | import sys as _sys |
Serhiy Storchaka | 87eb482 | 2015-03-24 19:31:50 +0200 | [diff] [blame] | 40 | import types as _types |
Guido van Rossum | 34d1928 | 2007-08-09 01:03:29 +0000 | [diff] [blame] | 41 | from io import StringIO as _StringIO |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 42 | |
Skip Montanaro | c62c81e | 2001-02-12 02:00:42 +0000 | [diff] [blame] | 43 | __all__ = ["pprint","pformat","isreadable","isrecursive","saferepr", |
Rémi Lapeyre | 96831c7 | 2019-03-22 18:22:20 +0100 | [diff] [blame] | 44 | "PrettyPrinter", "pp"] |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 45 | |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 46 | |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 47 | def pprint(object, stream=None, indent=1, width=80, depth=None, *, |
sblondon | 3ba3d51 | 2021-03-24 09:23:20 +0100 | [diff] [blame] | 48 | compact=False, sort_dicts=True, underscore_numbers=False): |
Skip Montanaro | 2dc0c13 | 2004-05-14 16:31:56 +0000 | [diff] [blame] | 49 | """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] | 50 | printer = PrettyPrinter( |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 51 | stream=stream, indent=indent, width=width, depth=depth, |
sblondon | 3ba3d51 | 2021-03-24 09:23:20 +0100 | [diff] [blame] | 52 | compact=compact, sort_dicts=sort_dicts, underscore_numbers=False) |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 53 | printer.pprint(object) |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 54 | |
Rémi Lapeyre | 96831c7 | 2019-03-22 18:22:20 +0100 | [diff] [blame] | 55 | def pformat(object, indent=1, width=80, depth=None, *, |
sblondon | 3ba3d51 | 2021-03-24 09:23:20 +0100 | [diff] [blame] | 56 | compact=False, sort_dicts=True, underscore_numbers=False): |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 57 | """Format a Python object into a pretty-printed representation.""" |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 58 | return PrettyPrinter(indent=indent, width=width, depth=depth, |
sblondon | 3ba3d51 | 2021-03-24 09:23:20 +0100 | [diff] [blame] | 59 | compact=compact, sort_dicts=sort_dicts, |
| 60 | underscore_numbers=underscore_numbers).pformat(object) |
Rémi Lapeyre | 96831c7 | 2019-03-22 18:22:20 +0100 | [diff] [blame] | 61 | |
| 62 | def pp(object, *args, sort_dicts=False, **kwargs): |
| 63 | """Pretty-print a Python object""" |
| 64 | pprint(object, *args, sort_dicts=sort_dicts, **kwargs) |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 65 | |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 66 | def saferepr(object): |
| 67 | """Version of repr() which can handle recursive data structures.""" |
Irit Katriel | ff420f0 | 2020-11-23 13:31:31 +0000 | [diff] [blame] | 68 | return PrettyPrinter()._safe_repr(object, {}, None, 0)[0] |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 69 | |
Tim Peters | a814db5 | 2001-05-14 07:05:58 +0000 | [diff] [blame] | 70 | def isreadable(object): |
| 71 | """Determine if saferepr(object) is readable by eval().""" |
Irit Katriel | ff420f0 | 2020-11-23 13:31:31 +0000 | [diff] [blame] | 72 | return PrettyPrinter()._safe_repr(object, {}, None, 0)[1] |
Tim Peters | a814db5 | 2001-05-14 07:05:58 +0000 | [diff] [blame] | 73 | |
| 74 | def isrecursive(object): |
| 75 | """Determine if object requires a recursive representation.""" |
Irit Katriel | ff420f0 | 2020-11-23 13:31:31 +0000 | [diff] [blame] | 76 | return PrettyPrinter()._safe_repr(object, {}, None, 0)[2] |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 77 | |
Raymond Hettinger | a7da166 | 2009-11-19 01:07:05 +0000 | [diff] [blame] | 78 | class _safe_key: |
| 79 | """Helper function for key functions when sorting unorderable objects. |
| 80 | |
Serhiy Storchaka | 6a7b3a7 | 2016-04-17 08:32:47 +0300 | [diff] [blame] | 81 | The wrapped-object will fallback to a Py2.x style comparison for |
Raymond Hettinger | a7da166 | 2009-11-19 01:07:05 +0000 | [diff] [blame] | 82 | unorderable types (sorting first comparing the type name and then by |
| 83 | the obj ids). Does not work recursively, so dict.items() must have |
| 84 | _safe_key applied to both the key and the value. |
| 85 | |
| 86 | """ |
| 87 | |
| 88 | __slots__ = ['obj'] |
| 89 | |
| 90 | def __init__(self, obj): |
| 91 | self.obj = obj |
| 92 | |
| 93 | def __lt__(self, other): |
Florent Xicluna | d6da90f | 2012-07-21 11:17:38 +0200 | [diff] [blame] | 94 | try: |
Serhiy Storchaka | 62aa7dc | 2015-04-06 22:52:44 +0300 | [diff] [blame] | 95 | return self.obj < other.obj |
Florent Xicluna | d6da90f | 2012-07-21 11:17:38 +0200 | [diff] [blame] | 96 | except TypeError: |
Serhiy Storchaka | 62aa7dc | 2015-04-06 22:52:44 +0300 | [diff] [blame] | 97 | return ((str(type(self.obj)), id(self.obj)) < \ |
| 98 | (str(type(other.obj)), id(other.obj))) |
Raymond Hettinger | a7da166 | 2009-11-19 01:07:05 +0000 | [diff] [blame] | 99 | |
| 100 | def _safe_tuple(t): |
| 101 | "Helper function for comparing 2-tuples" |
| 102 | return _safe_key(t[0]), _safe_key(t[1]) |
| 103 | |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 104 | class PrettyPrinter: |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 105 | def __init__(self, indent=1, width=80, depth=None, stream=None, *, |
sblondon | 3ba3d51 | 2021-03-24 09:23:20 +0100 | [diff] [blame] | 106 | compact=False, sort_dicts=True, underscore_numbers=False): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 107 | """Handle pretty printing operations onto a stream using a set of |
| 108 | configured parameters. |
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 | indent |
| 111 | Number of spaces to indent for each level of nesting. |
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 | width |
| 114 | Attempted maximum number of columns in the output. |
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 | depth |
| 117 | The maximum depth to print out nested structures. |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 118 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 119 | stream |
| 120 | The desired output stream. If omitted (or false), the standard |
| 121 | output stream available at construction will be used. |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 122 | |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 123 | compact |
| 124 | If true, several items will be combined in one line. |
| 125 | |
Rémi Lapeyre | 96831c7 | 2019-03-22 18:22:20 +0100 | [diff] [blame] | 126 | sort_dicts |
| 127 | If true, dict keys are sorted. |
| 128 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 129 | """ |
| 130 | indent = int(indent) |
| 131 | width = int(width) |
Serhiy Storchaka | f3fa308 | 2015-03-26 08:43:21 +0200 | [diff] [blame] | 132 | if indent < 0: |
| 133 | raise ValueError('indent must be >= 0') |
| 134 | if depth is not None and depth <= 0: |
| 135 | raise ValueError('depth must be > 0') |
| 136 | if not width: |
| 137 | raise ValueError('width must be != 0') |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 138 | self._depth = depth |
| 139 | self._indent_per_level = indent |
| 140 | self._width = width |
Raymond Hettinger | 16e3c42 | 2002-06-01 16:07:16 +0000 | [diff] [blame] | 141 | if stream is not None: |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 142 | self._stream = stream |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 143 | else: |
Fred Drake | 397b615 | 2002-12-31 07:14:18 +0000 | [diff] [blame] | 144 | self._stream = _sys.stdout |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 145 | self._compact = bool(compact) |
Rémi Lapeyre | 96831c7 | 2019-03-22 18:22:20 +0100 | [diff] [blame] | 146 | self._sort_dicts = sort_dicts |
sblondon | 3ba3d51 | 2021-03-24 09:23:20 +0100 | [diff] [blame] | 147 | self._underscore_numbers = underscore_numbers |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 148 | |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 149 | def pprint(self, object): |
Walter Dörwald | e62e936 | 2005-11-11 18:18:51 +0000 | [diff] [blame] | 150 | self._format(object, self._stream, 0, 0, {}, 0) |
| 151 | self._stream.write("\n") |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 152 | |
| 153 | def pformat(self, object): |
Fred Drake | 397b615 | 2002-12-31 07:14:18 +0000 | [diff] [blame] | 154 | sio = _StringIO() |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 155 | self._format(object, sio, 0, 0, {}, 0) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 156 | return sio.getvalue() |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 157 | |
Fred Drake | e0ffabe | 1997-07-18 20:42:39 +0000 | [diff] [blame] | 158 | def isrecursive(self, object): |
Fred Drake | 397b615 | 2002-12-31 07:14:18 +0000 | [diff] [blame] | 159 | return self.format(object, {}, 0, 0)[2] |
Fred Drake | e0ffabe | 1997-07-18 20:42:39 +0000 | [diff] [blame] | 160 | |
| 161 | def isreadable(self, object): |
Fred Drake | 397b615 | 2002-12-31 07:14:18 +0000 | [diff] [blame] | 162 | s, readable, recursive = self.format(object, {}, 0, 0) |
Fred Drake | aee113d | 2002-04-02 05:08:35 +0000 | [diff] [blame] | 163 | return readable and not recursive |
Fred Drake | e0ffabe | 1997-07-18 20:42:39 +0000 | [diff] [blame] | 164 | |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 165 | def _format(self, object, stream, indent, allowance, context, level): |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame] | 166 | objid = id(object) |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 167 | if objid in context: |
| 168 | stream.write(_recursion(object)) |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 169 | self._recursive = True |
| 170 | self._readable = False |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 171 | return |
Serhiy Storchaka | 8e2aa88 | 2015-03-24 18:45:23 +0200 | [diff] [blame] | 172 | rep = self._repr(object, context, level) |
Serhiy Storchaka | a750ce3 | 2015-02-14 10:55:19 +0200 | [diff] [blame] | 173 | max_width = self._width - indent - allowance |
Serhiy Storchaka | 8e2aa88 | 2015-03-24 18:45:23 +0200 | [diff] [blame] | 174 | if len(rep) > max_width: |
| 175 | p = self._dispatch.get(type(object).__repr__, None) |
| 176 | if p is not None: |
| 177 | context[objid] = 1 |
| 178 | p(self, object, stream, indent, allowance, context, level + 1) |
| 179 | del context[objid] |
| 180 | return |
Serhiy Storchaka | 8e2aa88 | 2015-03-24 18:45:23 +0200 | [diff] [blame] | 181 | stream.write(rep) |
| 182 | |
| 183 | _dispatch = {} |
| 184 | |
| 185 | def _pprint_dict(self, object, stream, indent, allowance, context, level): |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 186 | write = stream.write |
Serhiy Storchaka | 8e2aa88 | 2015-03-24 18:45:23 +0200 | [diff] [blame] | 187 | write('{') |
| 188 | if self._indent_per_level > 1: |
| 189 | write((self._indent_per_level - 1) * ' ') |
| 190 | length = len(object) |
| 191 | if length: |
Rémi Lapeyre | 96831c7 | 2019-03-22 18:22:20 +0100 | [diff] [blame] | 192 | if self._sort_dicts: |
| 193 | items = sorted(object.items(), key=_safe_tuple) |
| 194 | else: |
| 195 | items = object.items() |
Serhiy Storchaka | 8e2aa88 | 2015-03-24 18:45:23 +0200 | [diff] [blame] | 196 | self._format_dict_items(items, stream, indent, allowance + 1, |
| 197 | context, level) |
| 198 | write('}') |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 199 | |
Serhiy Storchaka | 8e2aa88 | 2015-03-24 18:45:23 +0200 | [diff] [blame] | 200 | _dispatch[dict.__repr__] = _pprint_dict |
Serhiy Storchaka | aa4c36f | 2015-03-26 08:51:33 +0200 | [diff] [blame] | 201 | |
| 202 | def _pprint_ordered_dict(self, object, stream, indent, allowance, context, level): |
| 203 | if not len(object): |
| 204 | stream.write(repr(object)) |
| 205 | return |
| 206 | cls = object.__class__ |
| 207 | stream.write(cls.__name__ + '(') |
| 208 | self._format(list(object.items()), stream, |
| 209 | indent + len(cls.__name__) + 1, allowance + 1, |
| 210 | context, level) |
| 211 | stream.write(')') |
| 212 | |
| 213 | _dispatch[_collections.OrderedDict.__repr__] = _pprint_ordered_dict |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 214 | |
Serhiy Storchaka | 8e2aa88 | 2015-03-24 18:45:23 +0200 | [diff] [blame] | 215 | def _pprint_list(self, object, stream, indent, allowance, context, level): |
| 216 | stream.write('[') |
| 217 | self._format_items(object, stream, indent, allowance + 1, |
| 218 | context, level) |
| 219 | stream.write(']') |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 220 | |
Serhiy Storchaka | 8e2aa88 | 2015-03-24 18:45:23 +0200 | [diff] [blame] | 221 | _dispatch[list.__repr__] = _pprint_list |
| 222 | |
| 223 | def _pprint_tuple(self, object, stream, indent, allowance, context, level): |
| 224 | stream.write('(') |
| 225 | endchar = ',)' if len(object) == 1 else ')' |
| 226 | self._format_items(object, stream, indent, allowance + len(endchar), |
| 227 | context, level) |
| 228 | stream.write(endchar) |
| 229 | |
| 230 | _dispatch[tuple.__repr__] = _pprint_tuple |
| 231 | |
| 232 | def _pprint_set(self, object, stream, indent, allowance, context, level): |
| 233 | if not len(object): |
| 234 | stream.write(repr(object)) |
| 235 | return |
| 236 | typ = object.__class__ |
| 237 | if typ is set: |
| 238 | stream.write('{') |
| 239 | endchar = '}' |
| 240 | else: |
| 241 | stream.write(typ.__name__ + '({') |
| 242 | endchar = '})' |
| 243 | indent += len(typ.__name__) + 1 |
| 244 | object = sorted(object, key=_safe_key) |
| 245 | self._format_items(object, stream, indent, allowance + len(endchar), |
| 246 | context, level) |
| 247 | stream.write(endchar) |
| 248 | |
| 249 | _dispatch[set.__repr__] = _pprint_set |
| 250 | _dispatch[frozenset.__repr__] = _pprint_set |
| 251 | |
| 252 | def _pprint_str(self, object, stream, indent, allowance, context, level): |
| 253 | write = stream.write |
| 254 | if not len(object): |
| 255 | write(repr(object)) |
| 256 | return |
| 257 | chunks = [] |
| 258 | lines = object.splitlines(True) |
| 259 | if level == 1: |
| 260 | indent += 1 |
| 261 | allowance += 1 |
| 262 | max_width1 = max_width = self._width - indent |
| 263 | for i, line in enumerate(lines): |
| 264 | rep = repr(line) |
| 265 | if i == len(lines) - 1: |
| 266 | max_width1 -= allowance |
| 267 | if len(rep) <= max_width1: |
| 268 | chunks.append(rep) |
| 269 | else: |
| 270 | # A list of alternating (non-space, space) strings |
| 271 | parts = re.findall(r'\S*\s*', line) |
| 272 | assert parts |
| 273 | assert not parts[-1] |
| 274 | parts.pop() # drop empty last part |
| 275 | max_width2 = max_width |
| 276 | current = '' |
| 277 | for j, part in enumerate(parts): |
| 278 | candidate = current + part |
| 279 | if j == len(parts) - 1 and i == len(lines) - 1: |
| 280 | max_width2 -= allowance |
| 281 | if len(repr(candidate)) > max_width2: |
Serhiy Storchaka | fe3dc37 | 2014-12-20 20:57:15 +0200 | [diff] [blame] | 282 | if current: |
| 283 | chunks.append(repr(current)) |
Serhiy Storchaka | 8e2aa88 | 2015-03-24 18:45:23 +0200 | [diff] [blame] | 284 | current = part |
| 285 | else: |
| 286 | current = candidate |
| 287 | if current: |
| 288 | chunks.append(repr(current)) |
| 289 | if len(chunks) == 1: |
| 290 | write(rep) |
| 291 | return |
| 292 | if level == 1: |
| 293 | write('(') |
| 294 | for i, rep in enumerate(chunks): |
| 295 | if i > 0: |
| 296 | write('\n' + ' '*indent) |
| 297 | write(rep) |
| 298 | if level == 1: |
| 299 | write(')') |
| 300 | |
| 301 | _dispatch[str.__repr__] = _pprint_str |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 302 | |
Serhiy Storchaka | 022f203 | 2015-03-24 19:22:37 +0200 | [diff] [blame] | 303 | def _pprint_bytes(self, object, stream, indent, allowance, context, level): |
| 304 | write = stream.write |
| 305 | if len(object) <= 4: |
| 306 | write(repr(object)) |
| 307 | return |
| 308 | parens = level == 1 |
| 309 | if parens: |
| 310 | indent += 1 |
| 311 | allowance += 1 |
| 312 | write('(') |
| 313 | delim = '' |
| 314 | for rep in _wrap_bytes_repr(object, self._width - indent, allowance): |
| 315 | write(delim) |
| 316 | write(rep) |
| 317 | if not delim: |
| 318 | delim = '\n' + ' '*indent |
| 319 | if parens: |
| 320 | write(')') |
| 321 | |
| 322 | _dispatch[bytes.__repr__] = _pprint_bytes |
| 323 | |
| 324 | def _pprint_bytearray(self, object, stream, indent, allowance, context, level): |
| 325 | write = stream.write |
| 326 | write('bytearray(') |
| 327 | self._pprint_bytes(bytes(object), stream, indent + 10, |
| 328 | allowance + 1, context, level + 1) |
| 329 | write(')') |
| 330 | |
| 331 | _dispatch[bytearray.__repr__] = _pprint_bytearray |
| 332 | |
Serhiy Storchaka | 87eb482 | 2015-03-24 19:31:50 +0200 | [diff] [blame] | 333 | def _pprint_mappingproxy(self, object, stream, indent, allowance, context, level): |
| 334 | stream.write('mappingproxy(') |
| 335 | self._format(object.copy(), stream, indent + 13, allowance + 1, |
| 336 | context, level) |
| 337 | stream.write(')') |
| 338 | |
| 339 | _dispatch[_types.MappingProxyType.__repr__] = _pprint_mappingproxy |
| 340 | |
Carl Bordum Hansen | 06a8916 | 2019-06-27 01:13:18 +0200 | [diff] [blame] | 341 | def _pprint_simplenamespace(self, object, stream, indent, allowance, context, level): |
| 342 | if type(object) is _types.SimpleNamespace: |
| 343 | # The SimpleNamespace repr is "namespace" instead of the class |
| 344 | # name, so we do the same here. For subclasses; use the class name. |
| 345 | cls_name = 'namespace' |
| 346 | else: |
| 347 | cls_name = object.__class__.__name__ |
| 348 | indent += len(cls_name) + 1 |
| 349 | delimnl = ',\n' + ' ' * indent |
| 350 | items = object.__dict__.items() |
| 351 | last_index = len(items) - 1 |
| 352 | |
| 353 | stream.write(cls_name + '(') |
| 354 | for i, (key, ent) in enumerate(items): |
| 355 | stream.write(key) |
| 356 | stream.write('=') |
| 357 | |
| 358 | last = i == last_index |
| 359 | self._format(ent, stream, indent + len(key) + 1, |
| 360 | allowance if last else 1, |
| 361 | context, level) |
| 362 | if not last: |
| 363 | stream.write(delimnl) |
| 364 | stream.write(')') |
| 365 | |
| 366 | _dispatch[_types.SimpleNamespace.__repr__] = _pprint_simplenamespace |
| 367 | |
Serhiy Storchaka | a750ce3 | 2015-02-14 10:55:19 +0200 | [diff] [blame] | 368 | def _format_dict_items(self, items, stream, indent, allowance, context, |
| 369 | level): |
| 370 | write = stream.write |
Serhiy Storchaka | 8e2aa88 | 2015-03-24 18:45:23 +0200 | [diff] [blame] | 371 | indent += self._indent_per_level |
Serhiy Storchaka | a750ce3 | 2015-02-14 10:55:19 +0200 | [diff] [blame] | 372 | delimnl = ',\n' + ' ' * indent |
| 373 | last_index = len(items) - 1 |
| 374 | for i, (key, ent) in enumerate(items): |
| 375 | last = i == last_index |
| 376 | rep = self._repr(key, context, level) |
| 377 | write(rep) |
| 378 | write(': ') |
| 379 | self._format(ent, stream, indent + len(rep) + 2, |
| 380 | allowance if last else 1, |
| 381 | context, level) |
| 382 | if not last: |
| 383 | write(delimnl) |
| 384 | |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 385 | def _format_items(self, items, stream, indent, allowance, context, level): |
| 386 | write = stream.write |
Serhiy Storchaka | 8e2aa88 | 2015-03-24 18:45:23 +0200 | [diff] [blame] | 387 | indent += self._indent_per_level |
| 388 | if self._indent_per_level > 1: |
| 389 | write((self._indent_per_level - 1) * ' ') |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 390 | delimnl = ',\n' + ' ' * indent |
| 391 | delim = '' |
Serhiy Storchaka | a750ce3 | 2015-02-14 10:55:19 +0200 | [diff] [blame] | 392 | width = max_width = self._width - indent + 1 |
| 393 | it = iter(items) |
| 394 | try: |
| 395 | next_ent = next(it) |
| 396 | except StopIteration: |
| 397 | return |
| 398 | last = False |
| 399 | while not last: |
| 400 | ent = next_ent |
| 401 | try: |
| 402 | next_ent = next(it) |
| 403 | except StopIteration: |
| 404 | last = True |
| 405 | max_width -= allowance |
| 406 | width -= allowance |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 407 | if self._compact: |
| 408 | rep = self._repr(ent, context, level) |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame] | 409 | w = len(rep) + 2 |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 410 | if width < w: |
| 411 | width = max_width |
| 412 | if delim: |
| 413 | delim = delimnl |
| 414 | if width >= w: |
| 415 | width -= w |
| 416 | write(delim) |
| 417 | delim = ', ' |
| 418 | write(rep) |
| 419 | continue |
| 420 | write(delim) |
| 421 | delim = delimnl |
Serhiy Storchaka | a750ce3 | 2015-02-14 10:55:19 +0200 | [diff] [blame] | 422 | self._format(ent, stream, indent, |
| 423 | allowance if last else 1, |
| 424 | context, level) |
Serhiy Storchaka | 7c411a4 | 2013-10-02 11:56:18 +0300 | [diff] [blame] | 425 | |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 426 | def _repr(self, object, context, level): |
Fred Drake | aee113d | 2002-04-02 05:08:35 +0000 | [diff] [blame] | 427 | repr, readable, recursive = self.format(object, context.copy(), |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 428 | self._depth, level) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 429 | if not readable: |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 430 | self._readable = False |
Tim Peters | a814db5 | 2001-05-14 07:05:58 +0000 | [diff] [blame] | 431 | if recursive: |
Fred Drake | e6691ef | 2002-07-08 12:28:06 +0000 | [diff] [blame] | 432 | self._recursive = True |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 433 | return repr |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 434 | |
Fred Drake | aee113d | 2002-04-02 05:08:35 +0000 | [diff] [blame] | 435 | def format(self, object, context, maxlevels, level): |
| 436 | """Format object for a specific context, returning a string |
| 437 | and flags indicating whether the representation is 'readable' |
| 438 | and whether the object represents a recursive construct. |
| 439 | """ |
Irit Katriel | ff420f0 | 2020-11-23 13:31:31 +0000 | [diff] [blame] | 440 | return self._safe_repr(object, context, maxlevels, level) |
Fred Drake | aee113d | 2002-04-02 05:08:35 +0000 | [diff] [blame] | 441 | |
Serhiy Storchaka | bedbf96 | 2015-05-12 13:35:48 +0300 | [diff] [blame] | 442 | def _pprint_default_dict(self, object, stream, indent, allowance, context, level): |
| 443 | if not len(object): |
| 444 | stream.write(repr(object)) |
| 445 | return |
| 446 | rdf = self._repr(object.default_factory, context, level) |
| 447 | cls = object.__class__ |
| 448 | indent += len(cls.__name__) + 1 |
| 449 | stream.write('%s(%s,\n%s' % (cls.__name__, rdf, ' ' * indent)) |
| 450 | self._pprint_dict(object, stream, indent, allowance + 1, context, level) |
| 451 | stream.write(')') |
| 452 | |
| 453 | _dispatch[_collections.defaultdict.__repr__] = _pprint_default_dict |
| 454 | |
| 455 | def _pprint_counter(self, object, stream, indent, allowance, context, level): |
| 456 | if not len(object): |
| 457 | stream.write(repr(object)) |
| 458 | return |
| 459 | cls = object.__class__ |
| 460 | stream.write(cls.__name__ + '({') |
| 461 | if self._indent_per_level > 1: |
| 462 | stream.write((self._indent_per_level - 1) * ' ') |
| 463 | items = object.most_common() |
| 464 | self._format_dict_items(items, stream, |
| 465 | indent + len(cls.__name__) + 1, allowance + 2, |
| 466 | context, level) |
| 467 | stream.write('})') |
| 468 | |
| 469 | _dispatch[_collections.Counter.__repr__] = _pprint_counter |
| 470 | |
| 471 | def _pprint_chain_map(self, object, stream, indent, allowance, context, level): |
| 472 | if not len(object.maps): |
| 473 | stream.write(repr(object)) |
| 474 | return |
| 475 | cls = object.__class__ |
| 476 | stream.write(cls.__name__ + '(') |
| 477 | indent += len(cls.__name__) + 1 |
| 478 | for i, m in enumerate(object.maps): |
| 479 | if i == len(object.maps) - 1: |
| 480 | self._format(m, stream, indent, allowance + 1, context, level) |
| 481 | stream.write(')') |
| 482 | else: |
| 483 | self._format(m, stream, indent, 1, context, level) |
| 484 | stream.write(',\n' + ' ' * indent) |
| 485 | |
| 486 | _dispatch[_collections.ChainMap.__repr__] = _pprint_chain_map |
| 487 | |
| 488 | def _pprint_deque(self, object, stream, indent, allowance, context, level): |
| 489 | if not len(object): |
| 490 | stream.write(repr(object)) |
| 491 | return |
| 492 | cls = object.__class__ |
| 493 | stream.write(cls.__name__ + '(') |
| 494 | indent += len(cls.__name__) + 1 |
| 495 | stream.write('[') |
| 496 | if object.maxlen is None: |
| 497 | self._format_items(object, stream, indent, allowance + 2, |
| 498 | context, level) |
| 499 | stream.write('])') |
| 500 | else: |
| 501 | self._format_items(object, stream, indent, 2, |
| 502 | context, level) |
| 503 | rml = self._repr(object.maxlen, context, level) |
| 504 | stream.write('],\n%smaxlen=%s)' % (' ' * indent, rml)) |
| 505 | |
| 506 | _dispatch[_collections.deque.__repr__] = _pprint_deque |
| 507 | |
| 508 | def _pprint_user_dict(self, object, stream, indent, allowance, context, level): |
| 509 | self._format(object.data, stream, indent, allowance, context, level - 1) |
| 510 | |
| 511 | _dispatch[_collections.UserDict.__repr__] = _pprint_user_dict |
| 512 | |
| 513 | def _pprint_user_list(self, object, stream, indent, allowance, context, level): |
| 514 | self._format(object.data, stream, indent, allowance, context, level - 1) |
| 515 | |
| 516 | _dispatch[_collections.UserList.__repr__] = _pprint_user_list |
| 517 | |
| 518 | def _pprint_user_string(self, object, stream, indent, allowance, context, level): |
| 519 | self._format(object.data, stream, indent, allowance, context, level - 1) |
| 520 | |
| 521 | _dispatch[_collections.UserString.__repr__] = _pprint_user_string |
Fred Drake | aee113d | 2002-04-02 05:08:35 +0000 | [diff] [blame] | 522 | |
Irit Katriel | ff420f0 | 2020-11-23 13:31:31 +0000 | [diff] [blame] | 523 | def _safe_repr(self, object, context, maxlevels, level): |
| 524 | # Return triple (repr_string, isreadable, isrecursive). |
| 525 | typ = type(object) |
| 526 | if typ in _builtin_scalars: |
| 527 | return repr(object), True, False |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 528 | |
Irit Katriel | ff420f0 | 2020-11-23 13:31:31 +0000 | [diff] [blame] | 529 | r = getattr(typ, "__repr__", None) |
sblondon | 3ba3d51 | 2021-03-24 09:23:20 +0100 | [diff] [blame] | 530 | |
| 531 | if issubclass(typ, int) and r is int.__repr__: |
| 532 | if self._underscore_numbers: |
| 533 | return f"{object:_d}", True, False |
| 534 | else: |
| 535 | return repr(object), True, False |
| 536 | |
Irit Katriel | ff420f0 | 2020-11-23 13:31:31 +0000 | [diff] [blame] | 537 | if issubclass(typ, dict) and r is dict.__repr__: |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 538 | if not object: |
Irit Katriel | ff420f0 | 2020-11-23 13:31:31 +0000 | [diff] [blame] | 539 | return "{}", True, False |
| 540 | objid = id(object) |
| 541 | if maxlevels and level >= maxlevels: |
| 542 | return "{...}", False, objid in context |
| 543 | if objid in context: |
| 544 | return _recursion(object), False, True |
| 545 | context[objid] = 1 |
| 546 | readable = True |
| 547 | recursive = False |
| 548 | components = [] |
| 549 | append = components.append |
| 550 | level += 1 |
| 551 | if self._sort_dicts: |
| 552 | items = sorted(object.items(), key=_safe_tuple) |
| 553 | else: |
| 554 | items = object.items() |
| 555 | for k, v in items: |
| 556 | krepr, kreadable, krecur = self.format( |
| 557 | k, context, maxlevels, level) |
| 558 | vrepr, vreadable, vrecur = self.format( |
| 559 | v, context, maxlevels, level) |
| 560 | append("%s: %s" % (krepr, vrepr)) |
| 561 | readable = readable and kreadable and vreadable |
| 562 | if krecur or vrecur: |
| 563 | recursive = True |
| 564 | del context[objid] |
| 565 | return "{%s}" % ", ".join(components), readable, recursive |
Tim Peters | 8876848 | 2001-11-13 21:51:26 +0000 | [diff] [blame] | 566 | |
Irit Katriel | ff420f0 | 2020-11-23 13:31:31 +0000 | [diff] [blame] | 567 | if (issubclass(typ, list) and r is list.__repr__) or \ |
| 568 | (issubclass(typ, tuple) and r is tuple.__repr__): |
| 569 | if issubclass(typ, list): |
| 570 | if not object: |
| 571 | return "[]", True, False |
| 572 | format = "[%s]" |
| 573 | elif len(object) == 1: |
| 574 | format = "(%s,)" |
| 575 | else: |
| 576 | if not object: |
| 577 | return "()", True, False |
| 578 | format = "(%s)" |
| 579 | objid = id(object) |
| 580 | if maxlevels and level >= maxlevels: |
| 581 | return format % "...", False, objid in context |
| 582 | if objid in context: |
| 583 | return _recursion(object), False, True |
| 584 | context[objid] = 1 |
| 585 | readable = True |
| 586 | recursive = False |
| 587 | components = [] |
| 588 | append = components.append |
| 589 | level += 1 |
| 590 | for o in object: |
| 591 | orepr, oreadable, orecur = self.format( |
| 592 | o, context, maxlevels, level) |
| 593 | append(orepr) |
| 594 | if not oreadable: |
| 595 | readable = False |
| 596 | if orecur: |
| 597 | recursive = True |
| 598 | del context[objid] |
| 599 | return format % ", ".join(components), readable, recursive |
| 600 | |
| 601 | rep = repr(object) |
| 602 | return rep, (rep and not rep.startswith('<')), False |
Tim Peters | 95b3f78 | 2001-05-14 18:39:41 +0000 | [diff] [blame] | 603 | |
sblondon | 3ba3d51 | 2021-03-24 09:23:20 +0100 | [diff] [blame] | 604 | _builtin_scalars = frozenset({str, bytes, bytearray, float, complex, |
Serhiy Storchaka | 8eb1f07 | 2015-05-16 21:38:05 +0300 | [diff] [blame] | 605 | bool, type(None)}) |
Guido van Rossum | 5e92aff | 1997-04-16 00:49:59 +0000 | [diff] [blame] | 606 | |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 607 | def _recursion(object): |
| 608 | return ("<Recursion on %s with id=%s>" |
Antoine Pitrou | 7d36e2f | 2013-10-03 21:29:36 +0200 | [diff] [blame] | 609 | % (type(object).__name__, id(object))) |
Fred Drake | a89fda0 | 1997-04-16 16:59:30 +0000 | [diff] [blame] | 610 | |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 611 | |
| 612 | def _perfcheck(object=None): |
| 613 | import time |
| 614 | if object is None: |
| 615 | object = [("string", (1, 2), [3, 4], {5: 6, 7: 8})] * 100000 |
| 616 | p = PrettyPrinter() |
Victor Stinner | 8db5b54 | 2018-12-17 11:30:34 +0100 | [diff] [blame] | 617 | t1 = time.perf_counter() |
Irit Katriel | ff420f0 | 2020-11-23 13:31:31 +0000 | [diff] [blame] | 618 | p._safe_repr(object, {}, None, 0, True) |
Victor Stinner | 8db5b54 | 2018-12-17 11:30:34 +0100 | [diff] [blame] | 619 | t2 = time.perf_counter() |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 620 | p.pformat(object) |
Victor Stinner | 8db5b54 | 2018-12-17 11:30:34 +0100 | [diff] [blame] | 621 | t3 = time.perf_counter() |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 622 | print("_safe_repr:", t2 - t1) |
| 623 | print("pformat:", t3 - t2) |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 624 | |
Serhiy Storchaka | 022f203 | 2015-03-24 19:22:37 +0200 | [diff] [blame] | 625 | def _wrap_bytes_repr(object, width, allowance): |
| 626 | current = b'' |
| 627 | last = len(object) // 4 * 4 |
| 628 | for i in range(0, len(object), 4): |
| 629 | part = object[i: i+4] |
| 630 | candidate = current + part |
| 631 | if i == last: |
| 632 | width -= allowance |
| 633 | if len(repr(candidate)) > width: |
| 634 | if current: |
| 635 | yield repr(current) |
| 636 | current = part |
| 637 | else: |
| 638 | current = candidate |
| 639 | if current: |
| 640 | yield repr(current) |
| 641 | |
Fred Drake | 49cc01e | 2001-11-01 17:50:38 +0000 | [diff] [blame] | 642 | if __name__ == "__main__": |
| 643 | _perfcheck() |