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