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