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