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