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