##// END OF EJS Templates
Fix bug with non-ascii reprs inside pretty-printed lists....
Thomas Kluyver -
Show More
@@ -1,593 +1,593 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Display formatters.
2 """Display formatters.
3
3
4
4
5 Authors:
5 Authors:
6
6
7 * Robert Kern
7 * Robert Kern
8 * Brian Granger
8 * Brian Granger
9 """
9 """
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Copyright (c) 2010, IPython Development Team.
11 # Copyright (c) 2010, IPython Development Team.
12 #
12 #
13 # Distributed under the terms of the Modified BSD License.
13 # Distributed under the terms of the Modified BSD License.
14 #
14 #
15 # The full license is in the file COPYING.txt, distributed with this software.
15 # The full license is in the file COPYING.txt, distributed with this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 # Stdlib imports
22 # Stdlib imports
23 import abc
23 import abc
24 import sys
24 import sys
25 # We must use StringIO, as cStringIO doesn't handle unicode properly.
25 # We must use StringIO, as cStringIO doesn't handle unicode properly.
26 from StringIO import StringIO
26 from StringIO import StringIO
27
27
28 # Our own imports
28 # Our own imports
29 from IPython.config.configurable import Configurable
29 from IPython.config.configurable import Configurable
30 from IPython.lib import pretty
30 from IPython.lib import pretty
31 from IPython.utils.traitlets import Bool, Dict, Int, Unicode, CUnicode, ObjectName
31 from IPython.utils.traitlets import Bool, Dict, Int, Unicode, CUnicode, ObjectName
32
32
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 # The main DisplayFormatter class
35 # The main DisplayFormatter class
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38
38
39 class DisplayFormatter(Configurable):
39 class DisplayFormatter(Configurable):
40
40
41 # When set to true only the default plain text formatter will be used.
41 # When set to true only the default plain text formatter will be used.
42 plain_text_only = Bool(False, config=True)
42 plain_text_only = Bool(False, config=True)
43
43
44 # A dict of formatter whose keys are format types (MIME types) and whose
44 # A dict of formatter whose keys are format types (MIME types) and whose
45 # values are subclasses of BaseFormatter.
45 # values are subclasses of BaseFormatter.
46 formatters = Dict(config=True)
46 formatters = Dict(config=True)
47 def _formatters_default(self):
47 def _formatters_default(self):
48 """Activate the default formatters."""
48 """Activate the default formatters."""
49 formatter_classes = [
49 formatter_classes = [
50 PlainTextFormatter,
50 PlainTextFormatter,
51 HTMLFormatter,
51 HTMLFormatter,
52 SVGFormatter,
52 SVGFormatter,
53 PNGFormatter,
53 PNGFormatter,
54 LatexFormatter,
54 LatexFormatter,
55 JSONFormatter,
55 JSONFormatter,
56 JavascriptFormatter
56 JavascriptFormatter
57 ]
57 ]
58 d = {}
58 d = {}
59 for cls in formatter_classes:
59 for cls in formatter_classes:
60 f = cls(config=self.config)
60 f = cls(config=self.config)
61 d[f.format_type] = f
61 d[f.format_type] = f
62 return d
62 return d
63
63
64 def format(self, obj, include=None, exclude=None):
64 def format(self, obj, include=None, exclude=None):
65 """Return a format data dict for an object.
65 """Return a format data dict for an object.
66
66
67 By default all format types will be computed.
67 By default all format types will be computed.
68
68
69 The following MIME types are currently implemented:
69 The following MIME types are currently implemented:
70
70
71 * text/plain
71 * text/plain
72 * text/html
72 * text/html
73 * text/latex
73 * text/latex
74 * application/json
74 * application/json
75 * image/png
75 * image/png
76 * immage/svg+xml
76 * immage/svg+xml
77
77
78 Parameters
78 Parameters
79 ----------
79 ----------
80 obj : object
80 obj : object
81 The Python object whose format data will be computed.
81 The Python object whose format data will be computed.
82 include : list or tuple, optional
82 include : list or tuple, optional
83 A list of format type strings (MIME types) to include in the
83 A list of format type strings (MIME types) to include in the
84 format data dict. If this is set *only* the format types included
84 format data dict. If this is set *only* the format types included
85 in this list will be computed.
85 in this list will be computed.
86 exclude : list or tuple, optional
86 exclude : list or tuple, optional
87 A list of format type string (MIME types) to exclue in the format
87 A list of format type string (MIME types) to exclue in the format
88 data dict. If this is set all format types will be computed,
88 data dict. If this is set all format types will be computed,
89 except for those included in this argument.
89 except for those included in this argument.
90
90
91 Returns
91 Returns
92 -------
92 -------
93 format_dict : dict
93 format_dict : dict
94 A dictionary of key/value pairs, one or each format that was
94 A dictionary of key/value pairs, one or each format that was
95 generated for the object. The keys are the format types, which
95 generated for the object. The keys are the format types, which
96 will usually be MIME type strings and the values and JSON'able
96 will usually be MIME type strings and the values and JSON'able
97 data structure containing the raw data for the representation in
97 data structure containing the raw data for the representation in
98 that format.
98 that format.
99 """
99 """
100 format_dict = {}
100 format_dict = {}
101
101
102 # If plain text only is active
102 # If plain text only is active
103 if self.plain_text_only:
103 if self.plain_text_only:
104 formatter = self.formatters['text/plain']
104 formatter = self.formatters['text/plain']
105 try:
105 try:
106 data = formatter(obj)
106 data = formatter(obj)
107 except:
107 except:
108 # FIXME: log the exception
108 # FIXME: log the exception
109 raise
109 raise
110 if data is not None:
110 if data is not None:
111 format_dict['text/plain'] = data
111 format_dict['text/plain'] = data
112 return format_dict
112 return format_dict
113
113
114 for format_type, formatter in self.formatters.items():
114 for format_type, formatter in self.formatters.items():
115 if include is not None:
115 if include is not None:
116 if format_type not in include:
116 if format_type not in include:
117 continue
117 continue
118 if exclude is not None:
118 if exclude is not None:
119 if format_type in exclude:
119 if format_type in exclude:
120 continue
120 continue
121 try:
121 try:
122 data = formatter(obj)
122 data = formatter(obj)
123 except:
123 except:
124 # FIXME: log the exception
124 # FIXME: log the exception
125 raise
125 raise
126 if data is not None:
126 if data is not None:
127 format_dict[format_type] = data
127 format_dict[format_type] = data
128 return format_dict
128 return format_dict
129
129
130 @property
130 @property
131 def format_types(self):
131 def format_types(self):
132 """Return the format types (MIME types) of the active formatters."""
132 """Return the format types (MIME types) of the active formatters."""
133 return self.formatters.keys()
133 return self.formatters.keys()
134
134
135
135
136 #-----------------------------------------------------------------------------
136 #-----------------------------------------------------------------------------
137 # Formatters for specific format types (text, html, svg, etc.)
137 # Formatters for specific format types (text, html, svg, etc.)
138 #-----------------------------------------------------------------------------
138 #-----------------------------------------------------------------------------
139
139
140
140
141 class FormatterABC(object):
141 class FormatterABC(object):
142 """ Abstract base class for Formatters.
142 """ Abstract base class for Formatters.
143
143
144 A formatter is a callable class that is responsible for computing the
144 A formatter is a callable class that is responsible for computing the
145 raw format data for a particular format type (MIME type). For example,
145 raw format data for a particular format type (MIME type). For example,
146 an HTML formatter would have a format type of `text/html` and would return
146 an HTML formatter would have a format type of `text/html` and would return
147 the HTML representation of the object when called.
147 the HTML representation of the object when called.
148 """
148 """
149 __metaclass__ = abc.ABCMeta
149 __metaclass__ = abc.ABCMeta
150
150
151 # The format type of the data returned, usually a MIME type.
151 # The format type of the data returned, usually a MIME type.
152 format_type = 'text/plain'
152 format_type = 'text/plain'
153
153
154 # Is the formatter enabled...
154 # Is the formatter enabled...
155 enabled = True
155 enabled = True
156
156
157 @abc.abstractmethod
157 @abc.abstractmethod
158 def __call__(self, obj):
158 def __call__(self, obj):
159 """Return a JSON'able representation of the object.
159 """Return a JSON'able representation of the object.
160
160
161 If the object cannot be formatted by this formatter, then return None
161 If the object cannot be formatted by this formatter, then return None
162 """
162 """
163 try:
163 try:
164 return repr(obj)
164 return repr(obj)
165 except TypeError:
165 except TypeError:
166 return None
166 return None
167
167
168
168
169 class BaseFormatter(Configurable):
169 class BaseFormatter(Configurable):
170 """A base formatter class that is configurable.
170 """A base formatter class that is configurable.
171
171
172 This formatter should usually be used as the base class of all formatters.
172 This formatter should usually be used as the base class of all formatters.
173 It is a traited :class:`Configurable` class and includes an extensible
173 It is a traited :class:`Configurable` class and includes an extensible
174 API for users to determine how their objects are formatted. The following
174 API for users to determine how their objects are formatted. The following
175 logic is used to find a function to format an given object.
175 logic is used to find a function to format an given object.
176
176
177 1. The object is introspected to see if it has a method with the name
177 1. The object is introspected to see if it has a method with the name
178 :attr:`print_method`. If is does, that object is passed to that method
178 :attr:`print_method`. If is does, that object is passed to that method
179 for formatting.
179 for formatting.
180 2. If no print method is found, three internal dictionaries are consulted
180 2. If no print method is found, three internal dictionaries are consulted
181 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
181 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
182 and :attr:`deferred_printers`.
182 and :attr:`deferred_printers`.
183
183
184 Users should use these dictionaries to register functions that will be
184 Users should use these dictionaries to register functions that will be
185 used to compute the format data for their objects (if those objects don't
185 used to compute the format data for their objects (if those objects don't
186 have the special print methods). The easiest way of using these
186 have the special print methods). The easiest way of using these
187 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
187 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
188 methods.
188 methods.
189
189
190 If no function/callable is found to compute the format data, ``None`` is
190 If no function/callable is found to compute the format data, ``None`` is
191 returned and this format type is not used.
191 returned and this format type is not used.
192 """
192 """
193
193
194 format_type = Unicode('text/plain')
194 format_type = Unicode('text/plain')
195
195
196 enabled = Bool(True, config=True)
196 enabled = Bool(True, config=True)
197
197
198 print_method = ObjectName('__repr__')
198 print_method = ObjectName('__repr__')
199
199
200 # The singleton printers.
200 # The singleton printers.
201 # Maps the IDs of the builtin singleton objects to the format functions.
201 # Maps the IDs of the builtin singleton objects to the format functions.
202 singleton_printers = Dict(config=True)
202 singleton_printers = Dict(config=True)
203 def _singleton_printers_default(self):
203 def _singleton_printers_default(self):
204 return {}
204 return {}
205
205
206 # The type-specific printers.
206 # The type-specific printers.
207 # Map type objects to the format functions.
207 # Map type objects to the format functions.
208 type_printers = Dict(config=True)
208 type_printers = Dict(config=True)
209 def _type_printers_default(self):
209 def _type_printers_default(self):
210 return {}
210 return {}
211
211
212 # The deferred-import type-specific printers.
212 # The deferred-import type-specific printers.
213 # Map (modulename, classname) pairs to the format functions.
213 # Map (modulename, classname) pairs to the format functions.
214 deferred_printers = Dict(config=True)
214 deferred_printers = Dict(config=True)
215 def _deferred_printers_default(self):
215 def _deferred_printers_default(self):
216 return {}
216 return {}
217
217
218 def __call__(self, obj):
218 def __call__(self, obj):
219 """Compute the format for an object."""
219 """Compute the format for an object."""
220 if self.enabled:
220 if self.enabled:
221 obj_id = id(obj)
221 obj_id = id(obj)
222 try:
222 try:
223 obj_class = getattr(obj, '__class__', None) or type(obj)
223 obj_class = getattr(obj, '__class__', None) or type(obj)
224 # First try to find registered singleton printers for the type.
224 # First try to find registered singleton printers for the type.
225 try:
225 try:
226 printer = self.singleton_printers[obj_id]
226 printer = self.singleton_printers[obj_id]
227 except (TypeError, KeyError):
227 except (TypeError, KeyError):
228 pass
228 pass
229 else:
229 else:
230 return printer(obj)
230 return printer(obj)
231 # Next look for type_printers.
231 # Next look for type_printers.
232 for cls in pretty._get_mro(obj_class):
232 for cls in pretty._get_mro(obj_class):
233 if cls in self.type_printers:
233 if cls in self.type_printers:
234 return self.type_printers[cls](obj)
234 return self.type_printers[cls](obj)
235 else:
235 else:
236 printer = self._in_deferred_types(cls)
236 printer = self._in_deferred_types(cls)
237 if printer is not None:
237 if printer is not None:
238 return printer(obj)
238 return printer(obj)
239 # Finally look for special method names.
239 # Finally look for special method names.
240 if hasattr(obj_class, self.print_method):
240 if hasattr(obj_class, self.print_method):
241 printer = getattr(obj_class, self.print_method)
241 printer = getattr(obj_class, self.print_method)
242 return printer(obj)
242 return printer(obj)
243 return None
243 return None
244 except Exception:
244 except Exception:
245 pass
245 pass
246 else:
246 else:
247 return None
247 return None
248
248
249 def for_type(self, typ, func):
249 def for_type(self, typ, func):
250 """Add a format function for a given type.
250 """Add a format function for a given type.
251
251
252 Parameters
252 Parameters
253 -----------
253 -----------
254 typ : class
254 typ : class
255 The class of the object that will be formatted using `func`.
255 The class of the object that will be formatted using `func`.
256 func : callable
256 func : callable
257 The callable that will be called to compute the format data. The
257 The callable that will be called to compute the format data. The
258 call signature of this function is simple, it must take the
258 call signature of this function is simple, it must take the
259 object to be formatted and return the raw data for the given
259 object to be formatted and return the raw data for the given
260 format. Subclasses may use a different call signature for the
260 format. Subclasses may use a different call signature for the
261 `func` argument.
261 `func` argument.
262 """
262 """
263 oldfunc = self.type_printers.get(typ, None)
263 oldfunc = self.type_printers.get(typ, None)
264 if func is not None:
264 if func is not None:
265 # To support easy restoration of old printers, we need to ignore
265 # To support easy restoration of old printers, we need to ignore
266 # Nones.
266 # Nones.
267 self.type_printers[typ] = func
267 self.type_printers[typ] = func
268 return oldfunc
268 return oldfunc
269
269
270 def for_type_by_name(self, type_module, type_name, func):
270 def for_type_by_name(self, type_module, type_name, func):
271 """Add a format function for a type specified by the full dotted
271 """Add a format function for a type specified by the full dotted
272 module and name of the type, rather than the type of the object.
272 module and name of the type, rather than the type of the object.
273
273
274 Parameters
274 Parameters
275 ----------
275 ----------
276 type_module : str
276 type_module : str
277 The full dotted name of the module the type is defined in, like
277 The full dotted name of the module the type is defined in, like
278 ``numpy``.
278 ``numpy``.
279 type_name : str
279 type_name : str
280 The name of the type (the class name), like ``dtype``
280 The name of the type (the class name), like ``dtype``
281 func : callable
281 func : callable
282 The callable that will be called to compute the format data. The
282 The callable that will be called to compute the format data. The
283 call signature of this function is simple, it must take the
283 call signature of this function is simple, it must take the
284 object to be formatted and return the raw data for the given
284 object to be formatted and return the raw data for the given
285 format. Subclasses may use a different call signature for the
285 format. Subclasses may use a different call signature for the
286 `func` argument.
286 `func` argument.
287 """
287 """
288 key = (type_module, type_name)
288 key = (type_module, type_name)
289 oldfunc = self.deferred_printers.get(key, None)
289 oldfunc = self.deferred_printers.get(key, None)
290 if func is not None:
290 if func is not None:
291 # To support easy restoration of old printers, we need to ignore
291 # To support easy restoration of old printers, we need to ignore
292 # Nones.
292 # Nones.
293 self.deferred_printers[key] = func
293 self.deferred_printers[key] = func
294 return oldfunc
294 return oldfunc
295
295
296 def _in_deferred_types(self, cls):
296 def _in_deferred_types(self, cls):
297 """
297 """
298 Check if the given class is specified in the deferred type registry.
298 Check if the given class is specified in the deferred type registry.
299
299
300 Returns the printer from the registry if it exists, and None if the
300 Returns the printer from the registry if it exists, and None if the
301 class is not in the registry. Successful matches will be moved to the
301 class is not in the registry. Successful matches will be moved to the
302 regular type registry for future use.
302 regular type registry for future use.
303 """
303 """
304 mod = getattr(cls, '__module__', None)
304 mod = getattr(cls, '__module__', None)
305 name = getattr(cls, '__name__', None)
305 name = getattr(cls, '__name__', None)
306 key = (mod, name)
306 key = (mod, name)
307 printer = None
307 printer = None
308 if key in self.deferred_printers:
308 if key in self.deferred_printers:
309 # Move the printer over to the regular registry.
309 # Move the printer over to the regular registry.
310 printer = self.deferred_printers.pop(key)
310 printer = self.deferred_printers.pop(key)
311 self.type_printers[cls] = printer
311 self.type_printers[cls] = printer
312 return printer
312 return printer
313
313
314
314
315 class PlainTextFormatter(BaseFormatter):
315 class PlainTextFormatter(BaseFormatter):
316 """The default pretty-printer.
316 """The default pretty-printer.
317
317
318 This uses :mod:`IPython.external.pretty` to compute the format data of
318 This uses :mod:`IPython.external.pretty` to compute the format data of
319 the object. If the object cannot be pretty printed, :func:`repr` is used.
319 the object. If the object cannot be pretty printed, :func:`repr` is used.
320 See the documentation of :mod:`IPython.external.pretty` for details on
320 See the documentation of :mod:`IPython.external.pretty` for details on
321 how to write pretty printers. Here is a simple example::
321 how to write pretty printers. Here is a simple example::
322
322
323 def dtype_pprinter(obj, p, cycle):
323 def dtype_pprinter(obj, p, cycle):
324 if cycle:
324 if cycle:
325 return p.text('dtype(...)')
325 return p.text('dtype(...)')
326 if hasattr(obj, 'fields'):
326 if hasattr(obj, 'fields'):
327 if obj.fields is None:
327 if obj.fields is None:
328 p.text(repr(obj))
328 p.text(repr(obj))
329 else:
329 else:
330 p.begin_group(7, 'dtype([')
330 p.begin_group(7, 'dtype([')
331 for i, field in enumerate(obj.descr):
331 for i, field in enumerate(obj.descr):
332 if i > 0:
332 if i > 0:
333 p.text(',')
333 p.text(',')
334 p.breakable()
334 p.breakable()
335 p.pretty(field)
335 p.pretty(field)
336 p.end_group(7, '])')
336 p.end_group(7, '])')
337 """
337 """
338
338
339 # The format type of data returned.
339 # The format type of data returned.
340 format_type = Unicode('text/plain')
340 format_type = Unicode('text/plain')
341
341
342 # This subclass ignores this attribute as it always need to return
342 # This subclass ignores this attribute as it always need to return
343 # something.
343 # something.
344 enabled = Bool(True, config=False)
344 enabled = Bool(True, config=False)
345
345
346 # Look for a _repr_pretty_ methods to use for pretty printing.
346 # Look for a _repr_pretty_ methods to use for pretty printing.
347 print_method = ObjectName('_repr_pretty_')
347 print_method = ObjectName('_repr_pretty_')
348
348
349 # Whether to pretty-print or not.
349 # Whether to pretty-print or not.
350 pprint = Bool(True, config=True)
350 pprint = Bool(True, config=True)
351
351
352 # Whether to be verbose or not.
352 # Whether to be verbose or not.
353 verbose = Bool(False, config=True)
353 verbose = Bool(False, config=True)
354
354
355 # The maximum width.
355 # The maximum width.
356 max_width = Int(79, config=True)
356 max_width = Int(79, config=True)
357
357
358 # The newline character.
358 # The newline character.
359 newline = Unicode('\n', config=True)
359 newline = Unicode('\n', config=True)
360
360
361 # format-string for pprinting floats
361 # format-string for pprinting floats
362 float_format = Unicode('%r')
362 float_format = Unicode('%r')
363 # setter for float precision, either int or direct format-string
363 # setter for float precision, either int or direct format-string
364 float_precision = CUnicode('', config=True)
364 float_precision = CUnicode('', config=True)
365
365
366 def _float_precision_changed(self, name, old, new):
366 def _float_precision_changed(self, name, old, new):
367 """float_precision changed, set float_format accordingly.
367 """float_precision changed, set float_format accordingly.
368
368
369 float_precision can be set by int or str.
369 float_precision can be set by int or str.
370 This will set float_format, after interpreting input.
370 This will set float_format, after interpreting input.
371 If numpy has been imported, numpy print precision will also be set.
371 If numpy has been imported, numpy print precision will also be set.
372
372
373 integer `n` sets format to '%.nf', otherwise, format set directly.
373 integer `n` sets format to '%.nf', otherwise, format set directly.
374
374
375 An empty string returns to defaults (repr for float, 8 for numpy).
375 An empty string returns to defaults (repr for float, 8 for numpy).
376
376
377 This parameter can be set via the '%precision' magic.
377 This parameter can be set via the '%precision' magic.
378 """
378 """
379
379
380 if '%' in new:
380 if '%' in new:
381 # got explicit format string
381 # got explicit format string
382 fmt = new
382 fmt = new
383 try:
383 try:
384 fmt%3.14159
384 fmt%3.14159
385 except Exception:
385 except Exception:
386 raise ValueError("Precision must be int or format string, not %r"%new)
386 raise ValueError("Precision must be int or format string, not %r"%new)
387 elif new:
387 elif new:
388 # otherwise, should be an int
388 # otherwise, should be an int
389 try:
389 try:
390 i = int(new)
390 i = int(new)
391 assert i >= 0
391 assert i >= 0
392 except ValueError:
392 except ValueError:
393 raise ValueError("Precision must be int or format string, not %r"%new)
393 raise ValueError("Precision must be int or format string, not %r"%new)
394 except AssertionError:
394 except AssertionError:
395 raise ValueError("int precision must be non-negative, not %r"%i)
395 raise ValueError("int precision must be non-negative, not %r"%i)
396
396
397 fmt = '%%.%if'%i
397 fmt = '%%.%if'%i
398 if 'numpy' in sys.modules:
398 if 'numpy' in sys.modules:
399 # set numpy precision if it has been imported
399 # set numpy precision if it has been imported
400 import numpy
400 import numpy
401 numpy.set_printoptions(precision=i)
401 numpy.set_printoptions(precision=i)
402 else:
402 else:
403 # default back to repr
403 # default back to repr
404 fmt = '%r'
404 fmt = '%r'
405 if 'numpy' in sys.modules:
405 if 'numpy' in sys.modules:
406 import numpy
406 import numpy
407 # numpy default is 8
407 # numpy default is 8
408 numpy.set_printoptions(precision=8)
408 numpy.set_printoptions(precision=8)
409 self.float_format = fmt
409 self.float_format = fmt
410
410
411 # Use the default pretty printers from IPython.external.pretty.
411 # Use the default pretty printers from IPython.external.pretty.
412 def _singleton_printers_default(self):
412 def _singleton_printers_default(self):
413 return pretty._singleton_pprinters.copy()
413 return pretty._singleton_pprinters.copy()
414
414
415 def _type_printers_default(self):
415 def _type_printers_default(self):
416 d = pretty._type_pprinters.copy()
416 d = pretty._type_pprinters.copy()
417 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
417 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
418 return d
418 return d
419
419
420 def _deferred_printers_default(self):
420 def _deferred_printers_default(self):
421 return pretty._deferred_type_pprinters.copy()
421 return pretty._deferred_type_pprinters.copy()
422
422
423 #### FormatterABC interface ####
423 #### FormatterABC interface ####
424
424
425 def __call__(self, obj):
425 def __call__(self, obj):
426 """Compute the pretty representation of the object."""
426 """Compute the pretty representation of the object."""
427 if not self.pprint:
427 if not self.pprint:
428 try:
428 try:
429 return repr(obj)
429 return repr(obj)
430 except TypeError:
430 except TypeError:
431 return ''
431 return ''
432 else:
432 else:
433 # This uses use StringIO, as cStringIO doesn't handle unicode.
433 # This uses use StringIO, as cStringIO doesn't handle unicode.
434 stream = StringIO()
434 stream = StringIO()
435 printer = pretty.RepresentationPrinter(stream, self.verbose,
435 printer = pretty.RepresentationPrinter(stream, self.verbose,
436 self.max_width, self.newline,
436 self.max_width, self.newline.encode(),
437 singleton_pprinters=self.singleton_printers,
437 singleton_pprinters=self.singleton_printers,
438 type_pprinters=self.type_printers,
438 type_pprinters=self.type_printers,
439 deferred_pprinters=self.deferred_printers)
439 deferred_pprinters=self.deferred_printers)
440 printer.pretty(obj)
440 printer.pretty(obj)
441 printer.flush()
441 printer.flush()
442 return stream.getvalue()
442 return stream.getvalue()
443
443
444
444
445 class HTMLFormatter(BaseFormatter):
445 class HTMLFormatter(BaseFormatter):
446 """An HTML formatter.
446 """An HTML formatter.
447
447
448 To define the callables that compute the HTML representation of your
448 To define the callables that compute the HTML representation of your
449 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
449 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
450 or :meth:`for_type_by_name` methods to register functions that handle
450 or :meth:`for_type_by_name` methods to register functions that handle
451 this.
451 this.
452
452
453 The return value of this formatter should be a valid HTML snippet that
453 The return value of this formatter should be a valid HTML snippet that
454 could be injected into an existing DOM. It should *not* include the
454 could be injected into an existing DOM. It should *not* include the
455 ```<html>`` or ```<body>`` tags.
455 ```<html>`` or ```<body>`` tags.
456 """
456 """
457 format_type = Unicode('text/html')
457 format_type = Unicode('text/html')
458
458
459 print_method = ObjectName('_repr_html_')
459 print_method = ObjectName('_repr_html_')
460
460
461
461
462 class SVGFormatter(BaseFormatter):
462 class SVGFormatter(BaseFormatter):
463 """An SVG formatter.
463 """An SVG formatter.
464
464
465 To define the callables that compute the SVG representation of your
465 To define the callables that compute the SVG representation of your
466 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
466 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
467 or :meth:`for_type_by_name` methods to register functions that handle
467 or :meth:`for_type_by_name` methods to register functions that handle
468 this.
468 this.
469
469
470 The return value of this formatter should be valid SVG enclosed in
470 The return value of this formatter should be valid SVG enclosed in
471 ```<svg>``` tags, that could be injected into an existing DOM. It should
471 ```<svg>``` tags, that could be injected into an existing DOM. It should
472 *not* include the ```<html>`` or ```<body>`` tags.
472 *not* include the ```<html>`` or ```<body>`` tags.
473 """
473 """
474 format_type = Unicode('image/svg+xml')
474 format_type = Unicode('image/svg+xml')
475
475
476 print_method = ObjectName('_repr_svg_')
476 print_method = ObjectName('_repr_svg_')
477
477
478
478
479 class PNGFormatter(BaseFormatter):
479 class PNGFormatter(BaseFormatter):
480 """A PNG formatter.
480 """A PNG formatter.
481
481
482 To define the callables that compute the PNG representation of your
482 To define the callables that compute the PNG representation of your
483 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
483 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
484 or :meth:`for_type_by_name` methods to register functions that handle
484 or :meth:`for_type_by_name` methods to register functions that handle
485 this.
485 this.
486
486
487 The return value of this formatter should be raw PNG data, *not*
487 The return value of this formatter should be raw PNG data, *not*
488 base64 encoded.
488 base64 encoded.
489 """
489 """
490 format_type = Unicode('image/png')
490 format_type = Unicode('image/png')
491
491
492 print_method = ObjectName('_repr_png_')
492 print_method = ObjectName('_repr_png_')
493
493
494
494
495 class LatexFormatter(BaseFormatter):
495 class LatexFormatter(BaseFormatter):
496 """A LaTeX formatter.
496 """A LaTeX formatter.
497
497
498 To define the callables that compute the LaTeX representation of your
498 To define the callables that compute the LaTeX representation of your
499 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
499 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
500 or :meth:`for_type_by_name` methods to register functions that handle
500 or :meth:`for_type_by_name` methods to register functions that handle
501 this.
501 this.
502
502
503 The return value of this formatter should be a valid LaTeX equation,
503 The return value of this formatter should be a valid LaTeX equation,
504 enclosed in either ```$``` or ```$$```.
504 enclosed in either ```$``` or ```$$```.
505 """
505 """
506 format_type = Unicode('text/latex')
506 format_type = Unicode('text/latex')
507
507
508 print_method = ObjectName('_repr_latex_')
508 print_method = ObjectName('_repr_latex_')
509
509
510
510
511 class JSONFormatter(BaseFormatter):
511 class JSONFormatter(BaseFormatter):
512 """A JSON string formatter.
512 """A JSON string formatter.
513
513
514 To define the callables that compute the JSON string representation of
514 To define the callables that compute the JSON string representation of
515 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
515 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
516 or :meth:`for_type_by_name` methods to register functions that handle
516 or :meth:`for_type_by_name` methods to register functions that handle
517 this.
517 this.
518
518
519 The return value of this formatter should be a valid JSON string.
519 The return value of this formatter should be a valid JSON string.
520 """
520 """
521 format_type = Unicode('application/json')
521 format_type = Unicode('application/json')
522
522
523 print_method = ObjectName('_repr_json_')
523 print_method = ObjectName('_repr_json_')
524
524
525
525
526 class JavascriptFormatter(BaseFormatter):
526 class JavascriptFormatter(BaseFormatter):
527 """A Javascript formatter.
527 """A Javascript formatter.
528
528
529 To define the callables that compute the Javascript representation of
529 To define the callables that compute the Javascript representation of
530 your objects, define a :meth:`_repr_javascript_` method or use the
530 your objects, define a :meth:`_repr_javascript_` method or use the
531 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
531 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
532 that handle this.
532 that handle this.
533
533
534 The return value of this formatter should be valid Javascript code and
534 The return value of this formatter should be valid Javascript code and
535 should *not* be enclosed in ```<script>``` tags.
535 should *not* be enclosed in ```<script>``` tags.
536 """
536 """
537 format_type = Unicode('application/javascript')
537 format_type = Unicode('application/javascript')
538
538
539 print_method = ObjectName('_repr_javascript_')
539 print_method = ObjectName('_repr_javascript_')
540
540
541 FormatterABC.register(BaseFormatter)
541 FormatterABC.register(BaseFormatter)
542 FormatterABC.register(PlainTextFormatter)
542 FormatterABC.register(PlainTextFormatter)
543 FormatterABC.register(HTMLFormatter)
543 FormatterABC.register(HTMLFormatter)
544 FormatterABC.register(SVGFormatter)
544 FormatterABC.register(SVGFormatter)
545 FormatterABC.register(PNGFormatter)
545 FormatterABC.register(PNGFormatter)
546 FormatterABC.register(LatexFormatter)
546 FormatterABC.register(LatexFormatter)
547 FormatterABC.register(JSONFormatter)
547 FormatterABC.register(JSONFormatter)
548 FormatterABC.register(JavascriptFormatter)
548 FormatterABC.register(JavascriptFormatter)
549
549
550
550
551 def format_display_data(obj, include=None, exclude=None):
551 def format_display_data(obj, include=None, exclude=None):
552 """Return a format data dict for an object.
552 """Return a format data dict for an object.
553
553
554 By default all format types will be computed.
554 By default all format types will be computed.
555
555
556 The following MIME types are currently implemented:
556 The following MIME types are currently implemented:
557
557
558 * text/plain
558 * text/plain
559 * text/html
559 * text/html
560 * text/latex
560 * text/latex
561 * application/json
561 * application/json
562 * image/png
562 * image/png
563 * immage/svg+xml
563 * immage/svg+xml
564
564
565 Parameters
565 Parameters
566 ----------
566 ----------
567 obj : object
567 obj : object
568 The Python object whose format data will be computed.
568 The Python object whose format data will be computed.
569
569
570 Returns
570 Returns
571 -------
571 -------
572 format_dict : dict
572 format_dict : dict
573 A dictionary of key/value pairs, one or each format that was
573 A dictionary of key/value pairs, one or each format that was
574 generated for the object. The keys are the format types, which
574 generated for the object. The keys are the format types, which
575 will usually be MIME type strings and the values and JSON'able
575 will usually be MIME type strings and the values and JSON'able
576 data structure containing the raw data for the representation in
576 data structure containing the raw data for the representation in
577 that format.
577 that format.
578 include : list or tuple, optional
578 include : list or tuple, optional
579 A list of format type strings (MIME types) to include in the
579 A list of format type strings (MIME types) to include in the
580 format data dict. If this is set *only* the format types included
580 format data dict. If this is set *only* the format types included
581 in this list will be computed.
581 in this list will be computed.
582 exclude : list or tuple, optional
582 exclude : list or tuple, optional
583 A list of format type string (MIME types) to exclue in the format
583 A list of format type string (MIME types) to exclue in the format
584 data dict. If this is set all format types will be computed,
584 data dict. If this is set all format types will be computed,
585 except for those included in this argument.
585 except for those included in this argument.
586 """
586 """
587 from IPython.core.interactiveshell import InteractiveShell
587 from IPython.core.interactiveshell import InteractiveShell
588
588
589 InteractiveShell.instance().display_formatter.format(
589 InteractiveShell.instance().display_formatter.format(
590 obj,
590 obj,
591 include,
591 include,
592 exclude
592 exclude
593 )
593 )
General Comments 0
You need to be logged in to leave comments. Login now