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