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