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