##// END OF EJS Templates
protect against broken repr in lib.pretty
MinRK -
Show More
@@ -1,657 +1,654 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Display formatters.
2 """Display formatters.
3
3
4 Inheritance diagram:
4 Inheritance diagram:
5
5
6 .. inheritance-diagram:: IPython.core.formatters
6 .. inheritance-diagram:: IPython.core.formatters
7 :parts: 3
7 :parts: 3
8
8
9 Authors:
9 Authors:
10
10
11 * Robert Kern
11 * Robert Kern
12 * Brian Granger
12 * Brian Granger
13 """
13 """
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Copyright (C) 2010-2011, IPython Development Team.
15 # Copyright (C) 2010-2011, IPython Development Team.
16 #
16 #
17 # Distributed under the terms of the Modified BSD License.
17 # Distributed under the terms of the Modified BSD License.
18 #
18 #
19 # The full license is in the file COPYING.txt, distributed with this software.
19 # The full license is in the file COPYING.txt, distributed with this software.
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 # Stdlib imports
26 # Stdlib imports
27 import abc
27 import abc
28 import sys
28 import sys
29 import warnings
29 import warnings
30
30
31 # Our own imports
31 # Our own imports
32 from IPython.config.configurable import Configurable
32 from IPython.config.configurable import Configurable
33 from IPython.lib import pretty
33 from IPython.lib import pretty
34 from IPython.utils.traitlets import (
34 from IPython.utils.traitlets import (
35 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
35 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
36 )
36 )
37 from IPython.utils.py3compat import unicode_to_str, with_metaclass, PY3
37 from IPython.utils.py3compat import unicode_to_str, with_metaclass, PY3
38
38
39 if PY3:
39 if PY3:
40 from io import StringIO
40 from io import StringIO
41 else:
41 else:
42 from StringIO import StringIO
42 from StringIO import StringIO
43
43
44
44
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46 # The main DisplayFormatter class
46 # The main DisplayFormatter class
47 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
48
48
49
49
50 class DisplayFormatter(Configurable):
50 class DisplayFormatter(Configurable):
51
51
52 # When set to true only the default plain text formatter will be used.
52 # When set to true only the default plain text formatter will be used.
53 plain_text_only = Bool(False, config=True)
53 plain_text_only = Bool(False, config=True)
54 def _plain_text_only_changed(self, name, old, new):
54 def _plain_text_only_changed(self, name, old, new):
55 warnings.warn("""DisplayFormatter.plain_text_only is deprecated.
55 warnings.warn("""DisplayFormatter.plain_text_only is deprecated.
56
56
57 Use DisplayFormatter.active_types = ['text/plain']
57 Use DisplayFormatter.active_types = ['text/plain']
58 for the same effect.
58 for the same effect.
59 """, DeprecationWarning)
59 """, DeprecationWarning)
60 if new:
60 if new:
61 self.active_types = ['text/plain']
61 self.active_types = ['text/plain']
62 else:
62 else:
63 self.active_types = self.format_types
63 self.active_types = self.format_types
64
64
65 active_types = List(Unicode, config=True,
65 active_types = List(Unicode, config=True,
66 help="""List of currently active mime-types to display.
66 help="""List of currently active mime-types to display.
67 You can use this to set a white-list for formats to display.
67 You can use this to set a white-list for formats to display.
68
68
69 Most users will not need to change this value.
69 Most users will not need to change this value.
70 """)
70 """)
71 def _active_types_default(self):
71 def _active_types_default(self):
72 return self.format_types
72 return self.format_types
73
73
74 def _active_types_changed(self, name, old, new):
74 def _active_types_changed(self, name, old, new):
75 for key, formatter in self.formatters.items():
75 for key, formatter in self.formatters.items():
76 if key in new:
76 if key in new:
77 formatter.enabled = True
77 formatter.enabled = True
78 else:
78 else:
79 formatter.enabled = False
79 formatter.enabled = False
80
80
81 # A dict of formatter whose keys are format types (MIME types) and whose
81 # A dict of formatter whose keys are format types (MIME types) and whose
82 # values are subclasses of BaseFormatter.
82 # values are subclasses of BaseFormatter.
83 formatters = Dict()
83 formatters = Dict()
84 def _formatters_default(self):
84 def _formatters_default(self):
85 """Activate the default formatters."""
85 """Activate the default formatters."""
86 formatter_classes = [
86 formatter_classes = [
87 PlainTextFormatter,
87 PlainTextFormatter,
88 HTMLFormatter,
88 HTMLFormatter,
89 SVGFormatter,
89 SVGFormatter,
90 PNGFormatter,
90 PNGFormatter,
91 JPEGFormatter,
91 JPEGFormatter,
92 LatexFormatter,
92 LatexFormatter,
93 JSONFormatter,
93 JSONFormatter,
94 JavascriptFormatter
94 JavascriptFormatter
95 ]
95 ]
96 d = {}
96 d = {}
97 for cls in formatter_classes:
97 for cls in formatter_classes:
98 f = cls(parent=self)
98 f = cls(parent=self)
99 d[f.format_type] = f
99 d[f.format_type] = f
100 return d
100 return d
101
101
102 def format(self, obj, include=None, exclude=None):
102 def format(self, obj, include=None, exclude=None):
103 """Return a format data dict for an object.
103 """Return a format data dict for an object.
104
104
105 By default all format types will be computed.
105 By default all format types will be computed.
106
106
107 The following MIME types are currently implemented:
107 The following MIME types are currently implemented:
108
108
109 * text/plain
109 * text/plain
110 * text/html
110 * text/html
111 * text/latex
111 * text/latex
112 * application/json
112 * application/json
113 * application/javascript
113 * application/javascript
114 * image/png
114 * image/png
115 * image/jpeg
115 * image/jpeg
116 * image/svg+xml
116 * image/svg+xml
117
117
118 Parameters
118 Parameters
119 ----------
119 ----------
120 obj : object
120 obj : object
121 The Python object whose format data will be computed.
121 The Python object whose format data will be computed.
122 include : list or tuple, optional
122 include : list or tuple, optional
123 A list of format type strings (MIME types) to include in the
123 A list of format type strings (MIME types) to include in the
124 format data dict. If this is set *only* the format types included
124 format data dict. If this is set *only* the format types included
125 in this list will be computed.
125 in this list will be computed.
126 exclude : list or tuple, optional
126 exclude : list or tuple, optional
127 A list of format type string (MIME types) to exclude in the format
127 A list of format type string (MIME types) to exclude in the format
128 data dict. If this is set all format types will be computed,
128 data dict. If this is set all format types will be computed,
129 except for those included in this argument.
129 except for those included in this argument.
130
130
131 Returns
131 Returns
132 -------
132 -------
133 (format_dict, metadata_dict) : tuple of two dicts
133 (format_dict, metadata_dict) : tuple of two dicts
134
134
135 format_dict is a dictionary of key/value pairs, one of each format that was
135 format_dict is a dictionary of key/value pairs, one of each format that was
136 generated for the object. The keys are the format types, which
136 generated for the object. The keys are the format types, which
137 will usually be MIME type strings and the values and JSON'able
137 will usually be MIME type strings and the values and JSON'able
138 data structure containing the raw data for the representation in
138 data structure containing the raw data for the representation in
139 that format.
139 that format.
140
140
141 metadata_dict is a dictionary of metadata about each mime-type output.
141 metadata_dict is a dictionary of metadata about each mime-type output.
142 Its keys will be a strict subset of the keys in format_dict.
142 Its keys will be a strict subset of the keys in format_dict.
143 """
143 """
144 format_dict = {}
144 format_dict = {}
145 md_dict = {}
145 md_dict = {}
146
146
147 for format_type, formatter in self.formatters.items():
147 for format_type, formatter in self.formatters.items():
148 if include and format_type not in include:
148 if include and format_type not in include:
149 continue
149 continue
150 if exclude and format_type in exclude:
150 if exclude and format_type in exclude:
151 continue
151 continue
152
152
153 md = None
153 md = None
154 try:
154 try:
155 data = formatter(obj)
155 data = formatter(obj)
156 except:
156 except:
157 # FIXME: log the exception
157 # FIXME: log the exception
158 raise
158 raise
159
159
160 # formatters can return raw data or (data, metadata)
160 # formatters can return raw data or (data, metadata)
161 if isinstance(data, tuple) and len(data) == 2:
161 if isinstance(data, tuple) and len(data) == 2:
162 data, md = data
162 data, md = data
163
163
164 if data is not None:
164 if data is not None:
165 format_dict[format_type] = data
165 format_dict[format_type] = data
166 if md is not None:
166 if md is not None:
167 md_dict[format_type] = md
167 md_dict[format_type] = md
168
168
169 return format_dict, md_dict
169 return format_dict, md_dict
170
170
171 @property
171 @property
172 def format_types(self):
172 def format_types(self):
173 """Return the format types (MIME types) of the active formatters."""
173 """Return the format types (MIME types) of the active formatters."""
174 return list(self.formatters.keys())
174 return list(self.formatters.keys())
175
175
176
176
177 #-----------------------------------------------------------------------------
177 #-----------------------------------------------------------------------------
178 # Formatters for specific format types (text, html, svg, etc.)
178 # Formatters for specific format types (text, html, svg, etc.)
179 #-----------------------------------------------------------------------------
179 #-----------------------------------------------------------------------------
180
180
181
181
182 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
182 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
183 """ Abstract base class for Formatters.
183 """ Abstract base class for Formatters.
184
184
185 A formatter is a callable class that is responsible for computing the
185 A formatter is a callable class that is responsible for computing the
186 raw format data for a particular format type (MIME type). For example,
186 raw format data for a particular format type (MIME type). For example,
187 an HTML formatter would have a format type of `text/html` and would return
187 an HTML formatter would have a format type of `text/html` and would return
188 the HTML representation of the object when called.
188 the HTML representation of the object when called.
189 """
189 """
190
190
191 # The format type of the data returned, usually a MIME type.
191 # The format type of the data returned, usually a MIME type.
192 format_type = 'text/plain'
192 format_type = 'text/plain'
193
193
194 # Is the formatter enabled...
194 # Is the formatter enabled...
195 enabled = True
195 enabled = True
196
196
197 @abc.abstractmethod
197 @abc.abstractmethod
198 def __call__(self, obj):
198 def __call__(self, obj):
199 """Return a JSON'able representation of the object.
199 """Return a JSON'able representation of the object.
200
200
201 If the object cannot be formatted by this formatter, then return None
201 If the object cannot be formatted by this formatter, then return None
202 """
202 """
203 try:
203 try:
204 return repr(obj)
204 return repr(obj)
205 except TypeError:
205 except Exception:
206 return None
206 return None
207
207
208
208
209 class BaseFormatter(Configurable):
209 class BaseFormatter(Configurable):
210 """A base formatter class that is configurable.
210 """A base formatter class that is configurable.
211
211
212 This formatter should usually be used as the base class of all formatters.
212 This formatter should usually be used as the base class of all formatters.
213 It is a traited :class:`Configurable` class and includes an extensible
213 It is a traited :class:`Configurable` class and includes an extensible
214 API for users to determine how their objects are formatted. The following
214 API for users to determine how their objects are formatted. The following
215 logic is used to find a function to format an given object.
215 logic is used to find a function to format an given object.
216
216
217 1. The object is introspected to see if it has a method with the name
217 1. The object is introspected to see if it has a method with the name
218 :attr:`print_method`. If is does, that object is passed to that method
218 :attr:`print_method`. If is does, that object is passed to that method
219 for formatting.
219 for formatting.
220 2. If no print method is found, three internal dictionaries are consulted
220 2. If no print method is found, three internal dictionaries are consulted
221 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
221 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
222 and :attr:`deferred_printers`.
222 and :attr:`deferred_printers`.
223
223
224 Users should use these dictionaries to register functions that will be
224 Users should use these dictionaries to register functions that will be
225 used to compute the format data for their objects (if those objects don't
225 used to compute the format data for their objects (if those objects don't
226 have the special print methods). The easiest way of using these
226 have the special print methods). The easiest way of using these
227 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
227 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
228 methods.
228 methods.
229
229
230 If no function/callable is found to compute the format data, ``None`` is
230 If no function/callable is found to compute the format data, ``None`` is
231 returned and this format type is not used.
231 returned and this format type is not used.
232 """
232 """
233
233
234 format_type = Unicode('text/plain')
234 format_type = Unicode('text/plain')
235
235
236 enabled = Bool(True, config=True)
236 enabled = Bool(True, config=True)
237
237
238 print_method = ObjectName('__repr__')
238 print_method = ObjectName('__repr__')
239
239
240 # The singleton printers.
240 # The singleton printers.
241 # Maps the IDs of the builtin singleton objects to the format functions.
241 # Maps the IDs of the builtin singleton objects to the format functions.
242 singleton_printers = Dict(config=True)
242 singleton_printers = Dict(config=True)
243 def _singleton_printers_default(self):
243 def _singleton_printers_default(self):
244 return {}
244 return {}
245
245
246 # The type-specific printers.
246 # The type-specific printers.
247 # Map type objects to the format functions.
247 # Map type objects to the format functions.
248 type_printers = Dict(config=True)
248 type_printers = Dict(config=True)
249 def _type_printers_default(self):
249 def _type_printers_default(self):
250 return {}
250 return {}
251
251
252 # The deferred-import type-specific printers.
252 # The deferred-import type-specific printers.
253 # Map (modulename, classname) pairs to the format functions.
253 # Map (modulename, classname) pairs to the format functions.
254 deferred_printers = Dict(config=True)
254 deferred_printers = Dict(config=True)
255 def _deferred_printers_default(self):
255 def _deferred_printers_default(self):
256 return {}
256 return {}
257
257
258 def __call__(self, obj):
258 def __call__(self, obj):
259 """Compute the format for an object."""
259 """Compute the format for an object."""
260 if self.enabled:
260 if self.enabled:
261 obj_id = id(obj)
261 obj_id = id(obj)
262 try:
262 try:
263 obj_class = getattr(obj, '__class__', None) or type(obj)
263 obj_class = getattr(obj, '__class__', None) or type(obj)
264 # First try to find registered singleton printers for the type.
264 # First try to find registered singleton printers for the type.
265 try:
265 try:
266 printer = self.singleton_printers[obj_id]
266 printer = self.singleton_printers[obj_id]
267 except (TypeError, KeyError):
267 except (TypeError, KeyError):
268 pass
268 pass
269 else:
269 else:
270 return printer(obj)
270 return printer(obj)
271 # Next look for type_printers.
271 # Next look for type_printers.
272 for cls in pretty._get_mro(obj_class):
272 for cls in pretty._get_mro(obj_class):
273 if cls in self.type_printers:
273 if cls in self.type_printers:
274 return self.type_printers[cls](obj)
274 return self.type_printers[cls](obj)
275 else:
275 else:
276 printer = self._in_deferred_types(cls)
276 printer = self._in_deferred_types(cls)
277 if printer is not None:
277 if printer is not None:
278 return printer(obj)
278 return printer(obj)
279 # Finally look for special method names.
279 # Finally look for special method names.
280 if hasattr(obj_class, self.print_method):
280 if hasattr(obj_class, self.print_method):
281 printer = getattr(obj_class, self.print_method)
281 printer = getattr(obj_class, self.print_method)
282 return printer(obj)
282 return printer(obj)
283 return None
283 return None
284 except Exception:
284 except Exception:
285 pass
285 pass
286 else:
286 else:
287 return None
287 return None
288
288
289 def for_type(self, typ, func):
289 def for_type(self, typ, func):
290 """Add a format function for a given type.
290 """Add a format function for a given type.
291
291
292 Parameters
292 Parameters
293 -----------
293 -----------
294 typ : class
294 typ : class
295 The class of the object that will be formatted using `func`.
295 The class of the object that will be formatted using `func`.
296 func : callable
296 func : callable
297 The callable that will be called to compute the format data. The
297 The callable that will be called to compute the format data. The
298 call signature of this function is simple, it must take the
298 call signature of this function is simple, it must take the
299 object to be formatted and return the raw data for the given
299 object to be formatted and return the raw data for the given
300 format. Subclasses may use a different call signature for the
300 format. Subclasses may use a different call signature for the
301 `func` argument.
301 `func` argument.
302 """
302 """
303 oldfunc = self.type_printers.get(typ, None)
303 oldfunc = self.type_printers.get(typ, None)
304 if func is not None:
304 if func is not None:
305 # To support easy restoration of old printers, we need to ignore
305 # To support easy restoration of old printers, we need to ignore
306 # Nones.
306 # Nones.
307 self.type_printers[typ] = func
307 self.type_printers[typ] = func
308 return oldfunc
308 return oldfunc
309
309
310 def for_type_by_name(self, type_module, type_name, func):
310 def for_type_by_name(self, type_module, type_name, func):
311 """Add a format function for a type specified by the full dotted
311 """Add a format function for a type specified by the full dotted
312 module and name of the type, rather than the type of the object.
312 module and name of the type, rather than the type of the object.
313
313
314 Parameters
314 Parameters
315 ----------
315 ----------
316 type_module : str
316 type_module : str
317 The full dotted name of the module the type is defined in, like
317 The full dotted name of the module the type is defined in, like
318 ``numpy``.
318 ``numpy``.
319 type_name : str
319 type_name : str
320 The name of the type (the class name), like ``dtype``
320 The name of the type (the class name), like ``dtype``
321 func : callable
321 func : callable
322 The callable that will be called to compute the format data. The
322 The callable that will be called to compute the format data. The
323 call signature of this function is simple, it must take the
323 call signature of this function is simple, it must take the
324 object to be formatted and return the raw data for the given
324 object to be formatted and return the raw data for the given
325 format. Subclasses may use a different call signature for the
325 format. Subclasses may use a different call signature for the
326 `func` argument.
326 `func` argument.
327 """
327 """
328 key = (type_module, type_name)
328 key = (type_module, type_name)
329 oldfunc = self.deferred_printers.get(key, None)
329 oldfunc = self.deferred_printers.get(key, None)
330 if func is not None:
330 if func is not None:
331 # To support easy restoration of old printers, we need to ignore
331 # To support easy restoration of old printers, we need to ignore
332 # Nones.
332 # Nones.
333 self.deferred_printers[key] = func
333 self.deferred_printers[key] = func
334 return oldfunc
334 return oldfunc
335
335
336 def _in_deferred_types(self, cls):
336 def _in_deferred_types(self, cls):
337 """
337 """
338 Check if the given class is specified in the deferred type registry.
338 Check if the given class is specified in the deferred type registry.
339
339
340 Returns the printer from the registry if it exists, and None if the
340 Returns the printer from the registry if it exists, and None if the
341 class is not in the registry. Successful matches will be moved to the
341 class is not in the registry. Successful matches will be moved to the
342 regular type registry for future use.
342 regular type registry for future use.
343 """
343 """
344 mod = getattr(cls, '__module__', None)
344 mod = getattr(cls, '__module__', None)
345 name = getattr(cls, '__name__', None)
345 name = getattr(cls, '__name__', None)
346 key = (mod, name)
346 key = (mod, name)
347 printer = None
347 printer = None
348 if key in self.deferred_printers:
348 if key in self.deferred_printers:
349 # Move the printer over to the regular registry.
349 # Move the printer over to the regular registry.
350 printer = self.deferred_printers.pop(key)
350 printer = self.deferred_printers.pop(key)
351 self.type_printers[cls] = printer
351 self.type_printers[cls] = printer
352 return printer
352 return printer
353
353
354
354
355 class PlainTextFormatter(BaseFormatter):
355 class PlainTextFormatter(BaseFormatter):
356 """The default pretty-printer.
356 """The default pretty-printer.
357
357
358 This uses :mod:`IPython.lib.pretty` to compute the format data of
358 This uses :mod:`IPython.lib.pretty` to compute the format data of
359 the object. If the object cannot be pretty printed, :func:`repr` is used.
359 the object. If the object cannot be pretty printed, :func:`repr` is used.
360 See the documentation of :mod:`IPython.lib.pretty` for details on
360 See the documentation of :mod:`IPython.lib.pretty` for details on
361 how to write pretty printers. Here is a simple example::
361 how to write pretty printers. Here is a simple example::
362
362
363 def dtype_pprinter(obj, p, cycle):
363 def dtype_pprinter(obj, p, cycle):
364 if cycle:
364 if cycle:
365 return p.text('dtype(...)')
365 return p.text('dtype(...)')
366 if hasattr(obj, 'fields'):
366 if hasattr(obj, 'fields'):
367 if obj.fields is None:
367 if obj.fields is None:
368 p.text(repr(obj))
368 p.text(repr(obj))
369 else:
369 else:
370 p.begin_group(7, 'dtype([')
370 p.begin_group(7, 'dtype([')
371 for i, field in enumerate(obj.descr):
371 for i, field in enumerate(obj.descr):
372 if i > 0:
372 if i > 0:
373 p.text(',')
373 p.text(',')
374 p.breakable()
374 p.breakable()
375 p.pretty(field)
375 p.pretty(field)
376 p.end_group(7, '])')
376 p.end_group(7, '])')
377 """
377 """
378
378
379 # The format type of data returned.
379 # The format type of data returned.
380 format_type = Unicode('text/plain')
380 format_type = Unicode('text/plain')
381
381
382 # This subclass ignores this attribute as it always need to return
382 # This subclass ignores this attribute as it always need to return
383 # something.
383 # something.
384 enabled = Bool(True, config=False)
384 enabled = Bool(True, config=False)
385
385
386 # Look for a _repr_pretty_ methods to use for pretty printing.
386 # Look for a _repr_pretty_ methods to use for pretty printing.
387 print_method = ObjectName('_repr_pretty_')
387 print_method = ObjectName('_repr_pretty_')
388
388
389 # Whether to pretty-print or not.
389 # Whether to pretty-print or not.
390 pprint = Bool(True, config=True)
390 pprint = Bool(True, config=True)
391
391
392 # Whether to be verbose or not.
392 # Whether to be verbose or not.
393 verbose = Bool(False, config=True)
393 verbose = Bool(False, config=True)
394
394
395 # The maximum width.
395 # The maximum width.
396 max_width = Integer(79, config=True)
396 max_width = Integer(79, config=True)
397
397
398 # The newline character.
398 # The newline character.
399 newline = Unicode('\n', config=True)
399 newline = Unicode('\n', config=True)
400
400
401 # format-string for pprinting floats
401 # format-string for pprinting floats
402 float_format = Unicode('%r')
402 float_format = Unicode('%r')
403 # setter for float precision, either int or direct format-string
403 # setter for float precision, either int or direct format-string
404 float_precision = CUnicode('', config=True)
404 float_precision = CUnicode('', config=True)
405
405
406 def _float_precision_changed(self, name, old, new):
406 def _float_precision_changed(self, name, old, new):
407 """float_precision changed, set float_format accordingly.
407 """float_precision changed, set float_format accordingly.
408
408
409 float_precision can be set by int or str.
409 float_precision can be set by int or str.
410 This will set float_format, after interpreting input.
410 This will set float_format, after interpreting input.
411 If numpy has been imported, numpy print precision will also be set.
411 If numpy has been imported, numpy print precision will also be set.
412
412
413 integer `n` sets format to '%.nf', otherwise, format set directly.
413 integer `n` sets format to '%.nf', otherwise, format set directly.
414
414
415 An empty string returns to defaults (repr for float, 8 for numpy).
415 An empty string returns to defaults (repr for float, 8 for numpy).
416
416
417 This parameter can be set via the '%precision' magic.
417 This parameter can be set via the '%precision' magic.
418 """
418 """
419
419
420 if '%' in new:
420 if '%' in new:
421 # got explicit format string
421 # got explicit format string
422 fmt = new
422 fmt = new
423 try:
423 try:
424 fmt%3.14159
424 fmt%3.14159
425 except Exception:
425 except Exception:
426 raise ValueError("Precision must be int or format string, not %r"%new)
426 raise ValueError("Precision must be int or format string, not %r"%new)
427 elif new:
427 elif new:
428 # otherwise, should be an int
428 # otherwise, should be an int
429 try:
429 try:
430 i = int(new)
430 i = int(new)
431 assert i >= 0
431 assert i >= 0
432 except ValueError:
432 except ValueError:
433 raise ValueError("Precision must be int or format string, not %r"%new)
433 raise ValueError("Precision must be int or format string, not %r"%new)
434 except AssertionError:
434 except AssertionError:
435 raise ValueError("int precision must be non-negative, not %r"%i)
435 raise ValueError("int precision must be non-negative, not %r"%i)
436
436
437 fmt = '%%.%if'%i
437 fmt = '%%.%if'%i
438 if 'numpy' in sys.modules:
438 if 'numpy' in sys.modules:
439 # set numpy precision if it has been imported
439 # set numpy precision if it has been imported
440 import numpy
440 import numpy
441 numpy.set_printoptions(precision=i)
441 numpy.set_printoptions(precision=i)
442 else:
442 else:
443 # default back to repr
443 # default back to repr
444 fmt = '%r'
444 fmt = '%r'
445 if 'numpy' in sys.modules:
445 if 'numpy' in sys.modules:
446 import numpy
446 import numpy
447 # numpy default is 8
447 # numpy default is 8
448 numpy.set_printoptions(precision=8)
448 numpy.set_printoptions(precision=8)
449 self.float_format = fmt
449 self.float_format = fmt
450
450
451 # Use the default pretty printers from IPython.lib.pretty.
451 # Use the default pretty printers from IPython.lib.pretty.
452 def _singleton_printers_default(self):
452 def _singleton_printers_default(self):
453 return pretty._singleton_pprinters.copy()
453 return pretty._singleton_pprinters.copy()
454
454
455 def _type_printers_default(self):
455 def _type_printers_default(self):
456 d = pretty._type_pprinters.copy()
456 d = pretty._type_pprinters.copy()
457 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
457 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
458 return d
458 return d
459
459
460 def _deferred_printers_default(self):
460 def _deferred_printers_default(self):
461 return pretty._deferred_type_pprinters.copy()
461 return pretty._deferred_type_pprinters.copy()
462
462
463 #### FormatterABC interface ####
463 #### FormatterABC interface ####
464
464
465 def __call__(self, obj):
465 def __call__(self, obj):
466 """Compute the pretty representation of the object."""
466 """Compute the pretty representation of the object."""
467 if not self.pprint:
467 if not self.pprint:
468 try:
468 return pretty._safe_repr(obj)
469 return repr(obj)
470 except TypeError:
471 return ''
472 else:
469 else:
473 # This uses use StringIO, as cStringIO doesn't handle unicode.
470 # This uses use StringIO, as cStringIO doesn't handle unicode.
474 stream = StringIO()
471 stream = StringIO()
475 # self.newline.encode() is a quick fix for issue gh-597. We need to
472 # self.newline.encode() is a quick fix for issue gh-597. We need to
476 # ensure that stream does not get a mix of unicode and bytestrings,
473 # ensure that stream does not get a mix of unicode and bytestrings,
477 # or it will cause trouble.
474 # or it will cause trouble.
478 printer = pretty.RepresentationPrinter(stream, self.verbose,
475 printer = pretty.RepresentationPrinter(stream, self.verbose,
479 self.max_width, unicode_to_str(self.newline),
476 self.max_width, unicode_to_str(self.newline),
480 singleton_pprinters=self.singleton_printers,
477 singleton_pprinters=self.singleton_printers,
481 type_pprinters=self.type_printers,
478 type_pprinters=self.type_printers,
482 deferred_pprinters=self.deferred_printers)
479 deferred_pprinters=self.deferred_printers)
483 printer.pretty(obj)
480 printer.pretty(obj)
484 printer.flush()
481 printer.flush()
485 return stream.getvalue()
482 return stream.getvalue()
486
483
487
484
488 class HTMLFormatter(BaseFormatter):
485 class HTMLFormatter(BaseFormatter):
489 """An HTML formatter.
486 """An HTML formatter.
490
487
491 To define the callables that compute the HTML representation of your
488 To define the callables that compute the HTML representation of your
492 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
489 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
493 or :meth:`for_type_by_name` methods to register functions that handle
490 or :meth:`for_type_by_name` methods to register functions that handle
494 this.
491 this.
495
492
496 The return value of this formatter should be a valid HTML snippet that
493 The return value of this formatter should be a valid HTML snippet that
497 could be injected into an existing DOM. It should *not* include the
494 could be injected into an existing DOM. It should *not* include the
498 ```<html>`` or ```<body>`` tags.
495 ```<html>`` or ```<body>`` tags.
499 """
496 """
500 format_type = Unicode('text/html')
497 format_type = Unicode('text/html')
501
498
502 print_method = ObjectName('_repr_html_')
499 print_method = ObjectName('_repr_html_')
503
500
504
501
505 class SVGFormatter(BaseFormatter):
502 class SVGFormatter(BaseFormatter):
506 """An SVG formatter.
503 """An SVG formatter.
507
504
508 To define the callables that compute the SVG representation of your
505 To define the callables that compute the SVG representation of your
509 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
506 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
510 or :meth:`for_type_by_name` methods to register functions that handle
507 or :meth:`for_type_by_name` methods to register functions that handle
511 this.
508 this.
512
509
513 The return value of this formatter should be valid SVG enclosed in
510 The return value of this formatter should be valid SVG enclosed in
514 ```<svg>``` tags, that could be injected into an existing DOM. It should
511 ```<svg>``` tags, that could be injected into an existing DOM. It should
515 *not* include the ```<html>`` or ```<body>`` tags.
512 *not* include the ```<html>`` or ```<body>`` tags.
516 """
513 """
517 format_type = Unicode('image/svg+xml')
514 format_type = Unicode('image/svg+xml')
518
515
519 print_method = ObjectName('_repr_svg_')
516 print_method = ObjectName('_repr_svg_')
520
517
521
518
522 class PNGFormatter(BaseFormatter):
519 class PNGFormatter(BaseFormatter):
523 """A PNG formatter.
520 """A PNG formatter.
524
521
525 To define the callables that compute the PNG representation of your
522 To define the callables that compute the PNG representation of your
526 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
523 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
527 or :meth:`for_type_by_name` methods to register functions that handle
524 or :meth:`for_type_by_name` methods to register functions that handle
528 this.
525 this.
529
526
530 The return value of this formatter should be raw PNG data, *not*
527 The return value of this formatter should be raw PNG data, *not*
531 base64 encoded.
528 base64 encoded.
532 """
529 """
533 format_type = Unicode('image/png')
530 format_type = Unicode('image/png')
534
531
535 print_method = ObjectName('_repr_png_')
532 print_method = ObjectName('_repr_png_')
536
533
537
534
538 class JPEGFormatter(BaseFormatter):
535 class JPEGFormatter(BaseFormatter):
539 """A JPEG formatter.
536 """A JPEG formatter.
540
537
541 To define the callables that compute the JPEG representation of your
538 To define the callables that compute the JPEG representation of your
542 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
539 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
543 or :meth:`for_type_by_name` methods to register functions that handle
540 or :meth:`for_type_by_name` methods to register functions that handle
544 this.
541 this.
545
542
546 The return value of this formatter should be raw JPEG data, *not*
543 The return value of this formatter should be raw JPEG data, *not*
547 base64 encoded.
544 base64 encoded.
548 """
545 """
549 format_type = Unicode('image/jpeg')
546 format_type = Unicode('image/jpeg')
550
547
551 print_method = ObjectName('_repr_jpeg_')
548 print_method = ObjectName('_repr_jpeg_')
552
549
553
550
554 class LatexFormatter(BaseFormatter):
551 class LatexFormatter(BaseFormatter):
555 """A LaTeX formatter.
552 """A LaTeX formatter.
556
553
557 To define the callables that compute the LaTeX representation of your
554 To define the callables that compute the LaTeX representation of your
558 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
555 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
559 or :meth:`for_type_by_name` methods to register functions that handle
556 or :meth:`for_type_by_name` methods to register functions that handle
560 this.
557 this.
561
558
562 The return value of this formatter should be a valid LaTeX equation,
559 The return value of this formatter should be a valid LaTeX equation,
563 enclosed in either ```$```, ```$$``` or another LaTeX equation
560 enclosed in either ```$```, ```$$``` or another LaTeX equation
564 environment.
561 environment.
565 """
562 """
566 format_type = Unicode('text/latex')
563 format_type = Unicode('text/latex')
567
564
568 print_method = ObjectName('_repr_latex_')
565 print_method = ObjectName('_repr_latex_')
569
566
570
567
571 class JSONFormatter(BaseFormatter):
568 class JSONFormatter(BaseFormatter):
572 """A JSON string formatter.
569 """A JSON string formatter.
573
570
574 To define the callables that compute the JSON string representation of
571 To define the callables that compute the JSON string representation of
575 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
572 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
576 or :meth:`for_type_by_name` methods to register functions that handle
573 or :meth:`for_type_by_name` methods to register functions that handle
577 this.
574 this.
578
575
579 The return value of this formatter should be a valid JSON string.
576 The return value of this formatter should be a valid JSON string.
580 """
577 """
581 format_type = Unicode('application/json')
578 format_type = Unicode('application/json')
582
579
583 print_method = ObjectName('_repr_json_')
580 print_method = ObjectName('_repr_json_')
584
581
585
582
586 class JavascriptFormatter(BaseFormatter):
583 class JavascriptFormatter(BaseFormatter):
587 """A Javascript formatter.
584 """A Javascript formatter.
588
585
589 To define the callables that compute the Javascript representation of
586 To define the callables that compute the Javascript representation of
590 your objects, define a :meth:`_repr_javascript_` method or use the
587 your objects, define a :meth:`_repr_javascript_` method or use the
591 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
588 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
592 that handle this.
589 that handle this.
593
590
594 The return value of this formatter should be valid Javascript code and
591 The return value of this formatter should be valid Javascript code and
595 should *not* be enclosed in ```<script>``` tags.
592 should *not* be enclosed in ```<script>``` tags.
596 """
593 """
597 format_type = Unicode('application/javascript')
594 format_type = Unicode('application/javascript')
598
595
599 print_method = ObjectName('_repr_javascript_')
596 print_method = ObjectName('_repr_javascript_')
600
597
601 FormatterABC.register(BaseFormatter)
598 FormatterABC.register(BaseFormatter)
602 FormatterABC.register(PlainTextFormatter)
599 FormatterABC.register(PlainTextFormatter)
603 FormatterABC.register(HTMLFormatter)
600 FormatterABC.register(HTMLFormatter)
604 FormatterABC.register(SVGFormatter)
601 FormatterABC.register(SVGFormatter)
605 FormatterABC.register(PNGFormatter)
602 FormatterABC.register(PNGFormatter)
606 FormatterABC.register(JPEGFormatter)
603 FormatterABC.register(JPEGFormatter)
607 FormatterABC.register(LatexFormatter)
604 FormatterABC.register(LatexFormatter)
608 FormatterABC.register(JSONFormatter)
605 FormatterABC.register(JSONFormatter)
609 FormatterABC.register(JavascriptFormatter)
606 FormatterABC.register(JavascriptFormatter)
610
607
611
608
612 def format_display_data(obj, include=None, exclude=None):
609 def format_display_data(obj, include=None, exclude=None):
613 """Return a format data dict for an object.
610 """Return a format data dict for an object.
614
611
615 By default all format types will be computed.
612 By default all format types will be computed.
616
613
617 The following MIME types are currently implemented:
614 The following MIME types are currently implemented:
618
615
619 * text/plain
616 * text/plain
620 * text/html
617 * text/html
621 * text/latex
618 * text/latex
622 * application/json
619 * application/json
623 * application/javascript
620 * application/javascript
624 * image/png
621 * image/png
625 * image/jpeg
622 * image/jpeg
626 * image/svg+xml
623 * image/svg+xml
627
624
628 Parameters
625 Parameters
629 ----------
626 ----------
630 obj : object
627 obj : object
631 The Python object whose format data will be computed.
628 The Python object whose format data will be computed.
632
629
633 Returns
630 Returns
634 -------
631 -------
635 format_dict : dict
632 format_dict : dict
636 A dictionary of key/value pairs, one or each format that was
633 A dictionary of key/value pairs, one or each format that was
637 generated for the object. The keys are the format types, which
634 generated for the object. The keys are the format types, which
638 will usually be MIME type strings and the values and JSON'able
635 will usually be MIME type strings and the values and JSON'able
639 data structure containing the raw data for the representation in
636 data structure containing the raw data for the representation in
640 that format.
637 that format.
641 include : list or tuple, optional
638 include : list or tuple, optional
642 A list of format type strings (MIME types) to include in the
639 A list of format type strings (MIME types) to include in the
643 format data dict. If this is set *only* the format types included
640 format data dict. If this is set *only* the format types included
644 in this list will be computed.
641 in this list will be computed.
645 exclude : list or tuple, optional
642 exclude : list or tuple, optional
646 A list of format type string (MIME types) to exclue in the format
643 A list of format type string (MIME types) to exclue in the format
647 data dict. If this is set all format types will be computed,
644 data dict. If this is set all format types will be computed,
648 except for those included in this argument.
645 except for those included in this argument.
649 """
646 """
650 from IPython.core.interactiveshell import InteractiveShell
647 from IPython.core.interactiveshell import InteractiveShell
651
648
652 InteractiveShell.instance().display_formatter.format(
649 InteractiveShell.instance().display_formatter.format(
653 obj,
650 obj,
654 include,
651 include,
655 exclude
652 exclude
656 )
653 )
657
654
@@ -1,797 +1,804 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Python advanced pretty printer. This pretty printer is intended to
3 Python advanced pretty printer. This pretty printer is intended to
4 replace the old `pprint` python module which does not allow developers
4 replace the old `pprint` python module which does not allow developers
5 to provide their own pretty print callbacks.
5 to provide their own pretty print callbacks.
6
6
7 This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
7 This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
8
8
9
9
10 Example Usage
10 Example Usage
11 -------------
11 -------------
12
12
13 To directly print the representation of an object use `pprint`::
13 To directly print the representation of an object use `pprint`::
14
14
15 from pretty import pprint
15 from pretty import pprint
16 pprint(complex_object)
16 pprint(complex_object)
17
17
18 To get a string of the output use `pretty`::
18 To get a string of the output use `pretty`::
19
19
20 from pretty import pretty
20 from pretty import pretty
21 string = pretty(complex_object)
21 string = pretty(complex_object)
22
22
23
23
24 Extending
24 Extending
25 ---------
25 ---------
26
26
27 The pretty library allows developers to add pretty printing rules for their
27 The pretty library allows developers to add pretty printing rules for their
28 own objects. This process is straightforward. All you have to do is to
28 own objects. This process is straightforward. All you have to do is to
29 add a `_repr_pretty_` method to your object and call the methods on the
29 add a `_repr_pretty_` method to your object and call the methods on the
30 pretty printer passed::
30 pretty printer passed::
31
31
32 class MyObject(object):
32 class MyObject(object):
33
33
34 def _repr_pretty_(self, p, cycle):
34 def _repr_pretty_(self, p, cycle):
35 ...
35 ...
36
36
37 Depending on the python version you want to support you have two
37 Depending on the python version you want to support you have two
38 possibilities. The following list shows the python 2.5 version and the
38 possibilities. The following list shows the python 2.5 version and the
39 compatibility one.
39 compatibility one.
40
40
41
41
42 Here the example implementation of a `_repr_pretty_` method for a list
42 Here the example implementation of a `_repr_pretty_` method for a list
43 subclass for python 2.5 and higher (python 2.5 requires the with statement
43 subclass for python 2.5 and higher (python 2.5 requires the with statement
44 __future__ import)::
44 __future__ import)::
45
45
46 class MyList(list):
46 class MyList(list):
47
47
48 def _repr_pretty_(self, p, cycle):
48 def _repr_pretty_(self, p, cycle):
49 if cycle:
49 if cycle:
50 p.text('MyList(...)')
50 p.text('MyList(...)')
51 else:
51 else:
52 with p.group(8, 'MyList([', '])'):
52 with p.group(8, 'MyList([', '])'):
53 for idx, item in enumerate(self):
53 for idx, item in enumerate(self):
54 if idx:
54 if idx:
55 p.text(',')
55 p.text(',')
56 p.breakable()
56 p.breakable()
57 p.pretty(item)
57 p.pretty(item)
58
58
59 The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
59 The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
60 react to that or the result is an infinite loop. `p.text()` just adds
60 react to that or the result is an infinite loop. `p.text()` just adds
61 non breaking text to the output, `p.breakable()` either adds a whitespace
61 non breaking text to the output, `p.breakable()` either adds a whitespace
62 or breaks here. If you pass it an argument it's used instead of the
62 or breaks here. If you pass it an argument it's used instead of the
63 default space. `p.pretty` prettyprints another object using the pretty print
63 default space. `p.pretty` prettyprints another object using the pretty print
64 method.
64 method.
65
65
66 The first parameter to the `group` function specifies the extra indentation
66 The first parameter to the `group` function specifies the extra indentation
67 of the next line. In this example the next item will either be not
67 of the next line. In this example the next item will either be not
68 breaked (if the items are short enough) or aligned with the right edge of
68 breaked (if the items are short enough) or aligned with the right edge of
69 the opening bracked of `MyList`.
69 the opening bracked of `MyList`.
70
70
71 If you want to support python 2.4 and lower you can use this code::
71 If you want to support python 2.4 and lower you can use this code::
72
72
73 class MyList(list):
73 class MyList(list):
74
74
75 def _repr_pretty_(self, p, cycle):
75 def _repr_pretty_(self, p, cycle):
76 if cycle:
76 if cycle:
77 p.text('MyList(...)')
77 p.text('MyList(...)')
78 else:
78 else:
79 p.begin_group(8, 'MyList([')
79 p.begin_group(8, 'MyList([')
80 for idx, item in enumerate(self):
80 for idx, item in enumerate(self):
81 if idx:
81 if idx:
82 p.text(',')
82 p.text(',')
83 p.breakable()
83 p.breakable()
84 p.pretty(item)
84 p.pretty(item)
85 p.end_group(8, '])')
85 p.end_group(8, '])')
86
86
87 If you just want to indent something you can use the group function
87 If you just want to indent something you can use the group function
88 without open / close parameters. Under python 2.5 you can also use this
88 without open / close parameters. Under python 2.5 you can also use this
89 code::
89 code::
90
90
91 with p.indent(2):
91 with p.indent(2):
92 ...
92 ...
93
93
94 Or under python2.4 you might want to modify ``p.indentation`` by hand but
94 Or under python2.4 you might want to modify ``p.indentation`` by hand but
95 this is rather ugly.
95 this is rather ugly.
96
96
97 Inheritance diagram:
97 Inheritance diagram:
98
98
99 .. inheritance-diagram:: IPython.lib.pretty
99 .. inheritance-diagram:: IPython.lib.pretty
100 :parts: 3
100 :parts: 3
101
101
102 :copyright: 2007 by Armin Ronacher.
102 :copyright: 2007 by Armin Ronacher.
103 Portions (c) 2009 by Robert Kern.
103 Portions (c) 2009 by Robert Kern.
104 :license: BSD License.
104 :license: BSD License.
105 """
105 """
106 from __future__ import print_function
106 from __future__ import print_function
107 from contextlib import contextmanager
107 from contextlib import contextmanager
108 import sys
108 import sys
109 import types
109 import types
110 import re
110 import re
111 import datetime
111 import datetime
112 from collections import deque
112 from collections import deque
113
113
114 from IPython.utils.py3compat import PY3
114 from IPython.utils.py3compat import PY3
115
115
116 if PY3:
116 if PY3:
117 from io import StringIO
117 from io import StringIO
118 else:
118 else:
119 from StringIO import StringIO
119 from StringIO import StringIO
120
120
121
121
122 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
122 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
123 'for_type', 'for_type_by_name']
123 'for_type', 'for_type_by_name']
124
124
125
125
126 _re_pattern_type = type(re.compile(''))
126 _re_pattern_type = type(re.compile(''))
127
127
128 def _safe_repr(obj):
129 """Don't trust repr to not be broken."""
130 try:
131 return repr(obj)
132 except Exception as e:
133 return "<repr(obj) failed: %s>" % e
134
128
135
129 def pretty(obj, verbose=False, max_width=79, newline='\n'):
136 def pretty(obj, verbose=False, max_width=79, newline='\n'):
130 """
137 """
131 Pretty print the object's representation.
138 Pretty print the object's representation.
132 """
139 """
133 stream = StringIO()
140 stream = StringIO()
134 printer = RepresentationPrinter(stream, verbose, max_width, newline)
141 printer = RepresentationPrinter(stream, verbose, max_width, newline)
135 printer.pretty(obj)
142 printer.pretty(obj)
136 printer.flush()
143 printer.flush()
137 return stream.getvalue()
144 return stream.getvalue()
138
145
139
146
140 def pprint(obj, verbose=False, max_width=79, newline='\n'):
147 def pprint(obj, verbose=False, max_width=79, newline='\n'):
141 """
148 """
142 Like `pretty` but print to stdout.
149 Like `pretty` but print to stdout.
143 """
150 """
144 printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline)
151 printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline)
145 printer.pretty(obj)
152 printer.pretty(obj)
146 printer.flush()
153 printer.flush()
147 sys.stdout.write(newline)
154 sys.stdout.write(newline)
148 sys.stdout.flush()
155 sys.stdout.flush()
149
156
150 class _PrettyPrinterBase(object):
157 class _PrettyPrinterBase(object):
151
158
152 @contextmanager
159 @contextmanager
153 def indent(self, indent):
160 def indent(self, indent):
154 """with statement support for indenting/dedenting."""
161 """with statement support for indenting/dedenting."""
155 self.indentation += indent
162 self.indentation += indent
156 try:
163 try:
157 yield
164 yield
158 finally:
165 finally:
159 self.indentation -= indent
166 self.indentation -= indent
160
167
161 @contextmanager
168 @contextmanager
162 def group(self, indent=0, open='', close=''):
169 def group(self, indent=0, open='', close=''):
163 """like begin_group / end_group but for the with statement."""
170 """like begin_group / end_group but for the with statement."""
164 self.begin_group(indent, open)
171 self.begin_group(indent, open)
165 try:
172 try:
166 yield
173 yield
167 finally:
174 finally:
168 self.end_group(indent, close)
175 self.end_group(indent, close)
169
176
170 class PrettyPrinter(_PrettyPrinterBase):
177 class PrettyPrinter(_PrettyPrinterBase):
171 """
178 """
172 Baseclass for the `RepresentationPrinter` prettyprinter that is used to
179 Baseclass for the `RepresentationPrinter` prettyprinter that is used to
173 generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
180 generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
174 this printer knows nothing about the default pprinters or the `_repr_pretty_`
181 this printer knows nothing about the default pprinters or the `_repr_pretty_`
175 callback method.
182 callback method.
176 """
183 """
177
184
178 def __init__(self, output, max_width=79, newline='\n'):
185 def __init__(self, output, max_width=79, newline='\n'):
179 self.output = output
186 self.output = output
180 self.max_width = max_width
187 self.max_width = max_width
181 self.newline = newline
188 self.newline = newline
182 self.output_width = 0
189 self.output_width = 0
183 self.buffer_width = 0
190 self.buffer_width = 0
184 self.buffer = deque()
191 self.buffer = deque()
185
192
186 root_group = Group(0)
193 root_group = Group(0)
187 self.group_stack = [root_group]
194 self.group_stack = [root_group]
188 self.group_queue = GroupQueue(root_group)
195 self.group_queue = GroupQueue(root_group)
189 self.indentation = 0
196 self.indentation = 0
190
197
191 def _break_outer_groups(self):
198 def _break_outer_groups(self):
192 while self.max_width < self.output_width + self.buffer_width:
199 while self.max_width < self.output_width + self.buffer_width:
193 group = self.group_queue.deq()
200 group = self.group_queue.deq()
194 if not group:
201 if not group:
195 return
202 return
196 while group.breakables:
203 while group.breakables:
197 x = self.buffer.popleft()
204 x = self.buffer.popleft()
198 self.output_width = x.output(self.output, self.output_width)
205 self.output_width = x.output(self.output, self.output_width)
199 self.buffer_width -= x.width
206 self.buffer_width -= x.width
200 while self.buffer and isinstance(self.buffer[0], Text):
207 while self.buffer and isinstance(self.buffer[0], Text):
201 x = self.buffer.popleft()
208 x = self.buffer.popleft()
202 self.output_width = x.output(self.output, self.output_width)
209 self.output_width = x.output(self.output, self.output_width)
203 self.buffer_width -= x.width
210 self.buffer_width -= x.width
204
211
205 def text(self, obj):
212 def text(self, obj):
206 """Add literal text to the output."""
213 """Add literal text to the output."""
207 width = len(obj)
214 width = len(obj)
208 if self.buffer:
215 if self.buffer:
209 text = self.buffer[-1]
216 text = self.buffer[-1]
210 if not isinstance(text, Text):
217 if not isinstance(text, Text):
211 text = Text()
218 text = Text()
212 self.buffer.append(text)
219 self.buffer.append(text)
213 text.add(obj, width)
220 text.add(obj, width)
214 self.buffer_width += width
221 self.buffer_width += width
215 self._break_outer_groups()
222 self._break_outer_groups()
216 else:
223 else:
217 self.output.write(obj)
224 self.output.write(obj)
218 self.output_width += width
225 self.output_width += width
219
226
220 def breakable(self, sep=' '):
227 def breakable(self, sep=' '):
221 """
228 """
222 Add a breakable separator to the output. This does not mean that it
229 Add a breakable separator to the output. This does not mean that it
223 will automatically break here. If no breaking on this position takes
230 will automatically break here. If no breaking on this position takes
224 place the `sep` is inserted which default to one space.
231 place the `sep` is inserted which default to one space.
225 """
232 """
226 width = len(sep)
233 width = len(sep)
227 group = self.group_stack[-1]
234 group = self.group_stack[-1]
228 if group.want_break:
235 if group.want_break:
229 self.flush()
236 self.flush()
230 self.output.write(self.newline)
237 self.output.write(self.newline)
231 self.output.write(' ' * self.indentation)
238 self.output.write(' ' * self.indentation)
232 self.output_width = self.indentation
239 self.output_width = self.indentation
233 self.buffer_width = 0
240 self.buffer_width = 0
234 else:
241 else:
235 self.buffer.append(Breakable(sep, width, self))
242 self.buffer.append(Breakable(sep, width, self))
236 self.buffer_width += width
243 self.buffer_width += width
237 self._break_outer_groups()
244 self._break_outer_groups()
238
245
239 def break_(self):
246 def break_(self):
240 """
247 """
241 Explicitly insert a newline into the output, maintaining correct indentation.
248 Explicitly insert a newline into the output, maintaining correct indentation.
242 """
249 """
243 self.flush()
250 self.flush()
244 self.output.write(self.newline)
251 self.output.write(self.newline)
245 self.output.write(' ' * self.indentation)
252 self.output.write(' ' * self.indentation)
246 self.output_width = self.indentation
253 self.output_width = self.indentation
247 self.buffer_width = 0
254 self.buffer_width = 0
248
255
249
256
250 def begin_group(self, indent=0, open=''):
257 def begin_group(self, indent=0, open=''):
251 """
258 """
252 Begin a group. If you want support for python < 2.5 which doesn't has
259 Begin a group. If you want support for python < 2.5 which doesn't has
253 the with statement this is the preferred way:
260 the with statement this is the preferred way:
254
261
255 p.begin_group(1, '{')
262 p.begin_group(1, '{')
256 ...
263 ...
257 p.end_group(1, '}')
264 p.end_group(1, '}')
258
265
259 The python 2.5 expression would be this:
266 The python 2.5 expression would be this:
260
267
261 with p.group(1, '{', '}'):
268 with p.group(1, '{', '}'):
262 ...
269 ...
263
270
264 The first parameter specifies the indentation for the next line (usually
271 The first parameter specifies the indentation for the next line (usually
265 the width of the opening text), the second the opening text. All
272 the width of the opening text), the second the opening text. All
266 parameters are optional.
273 parameters are optional.
267 """
274 """
268 if open:
275 if open:
269 self.text(open)
276 self.text(open)
270 group = Group(self.group_stack[-1].depth + 1)
277 group = Group(self.group_stack[-1].depth + 1)
271 self.group_stack.append(group)
278 self.group_stack.append(group)
272 self.group_queue.enq(group)
279 self.group_queue.enq(group)
273 self.indentation += indent
280 self.indentation += indent
274
281
275 def end_group(self, dedent=0, close=''):
282 def end_group(self, dedent=0, close=''):
276 """End a group. See `begin_group` for more details."""
283 """End a group. See `begin_group` for more details."""
277 self.indentation -= dedent
284 self.indentation -= dedent
278 group = self.group_stack.pop()
285 group = self.group_stack.pop()
279 if not group.breakables:
286 if not group.breakables:
280 self.group_queue.remove(group)
287 self.group_queue.remove(group)
281 if close:
288 if close:
282 self.text(close)
289 self.text(close)
283
290
284 def flush(self):
291 def flush(self):
285 """Flush data that is left in the buffer."""
292 """Flush data that is left in the buffer."""
286 for data in self.buffer:
293 for data in self.buffer:
287 self.output_width += data.output(self.output, self.output_width)
294 self.output_width += data.output(self.output, self.output_width)
288 self.buffer.clear()
295 self.buffer.clear()
289 self.buffer_width = 0
296 self.buffer_width = 0
290
297
291
298
292 def _get_mro(obj_class):
299 def _get_mro(obj_class):
293 """ Get a reasonable method resolution order of a class and its superclasses
300 """ Get a reasonable method resolution order of a class and its superclasses
294 for both old-style and new-style classes.
301 for both old-style and new-style classes.
295 """
302 """
296 if not hasattr(obj_class, '__mro__'):
303 if not hasattr(obj_class, '__mro__'):
297 # Old-style class. Mix in object to make a fake new-style class.
304 # Old-style class. Mix in object to make a fake new-style class.
298 try:
305 try:
299 obj_class = type(obj_class.__name__, (obj_class, object), {})
306 obj_class = type(obj_class.__name__, (obj_class, object), {})
300 except TypeError:
307 except TypeError:
301 # Old-style extension type that does not descend from object.
308 # Old-style extension type that does not descend from object.
302 # FIXME: try to construct a more thorough MRO.
309 # FIXME: try to construct a more thorough MRO.
303 mro = [obj_class]
310 mro = [obj_class]
304 else:
311 else:
305 mro = obj_class.__mro__[1:-1]
312 mro = obj_class.__mro__[1:-1]
306 else:
313 else:
307 mro = obj_class.__mro__
314 mro = obj_class.__mro__
308 return mro
315 return mro
309
316
310
317
311 class RepresentationPrinter(PrettyPrinter):
318 class RepresentationPrinter(PrettyPrinter):
312 """
319 """
313 Special pretty printer that has a `pretty` method that calls the pretty
320 Special pretty printer that has a `pretty` method that calls the pretty
314 printer for a python object.
321 printer for a python object.
315
322
316 This class stores processing data on `self` so you must *never* use
323 This class stores processing data on `self` so you must *never* use
317 this class in a threaded environment. Always lock it or reinstanciate
324 this class in a threaded environment. Always lock it or reinstanciate
318 it.
325 it.
319
326
320 Instances also have a verbose flag callbacks can access to control their
327 Instances also have a verbose flag callbacks can access to control their
321 output. For example the default instance repr prints all attributes and
328 output. For example the default instance repr prints all attributes and
322 methods that are not prefixed by an underscore if the printer is in
329 methods that are not prefixed by an underscore if the printer is in
323 verbose mode.
330 verbose mode.
324 """
331 """
325
332
326 def __init__(self, output, verbose=False, max_width=79, newline='\n',
333 def __init__(self, output, verbose=False, max_width=79, newline='\n',
327 singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None):
334 singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None):
328
335
329 PrettyPrinter.__init__(self, output, max_width, newline)
336 PrettyPrinter.__init__(self, output, max_width, newline)
330 self.verbose = verbose
337 self.verbose = verbose
331 self.stack = []
338 self.stack = []
332 if singleton_pprinters is None:
339 if singleton_pprinters is None:
333 singleton_pprinters = _singleton_pprinters.copy()
340 singleton_pprinters = _singleton_pprinters.copy()
334 self.singleton_pprinters = singleton_pprinters
341 self.singleton_pprinters = singleton_pprinters
335 if type_pprinters is None:
342 if type_pprinters is None:
336 type_pprinters = _type_pprinters.copy()
343 type_pprinters = _type_pprinters.copy()
337 self.type_pprinters = type_pprinters
344 self.type_pprinters = type_pprinters
338 if deferred_pprinters is None:
345 if deferred_pprinters is None:
339 deferred_pprinters = _deferred_type_pprinters.copy()
346 deferred_pprinters = _deferred_type_pprinters.copy()
340 self.deferred_pprinters = deferred_pprinters
347 self.deferred_pprinters = deferred_pprinters
341
348
342 def pretty(self, obj):
349 def pretty(self, obj):
343 """Pretty print the given object."""
350 """Pretty print the given object."""
344 obj_id = id(obj)
351 obj_id = id(obj)
345 cycle = obj_id in self.stack
352 cycle = obj_id in self.stack
346 self.stack.append(obj_id)
353 self.stack.append(obj_id)
347 self.begin_group()
354 self.begin_group()
348 try:
355 try:
349 obj_class = getattr(obj, '__class__', None) or type(obj)
356 obj_class = getattr(obj, '__class__', None) or type(obj)
350 # First try to find registered singleton printers for the type.
357 # First try to find registered singleton printers for the type.
351 try:
358 try:
352 printer = self.singleton_pprinters[obj_id]
359 printer = self.singleton_pprinters[obj_id]
353 except (TypeError, KeyError):
360 except (TypeError, KeyError):
354 pass
361 pass
355 else:
362 else:
356 return printer(obj, self, cycle)
363 return printer(obj, self, cycle)
357 # Next walk the mro and check for either:
364 # Next walk the mro and check for either:
358 # 1) a registered printer
365 # 1) a registered printer
359 # 2) a _repr_pretty_ method
366 # 2) a _repr_pretty_ method
360 for cls in _get_mro(obj_class):
367 for cls in _get_mro(obj_class):
361 if cls in self.type_pprinters:
368 if cls in self.type_pprinters:
362 # printer registered in self.type_pprinters
369 # printer registered in self.type_pprinters
363 return self.type_pprinters[cls](obj, self, cycle)
370 return self.type_pprinters[cls](obj, self, cycle)
364 else:
371 else:
365 # deferred printer
372 # deferred printer
366 printer = self._in_deferred_types(cls)
373 printer = self._in_deferred_types(cls)
367 if printer is not None:
374 if printer is not None:
368 return printer(obj, self, cycle)
375 return printer(obj, self, cycle)
369 else:
376 else:
370 # Finally look for special method names.
377 # Finally look for special method names.
371 # Some objects automatically create any requested
378 # Some objects automatically create any requested
372 # attribute. Try to ignore most of them by checking for
379 # attribute. Try to ignore most of them by checking for
373 # callability.
380 # callability.
374 if '_repr_pretty_' in cls.__dict__:
381 if '_repr_pretty_' in cls.__dict__:
375 meth = cls._repr_pretty_
382 meth = cls._repr_pretty_
376 if callable(meth):
383 if callable(meth):
377 return meth(obj, self, cycle)
384 return meth(obj, self, cycle)
378 return _default_pprint(obj, self, cycle)
385 return _default_pprint(obj, self, cycle)
379 finally:
386 finally:
380 self.end_group()
387 self.end_group()
381 self.stack.pop()
388 self.stack.pop()
382
389
383 def _in_deferred_types(self, cls):
390 def _in_deferred_types(self, cls):
384 """
391 """
385 Check if the given class is specified in the deferred type registry.
392 Check if the given class is specified in the deferred type registry.
386
393
387 Returns the printer from the registry if it exists, and None if the
394 Returns the printer from the registry if it exists, and None if the
388 class is not in the registry. Successful matches will be moved to the
395 class is not in the registry. Successful matches will be moved to the
389 regular type registry for future use.
396 regular type registry for future use.
390 """
397 """
391 mod = getattr(cls, '__module__', None)
398 mod = getattr(cls, '__module__', None)
392 name = getattr(cls, '__name__', None)
399 name = getattr(cls, '__name__', None)
393 key = (mod, name)
400 key = (mod, name)
394 printer = None
401 printer = None
395 if key in self.deferred_pprinters:
402 if key in self.deferred_pprinters:
396 # Move the printer over to the regular registry.
403 # Move the printer over to the regular registry.
397 printer = self.deferred_pprinters.pop(key)
404 printer = self.deferred_pprinters.pop(key)
398 self.type_pprinters[cls] = printer
405 self.type_pprinters[cls] = printer
399 return printer
406 return printer
400
407
401
408
402 class Printable(object):
409 class Printable(object):
403
410
404 def output(self, stream, output_width):
411 def output(self, stream, output_width):
405 return output_width
412 return output_width
406
413
407
414
408 class Text(Printable):
415 class Text(Printable):
409
416
410 def __init__(self):
417 def __init__(self):
411 self.objs = []
418 self.objs = []
412 self.width = 0
419 self.width = 0
413
420
414 def output(self, stream, output_width):
421 def output(self, stream, output_width):
415 for obj in self.objs:
422 for obj in self.objs:
416 stream.write(obj)
423 stream.write(obj)
417 return output_width + self.width
424 return output_width + self.width
418
425
419 def add(self, obj, width):
426 def add(self, obj, width):
420 self.objs.append(obj)
427 self.objs.append(obj)
421 self.width += width
428 self.width += width
422
429
423
430
424 class Breakable(Printable):
431 class Breakable(Printable):
425
432
426 def __init__(self, seq, width, pretty):
433 def __init__(self, seq, width, pretty):
427 self.obj = seq
434 self.obj = seq
428 self.width = width
435 self.width = width
429 self.pretty = pretty
436 self.pretty = pretty
430 self.indentation = pretty.indentation
437 self.indentation = pretty.indentation
431 self.group = pretty.group_stack[-1]
438 self.group = pretty.group_stack[-1]
432 self.group.breakables.append(self)
439 self.group.breakables.append(self)
433
440
434 def output(self, stream, output_width):
441 def output(self, stream, output_width):
435 self.group.breakables.popleft()
442 self.group.breakables.popleft()
436 if self.group.want_break:
443 if self.group.want_break:
437 stream.write(self.pretty.newline)
444 stream.write(self.pretty.newline)
438 stream.write(' ' * self.indentation)
445 stream.write(' ' * self.indentation)
439 return self.indentation
446 return self.indentation
440 if not self.group.breakables:
447 if not self.group.breakables:
441 self.pretty.group_queue.remove(self.group)
448 self.pretty.group_queue.remove(self.group)
442 stream.write(self.obj)
449 stream.write(self.obj)
443 return output_width + self.width
450 return output_width + self.width
444
451
445
452
446 class Group(Printable):
453 class Group(Printable):
447
454
448 def __init__(self, depth):
455 def __init__(self, depth):
449 self.depth = depth
456 self.depth = depth
450 self.breakables = deque()
457 self.breakables = deque()
451 self.want_break = False
458 self.want_break = False
452
459
453
460
454 class GroupQueue(object):
461 class GroupQueue(object):
455
462
456 def __init__(self, *groups):
463 def __init__(self, *groups):
457 self.queue = []
464 self.queue = []
458 for group in groups:
465 for group in groups:
459 self.enq(group)
466 self.enq(group)
460
467
461 def enq(self, group):
468 def enq(self, group):
462 depth = group.depth
469 depth = group.depth
463 while depth > len(self.queue) - 1:
470 while depth > len(self.queue) - 1:
464 self.queue.append([])
471 self.queue.append([])
465 self.queue[depth].append(group)
472 self.queue[depth].append(group)
466
473
467 def deq(self):
474 def deq(self):
468 for stack in self.queue:
475 for stack in self.queue:
469 for idx, group in enumerate(reversed(stack)):
476 for idx, group in enumerate(reversed(stack)):
470 if group.breakables:
477 if group.breakables:
471 del stack[idx]
478 del stack[idx]
472 group.want_break = True
479 group.want_break = True
473 return group
480 return group
474 for group in stack:
481 for group in stack:
475 group.want_break = True
482 group.want_break = True
476 del stack[:]
483 del stack[:]
477
484
478 def remove(self, group):
485 def remove(self, group):
479 try:
486 try:
480 self.queue[group.depth].remove(group)
487 self.queue[group.depth].remove(group)
481 except ValueError:
488 except ValueError:
482 pass
489 pass
483
490
484 try:
491 try:
485 _baseclass_reprs = (object.__repr__, types.InstanceType.__repr__)
492 _baseclass_reprs = (object.__repr__, types.InstanceType.__repr__)
486 except AttributeError: # Python 3
493 except AttributeError: # Python 3
487 _baseclass_reprs = (object.__repr__,)
494 _baseclass_reprs = (object.__repr__,)
488
495
489
496
490 def _default_pprint(obj, p, cycle):
497 def _default_pprint(obj, p, cycle):
491 """
498 """
492 The default print function. Used if an object does not provide one and
499 The default print function. Used if an object does not provide one and
493 it's none of the builtin objects.
500 it's none of the builtin objects.
494 """
501 """
495 klass = getattr(obj, '__class__', None) or type(obj)
502 klass = getattr(obj, '__class__', None) or type(obj)
496 if getattr(klass, '__repr__', None) not in _baseclass_reprs:
503 if getattr(klass, '__repr__', None) not in _baseclass_reprs:
497 # A user-provided repr. Find newlines and replace them with p.break_()
504 # A user-provided repr. Find newlines and replace them with p.break_()
498 output = repr(obj)
505 output = _safe_repr(obj)
499 for idx,output_line in enumerate(output.splitlines()):
506 for idx,output_line in enumerate(output.splitlines()):
500 if idx:
507 if idx:
501 p.break_()
508 p.break_()
502 p.text(output_line)
509 p.text(output_line)
503 return
510 return
504 p.begin_group(1, '<')
511 p.begin_group(1, '<')
505 p.pretty(klass)
512 p.pretty(klass)
506 p.text(' at 0x%x' % id(obj))
513 p.text(' at 0x%x' % id(obj))
507 if cycle:
514 if cycle:
508 p.text(' ...')
515 p.text(' ...')
509 elif p.verbose:
516 elif p.verbose:
510 first = True
517 first = True
511 for key in dir(obj):
518 for key in dir(obj):
512 if not key.startswith('_'):
519 if not key.startswith('_'):
513 try:
520 try:
514 value = getattr(obj, key)
521 value = getattr(obj, key)
515 except AttributeError:
522 except AttributeError:
516 continue
523 continue
517 if isinstance(value, types.MethodType):
524 if isinstance(value, types.MethodType):
518 continue
525 continue
519 if not first:
526 if not first:
520 p.text(',')
527 p.text(',')
521 p.breakable()
528 p.breakable()
522 p.text(key)
529 p.text(key)
523 p.text('=')
530 p.text('=')
524 step = len(key) + 1
531 step = len(key) + 1
525 p.indentation += step
532 p.indentation += step
526 p.pretty(value)
533 p.pretty(value)
527 p.indentation -= step
534 p.indentation -= step
528 first = False
535 first = False
529 p.end_group(1, '>')
536 p.end_group(1, '>')
530
537
531
538
532 def _seq_pprinter_factory(start, end, basetype):
539 def _seq_pprinter_factory(start, end, basetype):
533 """
540 """
534 Factory that returns a pprint function useful for sequences. Used by
541 Factory that returns a pprint function useful for sequences. Used by
535 the default pprint for tuples, dicts, and lists.
542 the default pprint for tuples, dicts, and lists.
536 """
543 """
537 def inner(obj, p, cycle):
544 def inner(obj, p, cycle):
538 typ = type(obj)
545 typ = type(obj)
539 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
546 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
540 # If the subclass provides its own repr, use it instead.
547 # If the subclass provides its own repr, use it instead.
541 return p.text(typ.__repr__(obj))
548 return p.text(typ.__repr__(obj))
542
549
543 if cycle:
550 if cycle:
544 return p.text(start + '...' + end)
551 return p.text(start + '...' + end)
545 step = len(start)
552 step = len(start)
546 p.begin_group(step, start)
553 p.begin_group(step, start)
547 for idx, x in enumerate(obj):
554 for idx, x in enumerate(obj):
548 if idx:
555 if idx:
549 p.text(',')
556 p.text(',')
550 p.breakable()
557 p.breakable()
551 p.pretty(x)
558 p.pretty(x)
552 if len(obj) == 1 and type(obj) is tuple:
559 if len(obj) == 1 and type(obj) is tuple:
553 # Special case for 1-item tuples.
560 # Special case for 1-item tuples.
554 p.text(',')
561 p.text(',')
555 p.end_group(step, end)
562 p.end_group(step, end)
556 return inner
563 return inner
557
564
558
565
559 def _set_pprinter_factory(start, end, basetype):
566 def _set_pprinter_factory(start, end, basetype):
560 """
567 """
561 Factory that returns a pprint function useful for sets and frozensets.
568 Factory that returns a pprint function useful for sets and frozensets.
562 """
569 """
563 def inner(obj, p, cycle):
570 def inner(obj, p, cycle):
564 typ = type(obj)
571 typ = type(obj)
565 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
572 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
566 # If the subclass provides its own repr, use it instead.
573 # If the subclass provides its own repr, use it instead.
567 return p.text(typ.__repr__(obj))
574 return p.text(typ.__repr__(obj))
568
575
569 if cycle:
576 if cycle:
570 return p.text(start + '...' + end)
577 return p.text(start + '...' + end)
571 if len(obj) == 0:
578 if len(obj) == 0:
572 # Special case.
579 # Special case.
573 p.text(basetype.__name__ + '()')
580 p.text(basetype.__name__ + '()')
574 else:
581 else:
575 step = len(start)
582 step = len(start)
576 p.begin_group(step, start)
583 p.begin_group(step, start)
577 # Like dictionary keys, we will try to sort the items.
584 # Like dictionary keys, we will try to sort the items.
578 items = list(obj)
585 items = list(obj)
579 try:
586 try:
580 items.sort()
587 items.sort()
581 except Exception:
588 except Exception:
582 # Sometimes the items don't sort.
589 # Sometimes the items don't sort.
583 pass
590 pass
584 for idx, x in enumerate(items):
591 for idx, x in enumerate(items):
585 if idx:
592 if idx:
586 p.text(',')
593 p.text(',')
587 p.breakable()
594 p.breakable()
588 p.pretty(x)
595 p.pretty(x)
589 p.end_group(step, end)
596 p.end_group(step, end)
590 return inner
597 return inner
591
598
592
599
593 def _dict_pprinter_factory(start, end, basetype=None):
600 def _dict_pprinter_factory(start, end, basetype=None):
594 """
601 """
595 Factory that returns a pprint function used by the default pprint of
602 Factory that returns a pprint function used by the default pprint of
596 dicts and dict proxies.
603 dicts and dict proxies.
597 """
604 """
598 def inner(obj, p, cycle):
605 def inner(obj, p, cycle):
599 typ = type(obj)
606 typ = type(obj)
600 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
607 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
601 # If the subclass provides its own repr, use it instead.
608 # If the subclass provides its own repr, use it instead.
602 return p.text(typ.__repr__(obj))
609 return p.text(typ.__repr__(obj))
603
610
604 if cycle:
611 if cycle:
605 return p.text('{...}')
612 return p.text('{...}')
606 p.begin_group(1, start)
613 p.begin_group(1, start)
607 keys = obj.keys()
614 keys = obj.keys()
608 try:
615 try:
609 keys.sort()
616 keys.sort()
610 except Exception as e:
617 except Exception as e:
611 # Sometimes the keys don't sort.
618 # Sometimes the keys don't sort.
612 pass
619 pass
613 for idx, key in enumerate(keys):
620 for idx, key in enumerate(keys):
614 if idx:
621 if idx:
615 p.text(',')
622 p.text(',')
616 p.breakable()
623 p.breakable()
617 p.pretty(key)
624 p.pretty(key)
618 p.text(': ')
625 p.text(': ')
619 p.pretty(obj[key])
626 p.pretty(obj[key])
620 p.end_group(1, end)
627 p.end_group(1, end)
621 return inner
628 return inner
622
629
623
630
624 def _super_pprint(obj, p, cycle):
631 def _super_pprint(obj, p, cycle):
625 """The pprint for the super type."""
632 """The pprint for the super type."""
626 p.begin_group(8, '<super: ')
633 p.begin_group(8, '<super: ')
627 p.pretty(obj.__self_class__)
634 p.pretty(obj.__self_class__)
628 p.text(',')
635 p.text(',')
629 p.breakable()
636 p.breakable()
630 p.pretty(obj.__self__)
637 p.pretty(obj.__self__)
631 p.end_group(8, '>')
638 p.end_group(8, '>')
632
639
633
640
634 def _re_pattern_pprint(obj, p, cycle):
641 def _re_pattern_pprint(obj, p, cycle):
635 """The pprint function for regular expression patterns."""
642 """The pprint function for regular expression patterns."""
636 p.text('re.compile(')
643 p.text('re.compile(')
637 pattern = repr(obj.pattern)
644 pattern = repr(obj.pattern)
638 if pattern[:1] in 'uU':
645 if pattern[:1] in 'uU':
639 pattern = pattern[1:]
646 pattern = pattern[1:]
640 prefix = 'ur'
647 prefix = 'ur'
641 else:
648 else:
642 prefix = 'r'
649 prefix = 'r'
643 pattern = prefix + pattern.replace('\\\\', '\\')
650 pattern = prefix + pattern.replace('\\\\', '\\')
644 p.text(pattern)
651 p.text(pattern)
645 if obj.flags:
652 if obj.flags:
646 p.text(',')
653 p.text(',')
647 p.breakable()
654 p.breakable()
648 done_one = False
655 done_one = False
649 for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
656 for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
650 'UNICODE', 'VERBOSE', 'DEBUG'):
657 'UNICODE', 'VERBOSE', 'DEBUG'):
651 if obj.flags & getattr(re, flag):
658 if obj.flags & getattr(re, flag):
652 if done_one:
659 if done_one:
653 p.text('|')
660 p.text('|')
654 p.text('re.' + flag)
661 p.text('re.' + flag)
655 done_one = True
662 done_one = True
656 p.text(')')
663 p.text(')')
657
664
658
665
659 def _type_pprint(obj, p, cycle):
666 def _type_pprint(obj, p, cycle):
660 """The pprint for classes and types."""
667 """The pprint for classes and types."""
661 mod = getattr(obj, '__module__', None)
668 mod = getattr(obj, '__module__', None)
662 if mod is None:
669 if mod is None:
663 # Heap allocated types might not have the module attribute,
670 # Heap allocated types might not have the module attribute,
664 # and others may set it to None.
671 # and others may set it to None.
665 return p.text(obj.__name__)
672 return p.text(obj.__name__)
666
673
667 if mod in ('__builtin__', 'builtins', 'exceptions'):
674 if mod in ('__builtin__', 'builtins', 'exceptions'):
668 name = obj.__name__
675 name = obj.__name__
669 else:
676 else:
670 name = mod + '.' + obj.__name__
677 name = mod + '.' + obj.__name__
671 p.text(name)
678 p.text(name)
672
679
673
680
674 def _repr_pprint(obj, p, cycle):
681 def _repr_pprint(obj, p, cycle):
675 """A pprint that just redirects to the normal repr function."""
682 """A pprint that just redirects to the normal repr function."""
676 p.text(repr(obj))
683 p.text(_safe_repr(obj))
677
684
678
685
679 def _function_pprint(obj, p, cycle):
686 def _function_pprint(obj, p, cycle):
680 """Base pprint for all functions and builtin functions."""
687 """Base pprint for all functions and builtin functions."""
681 if obj.__module__ in ('__builtin__', 'builtins', 'exceptions') or not obj.__module__:
688 if obj.__module__ in ('__builtin__', 'builtins', 'exceptions') or not obj.__module__:
682 name = obj.__name__
689 name = obj.__name__
683 else:
690 else:
684 name = obj.__module__ + '.' + obj.__name__
691 name = obj.__module__ + '.' + obj.__name__
685 p.text('<function %s>' % name)
692 p.text('<function %s>' % name)
686
693
687
694
688 def _exception_pprint(obj, p, cycle):
695 def _exception_pprint(obj, p, cycle):
689 """Base pprint for all exceptions."""
696 """Base pprint for all exceptions."""
690 if obj.__class__.__module__ in ('exceptions', 'builtins'):
697 if obj.__class__.__module__ in ('exceptions', 'builtins'):
691 name = obj.__class__.__name__
698 name = obj.__class__.__name__
692 else:
699 else:
693 name = '%s.%s' % (
700 name = '%s.%s' % (
694 obj.__class__.__module__,
701 obj.__class__.__module__,
695 obj.__class__.__name__
702 obj.__class__.__name__
696 )
703 )
697 step = len(name) + 1
704 step = len(name) + 1
698 p.begin_group(step, name + '(')
705 p.begin_group(step, name + '(')
699 for idx, arg in enumerate(getattr(obj, 'args', ())):
706 for idx, arg in enumerate(getattr(obj, 'args', ())):
700 if idx:
707 if idx:
701 p.text(',')
708 p.text(',')
702 p.breakable()
709 p.breakable()
703 p.pretty(arg)
710 p.pretty(arg)
704 p.end_group(step, ')')
711 p.end_group(step, ')')
705
712
706
713
707 #: the exception base
714 #: the exception base
708 try:
715 try:
709 _exception_base = BaseException
716 _exception_base = BaseException
710 except NameError:
717 except NameError:
711 _exception_base = Exception
718 _exception_base = Exception
712
719
713
720
714 #: printers for builtin types
721 #: printers for builtin types
715 _type_pprinters = {
722 _type_pprinters = {
716 int: _repr_pprint,
723 int: _repr_pprint,
717 float: _repr_pprint,
724 float: _repr_pprint,
718 str: _repr_pprint,
725 str: _repr_pprint,
719 tuple: _seq_pprinter_factory('(', ')', tuple),
726 tuple: _seq_pprinter_factory('(', ')', tuple),
720 list: _seq_pprinter_factory('[', ']', list),
727 list: _seq_pprinter_factory('[', ']', list),
721 dict: _dict_pprinter_factory('{', '}', dict),
728 dict: _dict_pprinter_factory('{', '}', dict),
722
729
723 set: _set_pprinter_factory('{', '}', set),
730 set: _set_pprinter_factory('{', '}', set),
724 frozenset: _set_pprinter_factory('frozenset({', '})', frozenset),
731 frozenset: _set_pprinter_factory('frozenset({', '})', frozenset),
725 super: _super_pprint,
732 super: _super_pprint,
726 _re_pattern_type: _re_pattern_pprint,
733 _re_pattern_type: _re_pattern_pprint,
727 type: _type_pprint,
734 type: _type_pprint,
728 types.FunctionType: _function_pprint,
735 types.FunctionType: _function_pprint,
729 types.BuiltinFunctionType: _function_pprint,
736 types.BuiltinFunctionType: _function_pprint,
730 types.MethodType: _repr_pprint,
737 types.MethodType: _repr_pprint,
731
738
732 datetime.datetime: _repr_pprint,
739 datetime.datetime: _repr_pprint,
733 datetime.timedelta: _repr_pprint,
740 datetime.timedelta: _repr_pprint,
734 _exception_base: _exception_pprint
741 _exception_base: _exception_pprint
735 }
742 }
736
743
737 try:
744 try:
738 _type_pprinters[types.DictProxyType] = _dict_pprinter_factory('<dictproxy {', '}>')
745 _type_pprinters[types.DictProxyType] = _dict_pprinter_factory('<dictproxy {', '}>')
739 _type_pprinters[types.ClassType] = _type_pprint
746 _type_pprinters[types.ClassType] = _type_pprint
740 _type_pprinters[types.SliceType] = _repr_pprint
747 _type_pprinters[types.SliceType] = _repr_pprint
741 except AttributeError: # Python 3
748 except AttributeError: # Python 3
742 _type_pprinters[slice] = _repr_pprint
749 _type_pprinters[slice] = _repr_pprint
743
750
744 try:
751 try:
745 _type_pprinters[xrange] = _repr_pprint
752 _type_pprinters[xrange] = _repr_pprint
746 _type_pprinters[long] = _repr_pprint
753 _type_pprinters[long] = _repr_pprint
747 _type_pprinters[unicode] = _repr_pprint
754 _type_pprinters[unicode] = _repr_pprint
748 except NameError:
755 except NameError:
749 _type_pprinters[range] = _repr_pprint
756 _type_pprinters[range] = _repr_pprint
750 _type_pprinters[bytes] = _repr_pprint
757 _type_pprinters[bytes] = _repr_pprint
751
758
752 #: printers for types specified by name
759 #: printers for types specified by name
753 _deferred_type_pprinters = {
760 _deferred_type_pprinters = {
754 }
761 }
755
762
756 def for_type(typ, func):
763 def for_type(typ, func):
757 """
764 """
758 Add a pretty printer for a given type.
765 Add a pretty printer for a given type.
759 """
766 """
760 oldfunc = _type_pprinters.get(typ, None)
767 oldfunc = _type_pprinters.get(typ, None)
761 if func is not None:
768 if func is not None:
762 # To support easy restoration of old pprinters, we need to ignore Nones.
769 # To support easy restoration of old pprinters, we need to ignore Nones.
763 _type_pprinters[typ] = func
770 _type_pprinters[typ] = func
764 return oldfunc
771 return oldfunc
765
772
766 def for_type_by_name(type_module, type_name, func):
773 def for_type_by_name(type_module, type_name, func):
767 """
774 """
768 Add a pretty printer for a type specified by the module and name of a type
775 Add a pretty printer for a type specified by the module and name of a type
769 rather than the type object itself.
776 rather than the type object itself.
770 """
777 """
771 key = (type_module, type_name)
778 key = (type_module, type_name)
772 oldfunc = _deferred_type_pprinters.get(key, None)
779 oldfunc = _deferred_type_pprinters.get(key, None)
773 if func is not None:
780 if func is not None:
774 # To support easy restoration of old pprinters, we need to ignore Nones.
781 # To support easy restoration of old pprinters, we need to ignore Nones.
775 _deferred_type_pprinters[key] = func
782 _deferred_type_pprinters[key] = func
776 return oldfunc
783 return oldfunc
777
784
778
785
779 #: printers for the default singletons
786 #: printers for the default singletons
780 _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
787 _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
781 NotImplemented]), _repr_pprint)
788 NotImplemented]), _repr_pprint)
782
789
783
790
784 if __name__ == '__main__':
791 if __name__ == '__main__':
785 from random import randrange
792 from random import randrange
786 class Foo(object):
793 class Foo(object):
787 def __init__(self):
794 def __init__(self):
788 self.foo = 1
795 self.foo = 1
789 self.bar = re.compile(r'\s+')
796 self.bar = re.compile(r'\s+')
790 self.blub = dict.fromkeys(range(30), randrange(1, 40))
797 self.blub = dict.fromkeys(range(30), randrange(1, 40))
791 self.hehe = 23424.234234
798 self.hehe = 23424.234234
792 self.list = ["blub", "blah", self]
799 self.list = ["blub", "blah", self]
793
800
794 def get_foo(self):
801 def get_foo(self):
795 print("foo")
802 print("foo")
796
803
797 pprint(Foo(), verbose=True)
804 pprint(Foo(), verbose=True)
General Comments 0
You need to be logged in to leave comments. Login now