##// END OF EJS Templates
remove unchanging boolean DICT_IS_ORDERED and dependent unreachable code
grey275 -
Show More
@@ -1,871 +1,863 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Python advanced pretty printer. This pretty printer is intended to
3 Python advanced pretty printer. This pretty printer is intended to
4 replace the old `pprint` python module which does not allow developers
4 replace the old `pprint` python module which does not allow developers
5 to provide their own pretty print callbacks.
5 to provide their own pretty print callbacks.
6
6
7 This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
7 This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
8
8
9
9
10 Example Usage
10 Example Usage
11 -------------
11 -------------
12
12
13 To directly print the representation of an object use `pprint`::
13 To directly print the representation of an object use `pprint`::
14
14
15 from pretty import pprint
15 from pretty import pprint
16 pprint(complex_object)
16 pprint(complex_object)
17
17
18 To get a string of the output use `pretty`::
18 To get a string of the output use `pretty`::
19
19
20 from pretty import pretty
20 from pretty import pretty
21 string = pretty(complex_object)
21 string = pretty(complex_object)
22
22
23
23
24 Extending
24 Extending
25 ---------
25 ---------
26
26
27 The pretty library allows developers to add pretty printing rules for their
27 The pretty library allows developers to add pretty printing rules for their
28 own objects. This process is straightforward. All you have to do is to
28 own objects. This process is straightforward. All you have to do is to
29 add a `_repr_pretty_` method to your object and call the methods on the
29 add a `_repr_pretty_` method to your object and call the methods on the
30 pretty printer passed::
30 pretty printer passed::
31
31
32 class MyObject(object):
32 class MyObject(object):
33
33
34 def _repr_pretty_(self, p, cycle):
34 def _repr_pretty_(self, p, cycle):
35 ...
35 ...
36
36
37 Here is an example implementation of a `_repr_pretty_` method for a list
37 Here is an example implementation of a `_repr_pretty_` method for a list
38 subclass::
38 subclass::
39
39
40 class MyList(list):
40 class MyList(list):
41
41
42 def _repr_pretty_(self, p, cycle):
42 def _repr_pretty_(self, p, cycle):
43 if cycle:
43 if cycle:
44 p.text('MyList(...)')
44 p.text('MyList(...)')
45 else:
45 else:
46 with p.group(8, 'MyList([', '])'):
46 with p.group(8, 'MyList([', '])'):
47 for idx, item in enumerate(self):
47 for idx, item in enumerate(self):
48 if idx:
48 if idx:
49 p.text(',')
49 p.text(',')
50 p.breakable()
50 p.breakable()
51 p.pretty(item)
51 p.pretty(item)
52
52
53 The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
53 The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
54 react to that or the result is an infinite loop. `p.text()` just adds
54 react to that or the result is an infinite loop. `p.text()` just adds
55 non breaking text to the output, `p.breakable()` either adds a whitespace
55 non breaking text to the output, `p.breakable()` either adds a whitespace
56 or breaks here. If you pass it an argument it's used instead of the
56 or breaks here. If you pass it an argument it's used instead of the
57 default space. `p.pretty` prettyprints another object using the pretty print
57 default space. `p.pretty` prettyprints another object using the pretty print
58 method.
58 method.
59
59
60 The first parameter to the `group` function specifies the extra indentation
60 The first parameter to the `group` function specifies the extra indentation
61 of the next line. In this example the next item will either be on the same
61 of the next line. In this example the next item will either be on the same
62 line (if the items are short enough) or aligned with the right edge of the
62 line (if the items are short enough) or aligned with the right edge of the
63 opening bracket of `MyList`.
63 opening bracket of `MyList`.
64
64
65 If you just want to indent something you can use the group function
65 If you just want to indent something you can use the group function
66 without open / close parameters. You can also use this code::
66 without open / close parameters. You can also use this code::
67
67
68 with p.indent(2):
68 with p.indent(2):
69 ...
69 ...
70
70
71 Inheritance diagram:
71 Inheritance diagram:
72
72
73 .. inheritance-diagram:: IPython.lib.pretty
73 .. inheritance-diagram:: IPython.lib.pretty
74 :parts: 3
74 :parts: 3
75
75
76 :copyright: 2007 by Armin Ronacher.
76 :copyright: 2007 by Armin Ronacher.
77 Portions (c) 2009 by Robert Kern.
77 Portions (c) 2009 by Robert Kern.
78 :license: BSD License.
78 :license: BSD License.
79 """
79 """
80
80
81 from contextlib import contextmanager
81 from contextlib import contextmanager
82 import datetime
82 import datetime
83 import os
83 import os
84 import re
84 import re
85 import sys
85 import sys
86 import types
86 import types
87 from collections import deque
87 from collections import deque
88 from inspect import signature
88 from inspect import signature
89 from io import StringIO
89 from io import StringIO
90 from warnings import warn
90 from warnings import warn
91
91
92 from IPython.utils.decorators import undoc
92 from IPython.utils.decorators import undoc
93 from IPython.utils.py3compat import PYPY
93 from IPython.utils.py3compat import PYPY
94
94
95 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
95 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
96 'for_type', 'for_type_by_name']
96 'for_type', 'for_type_by_name']
97
97
98
98
99 MAX_SEQ_LENGTH = 1000
99 MAX_SEQ_LENGTH = 1000
100 # The language spec says that dicts preserve order from 3.7, but CPython
101 # does so from 3.6, so it seems likely that people will expect that.
102 DICT_IS_ORDERED = True
103 _re_pattern_type = type(re.compile(''))
100 _re_pattern_type = type(re.compile(''))
104
101
105 def _safe_getattr(obj, attr, default=None):
102 def _safe_getattr(obj, attr, default=None):
106 """Safe version of getattr.
103 """Safe version of getattr.
107
104
108 Same as getattr, but will return ``default`` on any Exception,
105 Same as getattr, but will return ``default`` on any Exception,
109 rather than raising.
106 rather than raising.
110 """
107 """
111 try:
108 try:
112 return getattr(obj, attr, default)
109 return getattr(obj, attr, default)
113 except Exception:
110 except Exception:
114 return default
111 return default
115
112
116 @undoc
113 @undoc
117 class CUnicodeIO(StringIO):
114 class CUnicodeIO(StringIO):
118 def __init__(self, *args, **kwargs):
115 def __init__(self, *args, **kwargs):
119 super().__init__(*args, **kwargs)
116 super().__init__(*args, **kwargs)
120 warn(("CUnicodeIO is deprecated since IPython 6.0. "
117 warn(("CUnicodeIO is deprecated since IPython 6.0. "
121 "Please use io.StringIO instead."),
118 "Please use io.StringIO instead."),
122 DeprecationWarning, stacklevel=2)
119 DeprecationWarning, stacklevel=2)
123
120
124 def _sorted_for_pprint(items):
121 def _sorted_for_pprint(items):
125 """
122 """
126 Sort the given items for pretty printing. Since some predictable
123 Sort the given items for pretty printing. Since some predictable
127 sorting is better than no sorting at all, we sort on the string
124 sorting is better than no sorting at all, we sort on the string
128 representation if normal sorting fails.
125 representation if normal sorting fails.
129 """
126 """
130 items = list(items)
127 items = list(items)
131 try:
128 try:
132 return sorted(items)
129 return sorted(items)
133 except Exception:
130 except Exception:
134 try:
131 try:
135 return sorted(items, key=str)
132 return sorted(items, key=str)
136 except Exception:
133 except Exception:
137 return items
134 return items
138
135
139 def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
136 def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
140 """
137 """
141 Pretty print the object's representation.
138 Pretty print the object's representation.
142 """
139 """
143 stream = StringIO()
140 stream = StringIO()
144 printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)
141 printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)
145 printer.pretty(obj)
142 printer.pretty(obj)
146 printer.flush()
143 printer.flush()
147 return stream.getvalue()
144 return stream.getvalue()
148
145
149
146
150 def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
147 def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
151 """
148 """
152 Like `pretty` but print to stdout.
149 Like `pretty` but print to stdout.
153 """
150 """
154 printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
151 printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
155 printer.pretty(obj)
152 printer.pretty(obj)
156 printer.flush()
153 printer.flush()
157 sys.stdout.write(newline)
154 sys.stdout.write(newline)
158 sys.stdout.flush()
155 sys.stdout.flush()
159
156
160 class _PrettyPrinterBase(object):
157 class _PrettyPrinterBase(object):
161
158
162 @contextmanager
159 @contextmanager
163 def indent(self, indent):
160 def indent(self, indent):
164 """with statement support for indenting/dedenting."""
161 """with statement support for indenting/dedenting."""
165 self.indentation += indent
162 self.indentation += indent
166 try:
163 try:
167 yield
164 yield
168 finally:
165 finally:
169 self.indentation -= indent
166 self.indentation -= indent
170
167
171 @contextmanager
168 @contextmanager
172 def group(self, indent=0, open='', close=''):
169 def group(self, indent=0, open='', close=''):
173 """like begin_group / end_group but for the with statement."""
170 """like begin_group / end_group but for the with statement."""
174 self.begin_group(indent, open)
171 self.begin_group(indent, open)
175 try:
172 try:
176 yield
173 yield
177 finally:
174 finally:
178 self.end_group(indent, close)
175 self.end_group(indent, close)
179
176
180 class PrettyPrinter(_PrettyPrinterBase):
177 class PrettyPrinter(_PrettyPrinterBase):
181 """
178 """
182 Baseclass for the `RepresentationPrinter` prettyprinter that is used to
179 Baseclass for the `RepresentationPrinter` prettyprinter that is used to
183 generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
180 generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
184 this printer knows nothing about the default pprinters or the `_repr_pretty_`
181 this printer knows nothing about the default pprinters or the `_repr_pretty_`
185 callback method.
182 callback method.
186 """
183 """
187
184
188 def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
185 def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
189 self.output = output
186 self.output = output
190 self.max_width = max_width
187 self.max_width = max_width
191 self.newline = newline
188 self.newline = newline
192 self.max_seq_length = max_seq_length
189 self.max_seq_length = max_seq_length
193 self.output_width = 0
190 self.output_width = 0
194 self.buffer_width = 0
191 self.buffer_width = 0
195 self.buffer = deque()
192 self.buffer = deque()
196
193
197 root_group = Group(0)
194 root_group = Group(0)
198 self.group_stack = [root_group]
195 self.group_stack = [root_group]
199 self.group_queue = GroupQueue(root_group)
196 self.group_queue = GroupQueue(root_group)
200 self.indentation = 0
197 self.indentation = 0
201
198
202 def _break_outer_groups(self):
199 def _break_outer_groups(self):
203 while self.max_width < self.output_width + self.buffer_width:
200 while self.max_width < self.output_width + self.buffer_width:
204 group = self.group_queue.deq()
201 group = self.group_queue.deq()
205 if not group:
202 if not group:
206 return
203 return
207 while group.breakables:
204 while group.breakables:
208 x = self.buffer.popleft()
205 x = self.buffer.popleft()
209 self.output_width = x.output(self.output, self.output_width)
206 self.output_width = x.output(self.output, self.output_width)
210 self.buffer_width -= x.width
207 self.buffer_width -= x.width
211 while self.buffer and isinstance(self.buffer[0], Text):
208 while self.buffer and isinstance(self.buffer[0], Text):
212 x = self.buffer.popleft()
209 x = self.buffer.popleft()
213 self.output_width = x.output(self.output, self.output_width)
210 self.output_width = x.output(self.output, self.output_width)
214 self.buffer_width -= x.width
211 self.buffer_width -= x.width
215
212
216 def text(self, obj):
213 def text(self, obj):
217 """Add literal text to the output."""
214 """Add literal text to the output."""
218 width = len(obj)
215 width = len(obj)
219 if self.buffer:
216 if self.buffer:
220 text = self.buffer[-1]
217 text = self.buffer[-1]
221 if not isinstance(text, Text):
218 if not isinstance(text, Text):
222 text = Text()
219 text = Text()
223 self.buffer.append(text)
220 self.buffer.append(text)
224 text.add(obj, width)
221 text.add(obj, width)
225 self.buffer_width += width
222 self.buffer_width += width
226 self._break_outer_groups()
223 self._break_outer_groups()
227 else:
224 else:
228 self.output.write(obj)
225 self.output.write(obj)
229 self.output_width += width
226 self.output_width += width
230
227
231 def breakable(self, sep=' '):
228 def breakable(self, sep=' '):
232 """
229 """
233 Add a breakable separator to the output. This does not mean that it
230 Add a breakable separator to the output. This does not mean that it
234 will automatically break here. If no breaking on this position takes
231 will automatically break here. If no breaking on this position takes
235 place the `sep` is inserted which default to one space.
232 place the `sep` is inserted which default to one space.
236 """
233 """
237 width = len(sep)
234 width = len(sep)
238 group = self.group_stack[-1]
235 group = self.group_stack[-1]
239 if group.want_break:
236 if group.want_break:
240 self.flush()
237 self.flush()
241 self.output.write(self.newline)
238 self.output.write(self.newline)
242 self.output.write(' ' * self.indentation)
239 self.output.write(' ' * self.indentation)
243 self.output_width = self.indentation
240 self.output_width = self.indentation
244 self.buffer_width = 0
241 self.buffer_width = 0
245 else:
242 else:
246 self.buffer.append(Breakable(sep, width, self))
243 self.buffer.append(Breakable(sep, width, self))
247 self.buffer_width += width
244 self.buffer_width += width
248 self._break_outer_groups()
245 self._break_outer_groups()
249
246
250 def break_(self):
247 def break_(self):
251 """
248 """
252 Explicitly insert a newline into the output, maintaining correct indentation.
249 Explicitly insert a newline into the output, maintaining correct indentation.
253 """
250 """
254 self.flush()
251 self.flush()
255 self.output.write(self.newline)
252 self.output.write(self.newline)
256 self.output.write(' ' * self.indentation)
253 self.output.write(' ' * self.indentation)
257 self.output_width = self.indentation
254 self.output_width = self.indentation
258 self.buffer_width = 0
255 self.buffer_width = 0
259
256
260
257
261 def begin_group(self, indent=0, open=''):
258 def begin_group(self, indent=0, open=''):
262 """
259 """
263 Begin a group. If you want support for python < 2.5 which doesn't has
260 Begin a group. If you want support for python < 2.5 which doesn't has
264 the with statement this is the preferred way:
261 the with statement this is the preferred way:
265
262
266 p.begin_group(1, '{')
263 p.begin_group(1, '{')
267 ...
264 ...
268 p.end_group(1, '}')
265 p.end_group(1, '}')
269
266
270 The python 2.5 expression would be this:
267 The python 2.5 expression would be this:
271
268
272 with p.group(1, '{', '}'):
269 with p.group(1, '{', '}'):
273 ...
270 ...
274
271
275 The first parameter specifies the indentation for the next line (usually
272 The first parameter specifies the indentation for the next line (usually
276 the width of the opening text), the second the opening text. All
273 the width of the opening text), the second the opening text. All
277 parameters are optional.
274 parameters are optional.
278 """
275 """
279 if open:
276 if open:
280 self.text(open)
277 self.text(open)
281 group = Group(self.group_stack[-1].depth + 1)
278 group = Group(self.group_stack[-1].depth + 1)
282 self.group_stack.append(group)
279 self.group_stack.append(group)
283 self.group_queue.enq(group)
280 self.group_queue.enq(group)
284 self.indentation += indent
281 self.indentation += indent
285
282
286 def _enumerate(self, seq):
283 def _enumerate(self, seq):
287 """like enumerate, but with an upper limit on the number of items"""
284 """like enumerate, but with an upper limit on the number of items"""
288 for idx, x in enumerate(seq):
285 for idx, x in enumerate(seq):
289 if self.max_seq_length and idx >= self.max_seq_length:
286 if self.max_seq_length and idx >= self.max_seq_length:
290 self.text(',')
287 self.text(',')
291 self.breakable()
288 self.breakable()
292 self.text('...')
289 self.text('...')
293 return
290 return
294 yield idx, x
291 yield idx, x
295
292
296 def end_group(self, dedent=0, close=''):
293 def end_group(self, dedent=0, close=''):
297 """End a group. See `begin_group` for more details."""
294 """End a group. See `begin_group` for more details."""
298 self.indentation -= dedent
295 self.indentation -= dedent
299 group = self.group_stack.pop()
296 group = self.group_stack.pop()
300 if not group.breakables:
297 if not group.breakables:
301 self.group_queue.remove(group)
298 self.group_queue.remove(group)
302 if close:
299 if close:
303 self.text(close)
300 self.text(close)
304
301
305 def flush(self):
302 def flush(self):
306 """Flush data that is left in the buffer."""
303 """Flush data that is left in the buffer."""
307 for data in self.buffer:
304 for data in self.buffer:
308 self.output_width += data.output(self.output, self.output_width)
305 self.output_width += data.output(self.output, self.output_width)
309 self.buffer.clear()
306 self.buffer.clear()
310 self.buffer_width = 0
307 self.buffer_width = 0
311
308
312
309
313 def _get_mro(obj_class):
310 def _get_mro(obj_class):
314 """ Get a reasonable method resolution order of a class and its superclasses
311 """ Get a reasonable method resolution order of a class and its superclasses
315 for both old-style and new-style classes.
312 for both old-style and new-style classes.
316 """
313 """
317 if not hasattr(obj_class, '__mro__'):
314 if not hasattr(obj_class, '__mro__'):
318 # Old-style class. Mix in object to make a fake new-style class.
315 # Old-style class. Mix in object to make a fake new-style class.
319 try:
316 try:
320 obj_class = type(obj_class.__name__, (obj_class, object), {})
317 obj_class = type(obj_class.__name__, (obj_class, object), {})
321 except TypeError:
318 except TypeError:
322 # Old-style extension type that does not descend from object.
319 # Old-style extension type that does not descend from object.
323 # FIXME: try to construct a more thorough MRO.
320 # FIXME: try to construct a more thorough MRO.
324 mro = [obj_class]
321 mro = [obj_class]
325 else:
322 else:
326 mro = obj_class.__mro__[1:-1]
323 mro = obj_class.__mro__[1:-1]
327 else:
324 else:
328 mro = obj_class.__mro__
325 mro = obj_class.__mro__
329 return mro
326 return mro
330
327
331
328
332 class RepresentationPrinter(PrettyPrinter):
329 class RepresentationPrinter(PrettyPrinter):
333 """
330 """
334 Special pretty printer that has a `pretty` method that calls the pretty
331 Special pretty printer that has a `pretty` method that calls the pretty
335 printer for a python object.
332 printer for a python object.
336
333
337 This class stores processing data on `self` so you must *never* use
334 This class stores processing data on `self` so you must *never* use
338 this class in a threaded environment. Always lock it or reinstanciate
335 this class in a threaded environment. Always lock it or reinstanciate
339 it.
336 it.
340
337
341 Instances also have a verbose flag callbacks can access to control their
338 Instances also have a verbose flag callbacks can access to control their
342 output. For example the default instance repr prints all attributes and
339 output. For example the default instance repr prints all attributes and
343 methods that are not prefixed by an underscore if the printer is in
340 methods that are not prefixed by an underscore if the printer is in
344 verbose mode.
341 verbose mode.
345 """
342 """
346
343
347 def __init__(self, output, verbose=False, max_width=79, newline='\n',
344 def __init__(self, output, verbose=False, max_width=79, newline='\n',
348 singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,
345 singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,
349 max_seq_length=MAX_SEQ_LENGTH):
346 max_seq_length=MAX_SEQ_LENGTH):
350
347
351 PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)
348 PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)
352 self.verbose = verbose
349 self.verbose = verbose
353 self.stack = []
350 self.stack = []
354 if singleton_pprinters is None:
351 if singleton_pprinters is None:
355 singleton_pprinters = _singleton_pprinters.copy()
352 singleton_pprinters = _singleton_pprinters.copy()
356 self.singleton_pprinters = singleton_pprinters
353 self.singleton_pprinters = singleton_pprinters
357 if type_pprinters is None:
354 if type_pprinters is None:
358 type_pprinters = _type_pprinters.copy()
355 type_pprinters = _type_pprinters.copy()
359 self.type_pprinters = type_pprinters
356 self.type_pprinters = type_pprinters
360 if deferred_pprinters is None:
357 if deferred_pprinters is None:
361 deferred_pprinters = _deferred_type_pprinters.copy()
358 deferred_pprinters = _deferred_type_pprinters.copy()
362 self.deferred_pprinters = deferred_pprinters
359 self.deferred_pprinters = deferred_pprinters
363
360
364 def pretty(self, obj):
361 def pretty(self, obj):
365 """Pretty print the given object."""
362 """Pretty print the given object."""
366 obj_id = id(obj)
363 obj_id = id(obj)
367 cycle = obj_id in self.stack
364 cycle = obj_id in self.stack
368 self.stack.append(obj_id)
365 self.stack.append(obj_id)
369 self.begin_group()
366 self.begin_group()
370 try:
367 try:
371 obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
368 obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
372 # First try to find registered singleton printers for the type.
369 # First try to find registered singleton printers for the type.
373 try:
370 try:
374 printer = self.singleton_pprinters[obj_id]
371 printer = self.singleton_pprinters[obj_id]
375 except (TypeError, KeyError):
372 except (TypeError, KeyError):
376 pass
373 pass
377 else:
374 else:
378 return printer(obj, self, cycle)
375 return printer(obj, self, cycle)
379 # Next walk the mro and check for either:
376 # Next walk the mro and check for either:
380 # 1) a registered printer
377 # 1) a registered printer
381 # 2) a _repr_pretty_ method
378 # 2) a _repr_pretty_ method
382 for cls in _get_mro(obj_class):
379 for cls in _get_mro(obj_class):
383 if cls in self.type_pprinters:
380 if cls in self.type_pprinters:
384 # printer registered in self.type_pprinters
381 # printer registered in self.type_pprinters
385 return self.type_pprinters[cls](obj, self, cycle)
382 return self.type_pprinters[cls](obj, self, cycle)
386 else:
383 else:
387 # deferred printer
384 # deferred printer
388 printer = self._in_deferred_types(cls)
385 printer = self._in_deferred_types(cls)
389 if printer is not None:
386 if printer is not None:
390 return printer(obj, self, cycle)
387 return printer(obj, self, cycle)
391 else:
388 else:
392 # Finally look for special method names.
389 # Finally look for special method names.
393 # Some objects automatically create any requested
390 # Some objects automatically create any requested
394 # attribute. Try to ignore most of them by checking for
391 # attribute. Try to ignore most of them by checking for
395 # callability.
392 # callability.
396 if '_repr_pretty_' in cls.__dict__:
393 if '_repr_pretty_' in cls.__dict__:
397 meth = cls._repr_pretty_
394 meth = cls._repr_pretty_
398 if callable(meth):
395 if callable(meth):
399 return meth(obj, self, cycle)
396 return meth(obj, self, cycle)
400 if cls is not object \
397 if cls is not object \
401 and callable(cls.__dict__.get('__repr__')):
398 and callable(cls.__dict__.get('__repr__')):
402 return _repr_pprint(obj, self, cycle)
399 return _repr_pprint(obj, self, cycle)
403
400
404 return _default_pprint(obj, self, cycle)
401 return _default_pprint(obj, self, cycle)
405 finally:
402 finally:
406 self.end_group()
403 self.end_group()
407 self.stack.pop()
404 self.stack.pop()
408
405
409 def _in_deferred_types(self, cls):
406 def _in_deferred_types(self, cls):
410 """
407 """
411 Check if the given class is specified in the deferred type registry.
408 Check if the given class is specified in the deferred type registry.
412
409
413 Returns the printer from the registry if it exists, and None if the
410 Returns the printer from the registry if it exists, and None if the
414 class is not in the registry. Successful matches will be moved to the
411 class is not in the registry. Successful matches will be moved to the
415 regular type registry for future use.
412 regular type registry for future use.
416 """
413 """
417 mod = _safe_getattr(cls, '__module__', None)
414 mod = _safe_getattr(cls, '__module__', None)
418 name = _safe_getattr(cls, '__name__', None)
415 name = _safe_getattr(cls, '__name__', None)
419 key = (mod, name)
416 key = (mod, name)
420 printer = None
417 printer = None
421 if key in self.deferred_pprinters:
418 if key in self.deferred_pprinters:
422 # Move the printer over to the regular registry.
419 # Move the printer over to the regular registry.
423 printer = self.deferred_pprinters.pop(key)
420 printer = self.deferred_pprinters.pop(key)
424 self.type_pprinters[cls] = printer
421 self.type_pprinters[cls] = printer
425 return printer
422 return printer
426
423
427
424
428 class Printable(object):
425 class Printable(object):
429
426
430 def output(self, stream, output_width):
427 def output(self, stream, output_width):
431 return output_width
428 return output_width
432
429
433
430
434 class Text(Printable):
431 class Text(Printable):
435
432
436 def __init__(self):
433 def __init__(self):
437 self.objs = []
434 self.objs = []
438 self.width = 0
435 self.width = 0
439
436
440 def output(self, stream, output_width):
437 def output(self, stream, output_width):
441 for obj in self.objs:
438 for obj in self.objs:
442 stream.write(obj)
439 stream.write(obj)
443 return output_width + self.width
440 return output_width + self.width
444
441
445 def add(self, obj, width):
442 def add(self, obj, width):
446 self.objs.append(obj)
443 self.objs.append(obj)
447 self.width += width
444 self.width += width
448
445
449
446
450 class Breakable(Printable):
447 class Breakable(Printable):
451
448
452 def __init__(self, seq, width, pretty):
449 def __init__(self, seq, width, pretty):
453 self.obj = seq
450 self.obj = seq
454 self.width = width
451 self.width = width
455 self.pretty = pretty
452 self.pretty = pretty
456 self.indentation = pretty.indentation
453 self.indentation = pretty.indentation
457 self.group = pretty.group_stack[-1]
454 self.group = pretty.group_stack[-1]
458 self.group.breakables.append(self)
455 self.group.breakables.append(self)
459
456
460 def output(self, stream, output_width):
457 def output(self, stream, output_width):
461 self.group.breakables.popleft()
458 self.group.breakables.popleft()
462 if self.group.want_break:
459 if self.group.want_break:
463 stream.write(self.pretty.newline)
460 stream.write(self.pretty.newline)
464 stream.write(' ' * self.indentation)
461 stream.write(' ' * self.indentation)
465 return self.indentation
462 return self.indentation
466 if not self.group.breakables:
463 if not self.group.breakables:
467 self.pretty.group_queue.remove(self.group)
464 self.pretty.group_queue.remove(self.group)
468 stream.write(self.obj)
465 stream.write(self.obj)
469 return output_width + self.width
466 return output_width + self.width
470
467
471
468
472 class Group(Printable):
469 class Group(Printable):
473
470
474 def __init__(self, depth):
471 def __init__(self, depth):
475 self.depth = depth
472 self.depth = depth
476 self.breakables = deque()
473 self.breakables = deque()
477 self.want_break = False
474 self.want_break = False
478
475
479
476
480 class GroupQueue(object):
477 class GroupQueue(object):
481
478
482 def __init__(self, *groups):
479 def __init__(self, *groups):
483 self.queue = []
480 self.queue = []
484 for group in groups:
481 for group in groups:
485 self.enq(group)
482 self.enq(group)
486
483
487 def enq(self, group):
484 def enq(self, group):
488 depth = group.depth
485 depth = group.depth
489 while depth > len(self.queue) - 1:
486 while depth > len(self.queue) - 1:
490 self.queue.append([])
487 self.queue.append([])
491 self.queue[depth].append(group)
488 self.queue[depth].append(group)
492
489
493 def deq(self):
490 def deq(self):
494 for stack in self.queue:
491 for stack in self.queue:
495 for idx, group in enumerate(reversed(stack)):
492 for idx, group in enumerate(reversed(stack)):
496 if group.breakables:
493 if group.breakables:
497 del stack[idx]
494 del stack[idx]
498 group.want_break = True
495 group.want_break = True
499 return group
496 return group
500 for group in stack:
497 for group in stack:
501 group.want_break = True
498 group.want_break = True
502 del stack[:]
499 del stack[:]
503
500
504 def remove(self, group):
501 def remove(self, group):
505 try:
502 try:
506 self.queue[group.depth].remove(group)
503 self.queue[group.depth].remove(group)
507 except ValueError:
504 except ValueError:
508 pass
505 pass
509
506
510
507
511 def _default_pprint(obj, p, cycle):
508 def _default_pprint(obj, p, cycle):
512 """
509 """
513 The default print function. Used if an object does not provide one and
510 The default print function. Used if an object does not provide one and
514 it's none of the builtin objects.
511 it's none of the builtin objects.
515 """
512 """
516 klass = _safe_getattr(obj, '__class__', None) or type(obj)
513 klass = _safe_getattr(obj, '__class__', None) or type(obj)
517 if _safe_getattr(klass, '__repr__', None) is not object.__repr__:
514 if _safe_getattr(klass, '__repr__', None) is not object.__repr__:
518 # A user-provided repr. Find newlines and replace them with p.break_()
515 # A user-provided repr. Find newlines and replace them with p.break_()
519 _repr_pprint(obj, p, cycle)
516 _repr_pprint(obj, p, cycle)
520 return
517 return
521 p.begin_group(1, '<')
518 p.begin_group(1, '<')
522 p.pretty(klass)
519 p.pretty(klass)
523 p.text(' at 0x%x' % id(obj))
520 p.text(' at 0x%x' % id(obj))
524 if cycle:
521 if cycle:
525 p.text(' ...')
522 p.text(' ...')
526 elif p.verbose:
523 elif p.verbose:
527 first = True
524 first = True
528 for key in dir(obj):
525 for key in dir(obj):
529 if not key.startswith('_'):
526 if not key.startswith('_'):
530 try:
527 try:
531 value = getattr(obj, key)
528 value = getattr(obj, key)
532 except AttributeError:
529 except AttributeError:
533 continue
530 continue
534 if isinstance(value, types.MethodType):
531 if isinstance(value, types.MethodType):
535 continue
532 continue
536 if not first:
533 if not first:
537 p.text(',')
534 p.text(',')
538 p.breakable()
535 p.breakable()
539 p.text(key)
536 p.text(key)
540 p.text('=')
537 p.text('=')
541 step = len(key) + 1
538 step = len(key) + 1
542 p.indentation += step
539 p.indentation += step
543 p.pretty(value)
540 p.pretty(value)
544 p.indentation -= step
541 p.indentation -= step
545 first = False
542 first = False
546 p.end_group(1, '>')
543 p.end_group(1, '>')
547
544
548
545
549 def _seq_pprinter_factory(start, end):
546 def _seq_pprinter_factory(start, end):
550 """
547 """
551 Factory that returns a pprint function useful for sequences. Used by
548 Factory that returns a pprint function useful for sequences. Used by
552 the default pprint for tuples, dicts, and lists.
549 the default pprint for tuples, dicts, and lists.
553 """
550 """
554 def inner(obj, p, cycle):
551 def inner(obj, p, cycle):
555 if cycle:
552 if cycle:
556 return p.text(start + '...' + end)
553 return p.text(start + '...' + end)
557 step = len(start)
554 step = len(start)
558 p.begin_group(step, start)
555 p.begin_group(step, start)
559 for idx, x in p._enumerate(obj):
556 for idx, x in p._enumerate(obj):
560 if idx:
557 if idx:
561 p.text(',')
558 p.text(',')
562 p.breakable()
559 p.breakable()
563 p.pretty(x)
560 p.pretty(x)
564 if len(obj) == 1 and type(obj) is tuple:
561 if len(obj) == 1 and type(obj) is tuple:
565 # Special case for 1-item tuples.
562 # Special case for 1-item tuples.
566 p.text(',')
563 p.text(',')
567 p.end_group(step, end)
564 p.end_group(step, end)
568 return inner
565 return inner
569
566
570
567
571 def _set_pprinter_factory(start, end):
568 def _set_pprinter_factory(start, end):
572 """
569 """
573 Factory that returns a pprint function useful for sets and frozensets.
570 Factory that returns a pprint function useful for sets and frozensets.
574 """
571 """
575 def inner(obj, p, cycle):
572 def inner(obj, p, cycle):
576 if cycle:
573 if cycle:
577 return p.text(start + '...' + end)
574 return p.text(start + '...' + end)
578 if len(obj) == 0:
575 if len(obj) == 0:
579 # Special case.
576 # Special case.
580 p.text(type(obj).__name__ + '()')
577 p.text(type(obj).__name__ + '()')
581 else:
578 else:
582 step = len(start)
579 step = len(start)
583 p.begin_group(step, start)
580 p.begin_group(step, start)
584 # Like dictionary keys, we will try to sort the items if there aren't too many
581 # Like dictionary keys, we will try to sort the items if there aren't too many
585 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
582 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
586 items = _sorted_for_pprint(obj)
583 items = _sorted_for_pprint(obj)
587 else:
584 else:
588 items = obj
585 items = obj
589 for idx, x in p._enumerate(items):
586 for idx, x in p._enumerate(items):
590 if idx:
587 if idx:
591 p.text(',')
588 p.text(',')
592 p.breakable()
589 p.breakable()
593 p.pretty(x)
590 p.pretty(x)
594 p.end_group(step, end)
591 p.end_group(step, end)
595 return inner
592 return inner
596
593
597
594
598 def _dict_pprinter_factory(start, end):
595 def _dict_pprinter_factory(start, end):
599 """
596 """
600 Factory that returns a pprint function used by the default pprint of
597 Factory that returns a pprint function used by the default pprint of
601 dicts and dict proxies.
598 dicts and dict proxies.
602 """
599 """
603 def inner(obj, p, cycle):
600 def inner(obj, p, cycle):
604 if cycle:
601 if cycle:
605 return p.text('{...}')
602 return p.text('{...}')
606 step = len(start)
603 step = len(start)
607 p.begin_group(step, start)
604 p.begin_group(step, start)
608 keys = obj.keys()
605 keys = obj.keys()
609 # if dict isn't large enough to be truncated, sort keys before displaying
610 # From Python 3.7, dicts preserve order by definition, so we don't sort.
611 if not DICT_IS_ORDERED \
612 and not (p.max_seq_length and len(obj) >= p.max_seq_length):
613 keys = _sorted_for_pprint(keys)
614 for idx, key in p._enumerate(keys):
606 for idx, key in p._enumerate(keys):
615 if idx:
607 if idx:
616 p.text(',')
608 p.text(',')
617 p.breakable()
609 p.breakable()
618 p.pretty(key)
610 p.pretty(key)
619 p.text(': ')
611 p.text(': ')
620 p.pretty(obj[key])
612 p.pretty(obj[key])
621 p.end_group(step, end)
613 p.end_group(step, end)
622 return inner
614 return inner
623
615
624
616
625 def _super_pprint(obj, p, cycle):
617 def _super_pprint(obj, p, cycle):
626 """The pprint for the super type."""
618 """The pprint for the super type."""
627 p.begin_group(8, '<super: ')
619 p.begin_group(8, '<super: ')
628 p.pretty(obj.__thisclass__)
620 p.pretty(obj.__thisclass__)
629 p.text(',')
621 p.text(',')
630 p.breakable()
622 p.breakable()
631 if PYPY: # In PyPy, super() objects don't have __self__ attributes
623 if PYPY: # In PyPy, super() objects don't have __self__ attributes
632 dself = obj.__repr__.__self__
624 dself = obj.__repr__.__self__
633 p.pretty(None if dself is obj else dself)
625 p.pretty(None if dself is obj else dself)
634 else:
626 else:
635 p.pretty(obj.__self__)
627 p.pretty(obj.__self__)
636 p.end_group(8, '>')
628 p.end_group(8, '>')
637
629
638
630
639 def _re_pattern_pprint(obj, p, cycle):
631 def _re_pattern_pprint(obj, p, cycle):
640 """The pprint function for regular expression patterns."""
632 """The pprint function for regular expression patterns."""
641 p.text('re.compile(')
633 p.text('re.compile(')
642 pattern = repr(obj.pattern)
634 pattern = repr(obj.pattern)
643 if pattern[:1] in 'uU':
635 if pattern[:1] in 'uU':
644 pattern = pattern[1:]
636 pattern = pattern[1:]
645 prefix = 'ur'
637 prefix = 'ur'
646 else:
638 else:
647 prefix = 'r'
639 prefix = 'r'
648 pattern = prefix + pattern.replace('\\\\', '\\')
640 pattern = prefix + pattern.replace('\\\\', '\\')
649 p.text(pattern)
641 p.text(pattern)
650 if obj.flags:
642 if obj.flags:
651 p.text(',')
643 p.text(',')
652 p.breakable()
644 p.breakable()
653 done_one = False
645 done_one = False
654 for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
646 for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
655 'UNICODE', 'VERBOSE', 'DEBUG'):
647 'UNICODE', 'VERBOSE', 'DEBUG'):
656 if obj.flags & getattr(re, flag):
648 if obj.flags & getattr(re, flag):
657 if done_one:
649 if done_one:
658 p.text('|')
650 p.text('|')
659 p.text('re.' + flag)
651 p.text('re.' + flag)
660 done_one = True
652 done_one = True
661 p.text(')')
653 p.text(')')
662
654
663
655
664 def _type_pprint(obj, p, cycle):
656 def _type_pprint(obj, p, cycle):
665 """The pprint for classes and types."""
657 """The pprint for classes and types."""
666 # Heap allocated types might not have the module attribute,
658 # Heap allocated types might not have the module attribute,
667 # and others may set it to None.
659 # and others may set it to None.
668
660
669 # Checks for a __repr__ override in the metaclass. Can't compare the
661 # Checks for a __repr__ override in the metaclass. Can't compare the
670 # type(obj).__repr__ directly because in PyPy the representation function
662 # type(obj).__repr__ directly because in PyPy the representation function
671 # inherited from type isn't the same type.__repr__
663 # inherited from type isn't the same type.__repr__
672 if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
664 if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
673 _repr_pprint(obj, p, cycle)
665 _repr_pprint(obj, p, cycle)
674 return
666 return
675
667
676 mod = _safe_getattr(obj, '__module__', None)
668 mod = _safe_getattr(obj, '__module__', None)
677 try:
669 try:
678 name = obj.__qualname__
670 name = obj.__qualname__
679 if not isinstance(name, str):
671 if not isinstance(name, str):
680 # This can happen if the type implements __qualname__ as a property
672 # This can happen if the type implements __qualname__ as a property
681 # or other descriptor in Python 2.
673 # or other descriptor in Python 2.
682 raise Exception("Try __name__")
674 raise Exception("Try __name__")
683 except Exception:
675 except Exception:
684 name = obj.__name__
676 name = obj.__name__
685 if not isinstance(name, str):
677 if not isinstance(name, str):
686 name = '<unknown type>'
678 name = '<unknown type>'
687
679
688 if mod in (None, '__builtin__', 'builtins', 'exceptions'):
680 if mod in (None, '__builtin__', 'builtins', 'exceptions'):
689 p.text(name)
681 p.text(name)
690 else:
682 else:
691 p.text(mod + '.' + name)
683 p.text(mod + '.' + name)
692
684
693
685
694 def _repr_pprint(obj, p, cycle):
686 def _repr_pprint(obj, p, cycle):
695 """A pprint that just redirects to the normal repr function."""
687 """A pprint that just redirects to the normal repr function."""
696 # Find newlines and replace them with p.break_()
688 # Find newlines and replace them with p.break_()
697 output = repr(obj)
689 output = repr(obj)
698 for idx,output_line in enumerate(output.splitlines()):
690 for idx,output_line in enumerate(output.splitlines()):
699 if idx:
691 if idx:
700 p.break_()
692 p.break_()
701 p.text(output_line)
693 p.text(output_line)
702
694
703
695
704 def _function_pprint(obj, p, cycle):
696 def _function_pprint(obj, p, cycle):
705 """Base pprint for all functions and builtin functions."""
697 """Base pprint for all functions and builtin functions."""
706 name = _safe_getattr(obj, '__qualname__', obj.__name__)
698 name = _safe_getattr(obj, '__qualname__', obj.__name__)
707 mod = obj.__module__
699 mod = obj.__module__
708 if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
700 if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
709 name = mod + '.' + name
701 name = mod + '.' + name
710 try:
702 try:
711 func_def = name + str(signature(obj))
703 func_def = name + str(signature(obj))
712 except ValueError:
704 except ValueError:
713 func_def = name
705 func_def = name
714 p.text('<function %s>' % func_def)
706 p.text('<function %s>' % func_def)
715
707
716
708
717 def _exception_pprint(obj, p, cycle):
709 def _exception_pprint(obj, p, cycle):
718 """Base pprint for all exceptions."""
710 """Base pprint for all exceptions."""
719 name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
711 name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
720 if obj.__class__.__module__ not in ('exceptions', 'builtins'):
712 if obj.__class__.__module__ not in ('exceptions', 'builtins'):
721 name = '%s.%s' % (obj.__class__.__module__, name)
713 name = '%s.%s' % (obj.__class__.__module__, name)
722 step = len(name) + 1
714 step = len(name) + 1
723 p.begin_group(step, name + '(')
715 p.begin_group(step, name + '(')
724 for idx, arg in enumerate(getattr(obj, 'args', ())):
716 for idx, arg in enumerate(getattr(obj, 'args', ())):
725 if idx:
717 if idx:
726 p.text(',')
718 p.text(',')
727 p.breakable()
719 p.breakable()
728 p.pretty(arg)
720 p.pretty(arg)
729 p.end_group(step, ')')
721 p.end_group(step, ')')
730
722
731
723
732 #: the exception base
724 #: the exception base
733 try:
725 try:
734 _exception_base = BaseException
726 _exception_base = BaseException
735 except NameError:
727 except NameError:
736 _exception_base = Exception
728 _exception_base = Exception
737
729
738
730
739 #: printers for builtin types
731 #: printers for builtin types
740 _type_pprinters = {
732 _type_pprinters = {
741 int: _repr_pprint,
733 int: _repr_pprint,
742 float: _repr_pprint,
734 float: _repr_pprint,
743 str: _repr_pprint,
735 str: _repr_pprint,
744 tuple: _seq_pprinter_factory('(', ')'),
736 tuple: _seq_pprinter_factory('(', ')'),
745 list: _seq_pprinter_factory('[', ']'),
737 list: _seq_pprinter_factory('[', ']'),
746 dict: _dict_pprinter_factory('{', '}'),
738 dict: _dict_pprinter_factory('{', '}'),
747 set: _set_pprinter_factory('{', '}'),
739 set: _set_pprinter_factory('{', '}'),
748 frozenset: _set_pprinter_factory('frozenset({', '})'),
740 frozenset: _set_pprinter_factory('frozenset({', '})'),
749 super: _super_pprint,
741 super: _super_pprint,
750 _re_pattern_type: _re_pattern_pprint,
742 _re_pattern_type: _re_pattern_pprint,
751 type: _type_pprint,
743 type: _type_pprint,
752 types.FunctionType: _function_pprint,
744 types.FunctionType: _function_pprint,
753 types.BuiltinFunctionType: _function_pprint,
745 types.BuiltinFunctionType: _function_pprint,
754 types.MethodType: _repr_pprint,
746 types.MethodType: _repr_pprint,
755 datetime.datetime: _repr_pprint,
747 datetime.datetime: _repr_pprint,
756 datetime.timedelta: _repr_pprint,
748 datetime.timedelta: _repr_pprint,
757 _exception_base: _exception_pprint
749 _exception_base: _exception_pprint
758 }
750 }
759
751
760 # render os.environ like a dict
752 # render os.environ like a dict
761 _env_type = type(os.environ)
753 _env_type = type(os.environ)
762 # future-proof in case os.environ becomes a plain dict?
754 # future-proof in case os.environ becomes a plain dict?
763 if _env_type is not dict:
755 if _env_type is not dict:
764 _type_pprinters[_env_type] = _dict_pprinter_factory('environ{', '}')
756 _type_pprinters[_env_type] = _dict_pprinter_factory('environ{', '}')
765
757
766 try:
758 try:
767 # In PyPy, types.DictProxyType is dict, setting the dictproxy printer
759 # In PyPy, types.DictProxyType is dict, setting the dictproxy printer
768 # using dict.setdefault avoids overwriting the dict printer
760 # using dict.setdefault avoids overwriting the dict printer
769 _type_pprinters.setdefault(types.DictProxyType,
761 _type_pprinters.setdefault(types.DictProxyType,
770 _dict_pprinter_factory('dict_proxy({', '})'))
762 _dict_pprinter_factory('dict_proxy({', '})'))
771 _type_pprinters[types.ClassType] = _type_pprint
763 _type_pprinters[types.ClassType] = _type_pprint
772 _type_pprinters[types.SliceType] = _repr_pprint
764 _type_pprinters[types.SliceType] = _repr_pprint
773 except AttributeError: # Python 3
765 except AttributeError: # Python 3
774 _type_pprinters[types.MappingProxyType] = \
766 _type_pprinters[types.MappingProxyType] = \
775 _dict_pprinter_factory('mappingproxy({', '})')
767 _dict_pprinter_factory('mappingproxy({', '})')
776 _type_pprinters[slice] = _repr_pprint
768 _type_pprinters[slice] = _repr_pprint
777
769
778 try:
770 try:
779 _type_pprinters[long] = _repr_pprint
771 _type_pprinters[long] = _repr_pprint
780 _type_pprinters[unicode] = _repr_pprint
772 _type_pprinters[unicode] = _repr_pprint
781 except NameError:
773 except NameError:
782 _type_pprinters[range] = _repr_pprint
774 _type_pprinters[range] = _repr_pprint
783 _type_pprinters[bytes] = _repr_pprint
775 _type_pprinters[bytes] = _repr_pprint
784
776
785 #: printers for types specified by name
777 #: printers for types specified by name
786 _deferred_type_pprinters = {
778 _deferred_type_pprinters = {
787 }
779 }
788
780
789 def for_type(typ, func):
781 def for_type(typ, func):
790 """
782 """
791 Add a pretty printer for a given type.
783 Add a pretty printer for a given type.
792 """
784 """
793 oldfunc = _type_pprinters.get(typ, None)
785 oldfunc = _type_pprinters.get(typ, None)
794 if func is not None:
786 if func is not None:
795 # To support easy restoration of old pprinters, we need to ignore Nones.
787 # To support easy restoration of old pprinters, we need to ignore Nones.
796 _type_pprinters[typ] = func
788 _type_pprinters[typ] = func
797 return oldfunc
789 return oldfunc
798
790
799 def for_type_by_name(type_module, type_name, func):
791 def for_type_by_name(type_module, type_name, func):
800 """
792 """
801 Add a pretty printer for a type specified by the module and name of a type
793 Add a pretty printer for a type specified by the module and name of a type
802 rather than the type object itself.
794 rather than the type object itself.
803 """
795 """
804 key = (type_module, type_name)
796 key = (type_module, type_name)
805 oldfunc = _deferred_type_pprinters.get(key, None)
797 oldfunc = _deferred_type_pprinters.get(key, None)
806 if func is not None:
798 if func is not None:
807 # To support easy restoration of old pprinters, we need to ignore Nones.
799 # To support easy restoration of old pprinters, we need to ignore Nones.
808 _deferred_type_pprinters[key] = func
800 _deferred_type_pprinters[key] = func
809 return oldfunc
801 return oldfunc
810
802
811
803
812 #: printers for the default singletons
804 #: printers for the default singletons
813 _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
805 _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
814 NotImplemented]), _repr_pprint)
806 NotImplemented]), _repr_pprint)
815
807
816
808
817 def _defaultdict_pprint(obj, p, cycle):
809 def _defaultdict_pprint(obj, p, cycle):
818 name = obj.__class__.__name__
810 name = obj.__class__.__name__
819 with p.group(len(name) + 1, name + '(', ')'):
811 with p.group(len(name) + 1, name + '(', ')'):
820 if cycle:
812 if cycle:
821 p.text('...')
813 p.text('...')
822 else:
814 else:
823 p.pretty(obj.default_factory)
815 p.pretty(obj.default_factory)
824 p.text(',')
816 p.text(',')
825 p.breakable()
817 p.breakable()
826 p.pretty(dict(obj))
818 p.pretty(dict(obj))
827
819
828 def _ordereddict_pprint(obj, p, cycle):
820 def _ordereddict_pprint(obj, p, cycle):
829 name = obj.__class__.__name__
821 name = obj.__class__.__name__
830 with p.group(len(name) + 1, name + '(', ')'):
822 with p.group(len(name) + 1, name + '(', ')'):
831 if cycle:
823 if cycle:
832 p.text('...')
824 p.text('...')
833 elif len(obj):
825 elif len(obj):
834 p.pretty(list(obj.items()))
826 p.pretty(list(obj.items()))
835
827
836 def _deque_pprint(obj, p, cycle):
828 def _deque_pprint(obj, p, cycle):
837 name = obj.__class__.__name__
829 name = obj.__class__.__name__
838 with p.group(len(name) + 1, name + '(', ')'):
830 with p.group(len(name) + 1, name + '(', ')'):
839 if cycle:
831 if cycle:
840 p.text('...')
832 p.text('...')
841 else:
833 else:
842 p.pretty(list(obj))
834 p.pretty(list(obj))
843
835
844
836
845 def _counter_pprint(obj, p, cycle):
837 def _counter_pprint(obj, p, cycle):
846 name = obj.__class__.__name__
838 name = obj.__class__.__name__
847 with p.group(len(name) + 1, name + '(', ')'):
839 with p.group(len(name) + 1, name + '(', ')'):
848 if cycle:
840 if cycle:
849 p.text('...')
841 p.text('...')
850 elif len(obj):
842 elif len(obj):
851 p.pretty(dict(obj))
843 p.pretty(dict(obj))
852
844
853 for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
845 for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
854 for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
846 for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
855 for_type_by_name('collections', 'deque', _deque_pprint)
847 for_type_by_name('collections', 'deque', _deque_pprint)
856 for_type_by_name('collections', 'Counter', _counter_pprint)
848 for_type_by_name('collections', 'Counter', _counter_pprint)
857
849
858 if __name__ == '__main__':
850 if __name__ == '__main__':
859 from random import randrange
851 from random import randrange
860 class Foo(object):
852 class Foo(object):
861 def __init__(self):
853 def __init__(self):
862 self.foo = 1
854 self.foo = 1
863 self.bar = re.compile(r'\s+')
855 self.bar = re.compile(r'\s+')
864 self.blub = dict.fromkeys(range(30), randrange(1, 40))
856 self.blub = dict.fromkeys(range(30), randrange(1, 40))
865 self.hehe = 23424.234234
857 self.hehe = 23424.234234
866 self.list = ["blub", "blah", self]
858 self.list = ["blub", "blah", self]
867
859
868 def get_foo(self):
860 def get_foo(self):
869 print("foo")
861 print("foo")
870
862
871 pprint(Foo(), verbose=True)
863 pprint(Foo(), verbose=True)
General Comments 0
You need to be logged in to leave comments. Login now