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