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