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