##// END OF EJS Templates
image formatters allow both bytes and unicode (b64-encoded)
MinRK -
Show More
@@ -1,816 +1,816 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Display formatters.
2 """Display formatters.
3
3
4 Inheritance diagram:
4 Inheritance diagram:
5
5
6 .. inheritance-diagram:: IPython.core.formatters
6 .. inheritance-diagram:: IPython.core.formatters
7 :parts: 3
7 :parts: 3
8
8
9 Authors:
9 Authors:
10
10
11 * Robert Kern
11 * Robert Kern
12 * Brian Granger
12 * Brian Granger
13 """
13 """
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Copyright (C) 2010-2011, IPython Development Team.
15 # Copyright (C) 2010-2011, IPython Development Team.
16 #
16 #
17 # Distributed under the terms of the Modified BSD License.
17 # Distributed under the terms of the Modified BSD License.
18 #
18 #
19 # The full license is in the file COPYING.txt, distributed with this software.
19 # The full license is in the file COPYING.txt, distributed with this software.
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 # Stdlib imports
26 # Stdlib imports
27 import abc
27 import abc
28 import sys
28 import sys
29 import warnings
29 import warnings
30
30
31 from IPython.external.decorator import decorator
31 from IPython.external.decorator import decorator
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 import io
36 from IPython.utils import io
37 from IPython.utils.traitlets import (
37 from IPython.utils.traitlets import (
38 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
38 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
39 )
39 )
40 from IPython.utils.warn import warn
40 from IPython.utils.warn import warn
41 from IPython.utils.py3compat import (
41 from IPython.utils.py3compat import (
42 unicode_to_str, with_metaclass, PY3, string_types,
42 unicode_to_str, with_metaclass, PY3, string_types, unicode_type,
43 )
43 )
44
44
45 if PY3:
45 if PY3:
46 from io import StringIO
46 from io import StringIO
47 else:
47 else:
48 from StringIO import StringIO
48 from StringIO import StringIO
49
49
50
50
51 #-----------------------------------------------------------------------------
51 #-----------------------------------------------------------------------------
52 # The main DisplayFormatter class
52 # The main DisplayFormatter class
53 #-----------------------------------------------------------------------------
53 #-----------------------------------------------------------------------------
54
54
55 class DisplayFormatter(Configurable):
55 class DisplayFormatter(Configurable):
56
56
57 # When set to true only the default plain text formatter will be used.
57 # When set to true only the default plain text formatter will be used.
58 plain_text_only = Bool(False, config=True)
58 plain_text_only = Bool(False, config=True)
59 def _plain_text_only_changed(self, name, old, new):
59 def _plain_text_only_changed(self, name, old, new):
60 warnings.warn("""DisplayFormatter.plain_text_only is deprecated.
60 warnings.warn("""DisplayFormatter.plain_text_only is deprecated.
61
61
62 Use DisplayFormatter.active_types = ['text/plain']
62 Use DisplayFormatter.active_types = ['text/plain']
63 for the same effect.
63 for the same effect.
64 """, DeprecationWarning)
64 """, DeprecationWarning)
65 if new:
65 if new:
66 self.active_types = ['text/plain']
66 self.active_types = ['text/plain']
67 else:
67 else:
68 self.active_types = self.format_types
68 self.active_types = self.format_types
69
69
70 active_types = List(Unicode, config=True,
70 active_types = List(Unicode, config=True,
71 help="""List of currently active mime-types to display.
71 help="""List of currently active mime-types to display.
72 You can use this to set a white-list for formats to display.
72 You can use this to set a white-list for formats to display.
73
73
74 Most users will not need to change this value.
74 Most users will not need to change this value.
75 """)
75 """)
76 def _active_types_default(self):
76 def _active_types_default(self):
77 return self.format_types
77 return self.format_types
78
78
79 def _active_types_changed(self, name, old, new):
79 def _active_types_changed(self, name, old, new):
80 for key, formatter in self.formatters.items():
80 for key, formatter in self.formatters.items():
81 if key in new:
81 if key in new:
82 formatter.enabled = True
82 formatter.enabled = True
83 else:
83 else:
84 formatter.enabled = False
84 formatter.enabled = False
85
85
86 # A dict of formatter whose keys are format types (MIME types) and whose
86 # A dict of formatter whose keys are format types (MIME types) and whose
87 # values are subclasses of BaseFormatter.
87 # values are subclasses of BaseFormatter.
88 formatters = Dict()
88 formatters = Dict()
89 def _formatters_default(self):
89 def _formatters_default(self):
90 """Activate the default formatters."""
90 """Activate the default formatters."""
91 formatter_classes = [
91 formatter_classes = [
92 PlainTextFormatter,
92 PlainTextFormatter,
93 HTMLFormatter,
93 HTMLFormatter,
94 SVGFormatter,
94 SVGFormatter,
95 PNGFormatter,
95 PNGFormatter,
96 JPEGFormatter,
96 JPEGFormatter,
97 LatexFormatter,
97 LatexFormatter,
98 JSONFormatter,
98 JSONFormatter,
99 JavascriptFormatter
99 JavascriptFormatter
100 ]
100 ]
101 d = {}
101 d = {}
102 for cls in formatter_classes:
102 for cls in formatter_classes:
103 f = cls(parent=self)
103 f = cls(parent=self)
104 d[f.format_type] = f
104 d[f.format_type] = f
105 return d
105 return d
106
106
107 def format(self, obj, include=None, exclude=None):
107 def format(self, obj, include=None, exclude=None):
108 """Return a format data dict for an object.
108 """Return a format data dict for an object.
109
109
110 By default all format types will be computed.
110 By default all format types will be computed.
111
111
112 The following MIME types are currently implemented:
112 The following MIME types are currently implemented:
113
113
114 * text/plain
114 * text/plain
115 * text/html
115 * text/html
116 * text/latex
116 * text/latex
117 * application/json
117 * application/json
118 * application/javascript
118 * application/javascript
119 * image/png
119 * image/png
120 * image/jpeg
120 * image/jpeg
121 * image/svg+xml
121 * image/svg+xml
122
122
123 Parameters
123 Parameters
124 ----------
124 ----------
125 obj : object
125 obj : object
126 The Python object whose format data will be computed.
126 The Python object whose format data will be computed.
127 include : list or tuple, optional
127 include : list or tuple, optional
128 A list of format type strings (MIME types) to include in the
128 A list of format type strings (MIME types) to include in the
129 format data dict. If this is set *only* the format types included
129 format data dict. If this is set *only* the format types included
130 in this list will be computed.
130 in this list will be computed.
131 exclude : list or tuple, optional
131 exclude : list or tuple, optional
132 A list of format type string (MIME types) to exclude in the format
132 A list of format type string (MIME types) to exclude in the format
133 data dict. If this is set all format types will be computed,
133 data dict. If this is set all format types will be computed,
134 except for those included in this argument.
134 except for those included in this argument.
135
135
136 Returns
136 Returns
137 -------
137 -------
138 (format_dict, metadata_dict) : tuple of two dicts
138 (format_dict, metadata_dict) : tuple of two dicts
139
139
140 format_dict is a dictionary of key/value pairs, one of each format that was
140 format_dict is a dictionary of key/value pairs, one of each format that was
141 generated for the object. The keys are the format types, which
141 generated for the object. The keys are the format types, which
142 will usually be MIME type strings and the values and JSON'able
142 will usually be MIME type strings and the values and JSON'able
143 data structure containing the raw data for the representation in
143 data structure containing the raw data for the representation in
144 that format.
144 that format.
145
145
146 metadata_dict is a dictionary of metadata about each mime-type output.
146 metadata_dict is a dictionary of metadata about each mime-type output.
147 Its keys will be a strict subset of the keys in format_dict.
147 Its keys will be a strict subset of the keys in format_dict.
148 """
148 """
149 format_dict = {}
149 format_dict = {}
150 md_dict = {}
150 md_dict = {}
151
151
152 for format_type, formatter in self.formatters.items():
152 for format_type, formatter in self.formatters.items():
153 if include and format_type not in include:
153 if include and format_type not in include:
154 continue
154 continue
155 if exclude and format_type in exclude:
155 if exclude and format_type in exclude:
156 continue
156 continue
157
157
158 md = None
158 md = None
159 try:
159 try:
160 data = formatter(obj)
160 data = formatter(obj)
161 except:
161 except:
162 # FIXME: log the exception
162 # FIXME: log the exception
163 raise
163 raise
164
164
165 # formatters can return raw data or (data, metadata)
165 # formatters can return raw data or (data, metadata)
166 if isinstance(data, tuple) and len(data) == 2:
166 if isinstance(data, tuple) and len(data) == 2:
167 data, md = data
167 data, md = data
168
168
169 if data is not None:
169 if data is not None:
170 format_dict[format_type] = data
170 format_dict[format_type] = data
171 if md is not None:
171 if md is not None:
172 md_dict[format_type] = md
172 md_dict[format_type] = md
173
173
174 return format_dict, md_dict
174 return format_dict, md_dict
175
175
176 @property
176 @property
177 def format_types(self):
177 def format_types(self):
178 """Return the format types (MIME types) of the active formatters."""
178 """Return the format types (MIME types) of the active formatters."""
179 return list(self.formatters.keys())
179 return list(self.formatters.keys())
180
180
181
181
182 #-----------------------------------------------------------------------------
182 #-----------------------------------------------------------------------------
183 # Formatters for specific format types (text, html, svg, etc.)
183 # Formatters for specific format types (text, html, svg, etc.)
184 #-----------------------------------------------------------------------------
184 #-----------------------------------------------------------------------------
185
185
186 @decorator
186 @decorator
187 def warn_format_error(method, self, *args, **kwargs):
187 def warn_format_error(method, self, *args, **kwargs):
188 """decorator for warning on failed format call"""
188 """decorator for warning on failed format call"""
189 try:
189 try:
190 r = method(self, *args, **kwargs)
190 r = method(self, *args, **kwargs)
191 except Exception as e:
191 except Exception as e:
192 warn("Exception in %s formatter: %s" % (self.format_type, e))
192 warn("Exception in %s formatter: %s" % (self.format_type, e))
193 return None
193 return None
194 if r is None or isinstance(r, self._return_type) or \
194 if r is None or isinstance(r, self._return_type) or \
195 (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
195 (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
196 return r
196 return r
197 else:
197 else:
198 warn("%s formatter returned invalid type %s for object: %s" % (
198 warn("%s formatter returned invalid type %s (expected %s) for object: %s" % (
199 self.format_type, type(r), pretty._safe_repr(args[0])
199 self.format_type, type(r), self._return_type, pretty._safe_repr(args[0])
200 ))
200 ))
201
201
202
202
203
203
204 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
204 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
205 """ Abstract base class for Formatters.
205 """ Abstract base class for Formatters.
206
206
207 A formatter is a callable class that is responsible for computing the
207 A formatter is a callable class that is responsible for computing the
208 raw format data for a particular format type (MIME type). For example,
208 raw format data for a particular format type (MIME type). For example,
209 an HTML formatter would have a format type of `text/html` and would return
209 an HTML formatter would have a format type of `text/html` and would return
210 the HTML representation of the object when called.
210 the HTML representation of the object when called.
211 """
211 """
212
212
213 # The format type of the data returned, usually a MIME type.
213 # The format type of the data returned, usually a MIME type.
214 format_type = 'text/plain'
214 format_type = 'text/plain'
215
215
216 # Is the formatter enabled...
216 # Is the formatter enabled...
217 enabled = True
217 enabled = True
218
218
219 @abc.abstractmethod
219 @abc.abstractmethod
220 @warn_format_error
220 @warn_format_error
221 def __call__(self, obj):
221 def __call__(self, obj):
222 """Return a JSON'able representation of the object.
222 """Return a JSON'able representation of the object.
223
223
224 If the object cannot be formatted by this formatter,
224 If the object cannot be formatted by this formatter,
225 warn and return None.
225 warn and return None.
226 """
226 """
227 return repr(obj)
227 return repr(obj)
228
228
229
229
230 def _mod_name_key(typ):
230 def _mod_name_key(typ):
231 """Return a (__module__, __name__) tuple for a type.
231 """Return a (__module__, __name__) tuple for a type.
232
232
233 Used as key in Formatter.deferred_printers.
233 Used as key in Formatter.deferred_printers.
234 """
234 """
235 module = getattr(typ, '__module__', None)
235 module = getattr(typ, '__module__', None)
236 name = getattr(typ, '__name__', None)
236 name = getattr(typ, '__name__', None)
237 return (module, name)
237 return (module, name)
238
238
239
239
240 def _get_type(obj):
240 def _get_type(obj):
241 """Return the type of an instance (old and new-style)"""
241 """Return the type of an instance (old and new-style)"""
242 return getattr(obj, '__class__', None) or type(obj)
242 return getattr(obj, '__class__', None) or type(obj)
243
243
244 _raise_key_error = object()
244 _raise_key_error = object()
245
245
246
246
247 class BaseFormatter(Configurable):
247 class BaseFormatter(Configurable):
248 """A base formatter class that is configurable.
248 """A base formatter class that is configurable.
249
249
250 This formatter should usually be used as the base class of all formatters.
250 This formatter should usually be used as the base class of all formatters.
251 It is a traited :class:`Configurable` class and includes an extensible
251 It is a traited :class:`Configurable` class and includes an extensible
252 API for users to determine how their objects are formatted. The following
252 API for users to determine how their objects are formatted. The following
253 logic is used to find a function to format an given object.
253 logic is used to find a function to format an given object.
254
254
255 1. The object is introspected to see if it has a method with the name
255 1. The object is introspected to see if it has a method with the name
256 :attr:`print_method`. If is does, that object is passed to that method
256 :attr:`print_method`. If is does, that object is passed to that method
257 for formatting.
257 for formatting.
258 2. If no print method is found, three internal dictionaries are consulted
258 2. If no print method is found, three internal dictionaries are consulted
259 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
259 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
260 and :attr:`deferred_printers`.
260 and :attr:`deferred_printers`.
261
261
262 Users should use these dictionaries to register functions that will be
262 Users should use these dictionaries to register functions that will be
263 used to compute the format data for their objects (if those objects don't
263 used to compute the format data for their objects (if those objects don't
264 have the special print methods). The easiest way of using these
264 have the special print methods). The easiest way of using these
265 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
265 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
266 methods.
266 methods.
267
267
268 If no function/callable is found to compute the format data, ``None`` is
268 If no function/callable is found to compute the format data, ``None`` is
269 returned and this format type is not used.
269 returned and this format type is not used.
270 """
270 """
271
271
272 format_type = Unicode('text/plain')
272 format_type = Unicode('text/plain')
273 _return_type = string_types
273 _return_type = string_types
274
274
275 enabled = Bool(True, config=True)
275 enabled = Bool(True, config=True)
276
276
277 print_method = ObjectName('__repr__')
277 print_method = ObjectName('__repr__')
278
278
279 # The singleton printers.
279 # The singleton printers.
280 # Maps the IDs of the builtin singleton objects to the format functions.
280 # Maps the IDs of the builtin singleton objects to the format functions.
281 singleton_printers = Dict(config=True)
281 singleton_printers = Dict(config=True)
282
282
283 # The type-specific printers.
283 # The type-specific printers.
284 # Map type objects to the format functions.
284 # Map type objects to the format functions.
285 type_printers = Dict(config=True)
285 type_printers = Dict(config=True)
286
286
287 # The deferred-import type-specific printers.
287 # The deferred-import type-specific printers.
288 # Map (modulename, classname) pairs to the format functions.
288 # Map (modulename, classname) pairs to the format functions.
289 deferred_printers = Dict(config=True)
289 deferred_printers = Dict(config=True)
290
290
291 @warn_format_error
291 @warn_format_error
292 def __call__(self, obj):
292 def __call__(self, obj):
293 """Compute the format for an object."""
293 """Compute the format for an object."""
294 if self.enabled:
294 if self.enabled:
295 # lookup registered printer
295 # lookup registered printer
296 try:
296 try:
297 printer = self.lookup(obj)
297 printer = self.lookup(obj)
298 except KeyError:
298 except KeyError:
299 pass
299 pass
300 else:
300 else:
301 return printer(obj)
301 return printer(obj)
302 # Finally look for special method names
302 # Finally look for special method names
303 method = pretty._safe_getattr(obj, self.print_method, None)
303 method = pretty._safe_getattr(obj, self.print_method, None)
304 if method is not None:
304 if method is not None:
305 return method()
305 return method()
306 return None
306 return None
307 else:
307 else:
308 return None
308 return None
309
309
310 def __contains__(self, typ):
310 def __contains__(self, typ):
311 """map in to lookup_by_type"""
311 """map in to lookup_by_type"""
312 try:
312 try:
313 self.lookup_by_type(typ)
313 self.lookup_by_type(typ)
314 except KeyError:
314 except KeyError:
315 return False
315 return False
316 else:
316 else:
317 return True
317 return True
318
318
319 def lookup(self, obj):
319 def lookup(self, obj):
320 """Look up the formatter for a given instance.
320 """Look up the formatter for a given instance.
321
321
322 Parameters
322 Parameters
323 ----------
323 ----------
324 obj : object instance
324 obj : object instance
325
325
326 Returns
326 Returns
327 -------
327 -------
328 f : callable
328 f : callable
329 The registered formatting callable for the type.
329 The registered formatting callable for the type.
330
330
331 Raises
331 Raises
332 ------
332 ------
333 KeyError if the type has not been registered.
333 KeyError if the type has not been registered.
334 """
334 """
335 # look for singleton first
335 # look for singleton first
336 obj_id = id(obj)
336 obj_id = id(obj)
337 if obj_id in self.singleton_printers:
337 if obj_id in self.singleton_printers:
338 return self.singleton_printers[obj_id]
338 return self.singleton_printers[obj_id]
339 # then lookup by type
339 # then lookup by type
340 return self.lookup_by_type(_get_type(obj))
340 return self.lookup_by_type(_get_type(obj))
341
341
342 def lookup_by_type(self, typ):
342 def lookup_by_type(self, typ):
343 """Look up the registered formatter for a type.
343 """Look up the registered formatter for a type.
344
344
345 Parameters
345 Parameters
346 ----------
346 ----------
347 typ : type or '__module__.__name__' string for a type
347 typ : type or '__module__.__name__' string for a type
348
348
349 Returns
349 Returns
350 -------
350 -------
351 f : callable
351 f : callable
352 The registered formatting callable for the type.
352 The registered formatting callable for the type.
353
353
354 Raises
354 Raises
355 ------
355 ------
356 KeyError if the type has not been registered.
356 KeyError if the type has not been registered.
357 """
357 """
358 if isinstance(typ, string_types):
358 if isinstance(typ, string_types):
359 typ_key = tuple(typ.rsplit('.',1))
359 typ_key = tuple(typ.rsplit('.',1))
360 if typ_key not in self.deferred_printers:
360 if typ_key not in self.deferred_printers:
361 # We may have it cached in the type map. We will have to
361 # We may have it cached in the type map. We will have to
362 # iterate over all of the types to check.
362 # iterate over all of the types to check.
363 for cls in self.type_printers:
363 for cls in self.type_printers:
364 if _mod_name_key(cls) == typ_key:
364 if _mod_name_key(cls) == typ_key:
365 return self.type_printers[cls]
365 return self.type_printers[cls]
366 else:
366 else:
367 return self.deferred_printers[typ_key]
367 return self.deferred_printers[typ_key]
368 else:
368 else:
369 for cls in pretty._get_mro(typ):
369 for cls in pretty._get_mro(typ):
370 if cls in self.type_printers or self._in_deferred_types(cls):
370 if cls in self.type_printers or self._in_deferred_types(cls):
371 return self.type_printers[cls]
371 return self.type_printers[cls]
372
372
373 # If we have reached here, the lookup failed.
373 # If we have reached here, the lookup failed.
374 raise KeyError("No registered printer for {0!r}".format(typ))
374 raise KeyError("No registered printer for {0!r}".format(typ))
375
375
376 def for_type(self, typ, func=None):
376 def for_type(self, typ, func=None):
377 """Add a format function for a given type.
377 """Add a format function for a given type.
378
378
379 Parameters
379 Parameters
380 -----------
380 -----------
381 typ : type or '__module__.__name__' string for a type
381 typ : type or '__module__.__name__' string for a type
382 The class of the object that will be formatted using `func`.
382 The class of the object that will be formatted using `func`.
383 func : callable
383 func : callable
384 A callable for computing the format data.
384 A callable for computing the format data.
385 `func` will be called with the object to be formatted,
385 `func` will be called with the object to be formatted,
386 and will return the raw data in this formatter's format.
386 and will return the raw data in this formatter's format.
387 Subclasses may use a different call signature for the
387 Subclasses may use a different call signature for the
388 `func` argument.
388 `func` argument.
389
389
390 If `func` is None or not specified, there will be no change,
390 If `func` is None or not specified, there will be no change,
391 only returning the current value.
391 only returning the current value.
392
392
393 Returns
393 Returns
394 -------
394 -------
395 oldfunc : callable
395 oldfunc : callable
396 The currently registered callable.
396 The currently registered callable.
397 If you are registering a new formatter,
397 If you are registering a new formatter,
398 this will be the previous value (to enable restoring later).
398 this will be the previous value (to enable restoring later).
399 """
399 """
400 # if string given, interpret as 'pkg.module.class_name'
400 # if string given, interpret as 'pkg.module.class_name'
401 if isinstance(typ, string_types):
401 if isinstance(typ, string_types):
402 type_module, type_name = typ.rsplit('.', 1)
402 type_module, type_name = typ.rsplit('.', 1)
403 return self.for_type_by_name(type_module, type_name, func)
403 return self.for_type_by_name(type_module, type_name, func)
404
404
405 try:
405 try:
406 oldfunc = self.lookup_by_type(typ)
406 oldfunc = self.lookup_by_type(typ)
407 except KeyError:
407 except KeyError:
408 oldfunc = None
408 oldfunc = None
409
409
410 if func is not None:
410 if func is not None:
411 self.type_printers[typ] = func
411 self.type_printers[typ] = func
412
412
413 return oldfunc
413 return oldfunc
414
414
415 def for_type_by_name(self, type_module, type_name, func=None):
415 def for_type_by_name(self, type_module, type_name, func=None):
416 """Add a format function for a type specified by the full dotted
416 """Add a format function for a type specified by the full dotted
417 module and name of the type, rather than the type of the object.
417 module and name of the type, rather than the type of the object.
418
418
419 Parameters
419 Parameters
420 ----------
420 ----------
421 type_module : str
421 type_module : str
422 The full dotted name of the module the type is defined in, like
422 The full dotted name of the module the type is defined in, like
423 ``numpy``.
423 ``numpy``.
424 type_name : str
424 type_name : str
425 The name of the type (the class name), like ``dtype``
425 The name of the type (the class name), like ``dtype``
426 func : callable
426 func : callable
427 A callable for computing the format data.
427 A callable for computing the format data.
428 `func` will be called with the object to be formatted,
428 `func` will be called with the object to be formatted,
429 and will return the raw data in this formatter's format.
429 and will return the raw data in this formatter's format.
430 Subclasses may use a different call signature for the
430 Subclasses may use a different call signature for the
431 `func` argument.
431 `func` argument.
432
432
433 If `func` is None or unspecified, there will be no change,
433 If `func` is None or unspecified, there will be no change,
434 only returning the current value.
434 only returning the current value.
435
435
436 Returns
436 Returns
437 -------
437 -------
438 oldfunc : callable
438 oldfunc : callable
439 The currently registered callable.
439 The currently registered callable.
440 If you are registering a new formatter,
440 If you are registering a new formatter,
441 this will be the previous value (to enable restoring later).
441 this will be the previous value (to enable restoring later).
442 """
442 """
443 key = (type_module, type_name)
443 key = (type_module, type_name)
444
444
445 try:
445 try:
446 oldfunc = self.lookup_by_type("%s.%s" % key)
446 oldfunc = self.lookup_by_type("%s.%s" % key)
447 except KeyError:
447 except KeyError:
448 oldfunc = None
448 oldfunc = None
449
449
450 if func is not None:
450 if func is not None:
451 self.deferred_printers[key] = func
451 self.deferred_printers[key] = func
452 return oldfunc
452 return oldfunc
453
453
454 def pop(self, typ, default=_raise_key_error):
454 def pop(self, typ, default=_raise_key_error):
455 """Pop a formatter for the given type.
455 """Pop a formatter for the given type.
456
456
457 Parameters
457 Parameters
458 ----------
458 ----------
459 typ : type or '__module__.__name__' string for a type
459 typ : type or '__module__.__name__' string for a type
460 default : object
460 default : object
461 value to be returned if no formatter is registered for typ.
461 value to be returned if no formatter is registered for typ.
462
462
463 Returns
463 Returns
464 -------
464 -------
465 obj : object
465 obj : object
466 The last registered object for the type.
466 The last registered object for the type.
467
467
468 Raises
468 Raises
469 ------
469 ------
470 KeyError if the type is not registered and default is not specified.
470 KeyError if the type is not registered and default is not specified.
471 """
471 """
472
472
473 if isinstance(typ, string_types):
473 if isinstance(typ, string_types):
474 typ_key = tuple(typ.rsplit('.',1))
474 typ_key = tuple(typ.rsplit('.',1))
475 if typ_key not in self.deferred_printers:
475 if typ_key not in self.deferred_printers:
476 # We may have it cached in the type map. We will have to
476 # We may have it cached in the type map. We will have to
477 # iterate over all of the types to check.
477 # iterate over all of the types to check.
478 for cls in self.type_printers:
478 for cls in self.type_printers:
479 if _mod_name_key(cls) == typ_key:
479 if _mod_name_key(cls) == typ_key:
480 old = self.type_printers.pop(cls)
480 old = self.type_printers.pop(cls)
481 break
481 break
482 else:
482 else:
483 old = default
483 old = default
484 else:
484 else:
485 old = self.deferred_printers.pop(typ_key)
485 old = self.deferred_printers.pop(typ_key)
486 else:
486 else:
487 if typ in self.type_printers:
487 if typ in self.type_printers:
488 old = self.type_printers.pop(typ)
488 old = self.type_printers.pop(typ)
489 else:
489 else:
490 old = self.deferred_printers.pop(_mod_name_key(typ), default)
490 old = self.deferred_printers.pop(_mod_name_key(typ), default)
491 if old is _raise_key_error:
491 if old is _raise_key_error:
492 raise KeyError("No registered value for {0!r}".format(typ))
492 raise KeyError("No registered value for {0!r}".format(typ))
493 return old
493 return old
494
494
495 def _in_deferred_types(self, cls):
495 def _in_deferred_types(self, cls):
496 """
496 """
497 Check if the given class is specified in the deferred type registry.
497 Check if the given class is specified in the deferred type registry.
498
498
499 Successful matches will be moved to the regular type registry for future use.
499 Successful matches will be moved to the regular type registry for future use.
500 """
500 """
501 mod = getattr(cls, '__module__', None)
501 mod = getattr(cls, '__module__', None)
502 name = getattr(cls, '__name__', None)
502 name = getattr(cls, '__name__', None)
503 key = (mod, name)
503 key = (mod, name)
504 if key in self.deferred_printers:
504 if key in self.deferred_printers:
505 # Move the printer over to the regular registry.
505 # Move the printer over to the regular registry.
506 printer = self.deferred_printers.pop(key)
506 printer = self.deferred_printers.pop(key)
507 self.type_printers[cls] = printer
507 self.type_printers[cls] = printer
508 return True
508 return True
509 return False
509 return False
510
510
511
511
512 class PlainTextFormatter(BaseFormatter):
512 class PlainTextFormatter(BaseFormatter):
513 """The default pretty-printer.
513 """The default pretty-printer.
514
514
515 This uses :mod:`IPython.lib.pretty` to compute the format data of
515 This uses :mod:`IPython.lib.pretty` to compute the format data of
516 the object. If the object cannot be pretty printed, :func:`repr` is used.
516 the object. If the object cannot be pretty printed, :func:`repr` is used.
517 See the documentation of :mod:`IPython.lib.pretty` for details on
517 See the documentation of :mod:`IPython.lib.pretty` for details on
518 how to write pretty printers. Here is a simple example::
518 how to write pretty printers. Here is a simple example::
519
519
520 def dtype_pprinter(obj, p, cycle):
520 def dtype_pprinter(obj, p, cycle):
521 if cycle:
521 if cycle:
522 return p.text('dtype(...)')
522 return p.text('dtype(...)')
523 if hasattr(obj, 'fields'):
523 if hasattr(obj, 'fields'):
524 if obj.fields is None:
524 if obj.fields is None:
525 p.text(repr(obj))
525 p.text(repr(obj))
526 else:
526 else:
527 p.begin_group(7, 'dtype([')
527 p.begin_group(7, 'dtype([')
528 for i, field in enumerate(obj.descr):
528 for i, field in enumerate(obj.descr):
529 if i > 0:
529 if i > 0:
530 p.text(',')
530 p.text(',')
531 p.breakable()
531 p.breakable()
532 p.pretty(field)
532 p.pretty(field)
533 p.end_group(7, '])')
533 p.end_group(7, '])')
534 """
534 """
535
535
536 # The format type of data returned.
536 # The format type of data returned.
537 format_type = Unicode('text/plain')
537 format_type = Unicode('text/plain')
538
538
539 # This subclass ignores this attribute as it always need to return
539 # This subclass ignores this attribute as it always need to return
540 # something.
540 # something.
541 enabled = Bool(True, config=False)
541 enabled = Bool(True, config=False)
542
542
543 # Look for a _repr_pretty_ methods to use for pretty printing.
543 # Look for a _repr_pretty_ methods to use for pretty printing.
544 print_method = ObjectName('_repr_pretty_')
544 print_method = ObjectName('_repr_pretty_')
545
545
546 # Whether to pretty-print or not.
546 # Whether to pretty-print or not.
547 pprint = Bool(True, config=True)
547 pprint = Bool(True, config=True)
548
548
549 # Whether to be verbose or not.
549 # Whether to be verbose or not.
550 verbose = Bool(False, config=True)
550 verbose = Bool(False, config=True)
551
551
552 # The maximum width.
552 # The maximum width.
553 max_width = Integer(79, config=True)
553 max_width = Integer(79, config=True)
554
554
555 # The newline character.
555 # The newline character.
556 newline = Unicode('\n', config=True)
556 newline = Unicode('\n', config=True)
557
557
558 # format-string for pprinting floats
558 # format-string for pprinting floats
559 float_format = Unicode('%r')
559 float_format = Unicode('%r')
560 # setter for float precision, either int or direct format-string
560 # setter for float precision, either int or direct format-string
561 float_precision = CUnicode('', config=True)
561 float_precision = CUnicode('', config=True)
562
562
563 def _float_precision_changed(self, name, old, new):
563 def _float_precision_changed(self, name, old, new):
564 """float_precision changed, set float_format accordingly.
564 """float_precision changed, set float_format accordingly.
565
565
566 float_precision can be set by int or str.
566 float_precision can be set by int or str.
567 This will set float_format, after interpreting input.
567 This will set float_format, after interpreting input.
568 If numpy has been imported, numpy print precision will also be set.
568 If numpy has been imported, numpy print precision will also be set.
569
569
570 integer `n` sets format to '%.nf', otherwise, format set directly.
570 integer `n` sets format to '%.nf', otherwise, format set directly.
571
571
572 An empty string returns to defaults (repr for float, 8 for numpy).
572 An empty string returns to defaults (repr for float, 8 for numpy).
573
573
574 This parameter can be set via the '%precision' magic.
574 This parameter can be set via the '%precision' magic.
575 """
575 """
576
576
577 if '%' in new:
577 if '%' in new:
578 # got explicit format string
578 # got explicit format string
579 fmt = new
579 fmt = new
580 try:
580 try:
581 fmt%3.14159
581 fmt%3.14159
582 except Exception:
582 except Exception:
583 raise ValueError("Precision must be int or format string, not %r"%new)
583 raise ValueError("Precision must be int or format string, not %r"%new)
584 elif new:
584 elif new:
585 # otherwise, should be an int
585 # otherwise, should be an int
586 try:
586 try:
587 i = int(new)
587 i = int(new)
588 assert i >= 0
588 assert i >= 0
589 except ValueError:
589 except ValueError:
590 raise ValueError("Precision must be int or format string, not %r"%new)
590 raise ValueError("Precision must be int or format string, not %r"%new)
591 except AssertionError:
591 except AssertionError:
592 raise ValueError("int precision must be non-negative, not %r"%i)
592 raise ValueError("int precision must be non-negative, not %r"%i)
593
593
594 fmt = '%%.%if'%i
594 fmt = '%%.%if'%i
595 if 'numpy' in sys.modules:
595 if 'numpy' in sys.modules:
596 # set numpy precision if it has been imported
596 # set numpy precision if it has been imported
597 import numpy
597 import numpy
598 numpy.set_printoptions(precision=i)
598 numpy.set_printoptions(precision=i)
599 else:
599 else:
600 # default back to repr
600 # default back to repr
601 fmt = '%r'
601 fmt = '%r'
602 if 'numpy' in sys.modules:
602 if 'numpy' in sys.modules:
603 import numpy
603 import numpy
604 # numpy default is 8
604 # numpy default is 8
605 numpy.set_printoptions(precision=8)
605 numpy.set_printoptions(precision=8)
606 self.float_format = fmt
606 self.float_format = fmt
607
607
608 # Use the default pretty printers from IPython.lib.pretty.
608 # Use the default pretty printers from IPython.lib.pretty.
609 def _singleton_printers_default(self):
609 def _singleton_printers_default(self):
610 return pretty._singleton_pprinters.copy()
610 return pretty._singleton_pprinters.copy()
611
611
612 def _type_printers_default(self):
612 def _type_printers_default(self):
613 d = pretty._type_pprinters.copy()
613 d = pretty._type_pprinters.copy()
614 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
614 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
615 return d
615 return d
616
616
617 def _deferred_printers_default(self):
617 def _deferred_printers_default(self):
618 return pretty._deferred_type_pprinters.copy()
618 return pretty._deferred_type_pprinters.copy()
619
619
620 #### FormatterABC interface ####
620 #### FormatterABC interface ####
621
621
622 @warn_format_error
622 @warn_format_error
623 def __call__(self, obj):
623 def __call__(self, obj):
624 """Compute the pretty representation of the object."""
624 """Compute the pretty representation of the object."""
625 if not self.pprint:
625 if not self.pprint:
626 return pretty._safe_repr(obj)
626 return pretty._safe_repr(obj)
627 else:
627 else:
628 # This uses use StringIO, as cStringIO doesn't handle unicode.
628 # This uses use StringIO, as cStringIO doesn't handle unicode.
629 stream = StringIO()
629 stream = StringIO()
630 # self.newline.encode() is a quick fix for issue gh-597. We need to
630 # self.newline.encode() is a quick fix for issue gh-597. We need to
631 # ensure that stream does not get a mix of unicode and bytestrings,
631 # ensure that stream does not get a mix of unicode and bytestrings,
632 # or it will cause trouble.
632 # or it will cause trouble.
633 printer = pretty.RepresentationPrinter(stream, self.verbose,
633 printer = pretty.RepresentationPrinter(stream, self.verbose,
634 self.max_width, unicode_to_str(self.newline),
634 self.max_width, unicode_to_str(self.newline),
635 singleton_pprinters=self.singleton_printers,
635 singleton_pprinters=self.singleton_printers,
636 type_pprinters=self.type_printers,
636 type_pprinters=self.type_printers,
637 deferred_pprinters=self.deferred_printers)
637 deferred_pprinters=self.deferred_printers)
638 printer.pretty(obj)
638 printer.pretty(obj)
639 printer.flush()
639 printer.flush()
640 return stream.getvalue()
640 return stream.getvalue()
641
641
642
642
643 class HTMLFormatter(BaseFormatter):
643 class HTMLFormatter(BaseFormatter):
644 """An HTML formatter.
644 """An HTML formatter.
645
645
646 To define the callables that compute the HTML representation of your
646 To define the callables that compute the HTML representation of your
647 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
647 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
648 or :meth:`for_type_by_name` methods to register functions that handle
648 or :meth:`for_type_by_name` methods to register functions that handle
649 this.
649 this.
650
650
651 The return value of this formatter should be a valid HTML snippet that
651 The return value of this formatter should be a valid HTML snippet that
652 could be injected into an existing DOM. It should *not* include the
652 could be injected into an existing DOM. It should *not* include the
653 ```<html>`` or ```<body>`` tags.
653 ```<html>`` or ```<body>`` tags.
654 """
654 """
655 format_type = Unicode('text/html')
655 format_type = Unicode('text/html')
656
656
657 print_method = ObjectName('_repr_html_')
657 print_method = ObjectName('_repr_html_')
658
658
659
659
660 class SVGFormatter(BaseFormatter):
660 class SVGFormatter(BaseFormatter):
661 """An SVG formatter.
661 """An SVG formatter.
662
662
663 To define the callables that compute the SVG representation of your
663 To define the callables that compute the SVG representation of your
664 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
664 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
665 or :meth:`for_type_by_name` methods to register functions that handle
665 or :meth:`for_type_by_name` methods to register functions that handle
666 this.
666 this.
667
667
668 The return value of this formatter should be valid SVG enclosed in
668 The return value of this formatter should be valid SVG enclosed in
669 ```<svg>``` tags, that could be injected into an existing DOM. It should
669 ```<svg>``` tags, that could be injected into an existing DOM. It should
670 *not* include the ```<html>`` or ```<body>`` tags.
670 *not* include the ```<html>`` or ```<body>`` tags.
671 """
671 """
672 format_type = Unicode('image/svg+xml')
672 format_type = Unicode('image/svg+xml')
673
673
674 print_method = ObjectName('_repr_svg_')
674 print_method = ObjectName('_repr_svg_')
675
675
676
676
677 class PNGFormatter(BaseFormatter):
677 class PNGFormatter(BaseFormatter):
678 """A PNG formatter.
678 """A PNG formatter.
679
679
680 To define the callables that compute the PNG representation of your
680 To define the callables that compute the PNG representation of your
681 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
681 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
682 or :meth:`for_type_by_name` methods to register functions that handle
682 or :meth:`for_type_by_name` methods to register functions that handle
683 this.
683 this.
684
684
685 The return value of this formatter should be raw PNG data, *not*
685 The return value of this formatter should be raw PNG data, *not*
686 base64 encoded.
686 base64 encoded.
687 """
687 """
688 format_type = Unicode('image/png')
688 format_type = Unicode('image/png')
689
689
690 print_method = ObjectName('_repr_png_')
690 print_method = ObjectName('_repr_png_')
691
691
692 _return_type = bytes
692 _return_type = (bytes, unicode_type)
693
693
694
694
695 class JPEGFormatter(BaseFormatter):
695 class JPEGFormatter(BaseFormatter):
696 """A JPEG formatter.
696 """A JPEG formatter.
697
697
698 To define the callables that compute the JPEG representation of your
698 To define the callables that compute the JPEG representation of your
699 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
699 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
700 or :meth:`for_type_by_name` methods to register functions that handle
700 or :meth:`for_type_by_name` methods to register functions that handle
701 this.
701 this.
702
702
703 The return value of this formatter should be raw JPEG data, *not*
703 The return value of this formatter should be raw JPEG data, *not*
704 base64 encoded.
704 base64 encoded.
705 """
705 """
706 format_type = Unicode('image/jpeg')
706 format_type = Unicode('image/jpeg')
707
707
708 print_method = ObjectName('_repr_jpeg_')
708 print_method = ObjectName('_repr_jpeg_')
709
709
710 _return_type = bytes
710 _return_type = (bytes, unicode_type)
711
711
712
712
713 class LatexFormatter(BaseFormatter):
713 class LatexFormatter(BaseFormatter):
714 """A LaTeX formatter.
714 """A LaTeX formatter.
715
715
716 To define the callables that compute the LaTeX representation of your
716 To define the callables that compute the LaTeX representation of your
717 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
717 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
718 or :meth:`for_type_by_name` methods to register functions that handle
718 or :meth:`for_type_by_name` methods to register functions that handle
719 this.
719 this.
720
720
721 The return value of this formatter should be a valid LaTeX equation,
721 The return value of this formatter should be a valid LaTeX equation,
722 enclosed in either ```$```, ```$$``` or another LaTeX equation
722 enclosed in either ```$```, ```$$``` or another LaTeX equation
723 environment.
723 environment.
724 """
724 """
725 format_type = Unicode('text/latex')
725 format_type = Unicode('text/latex')
726
726
727 print_method = ObjectName('_repr_latex_')
727 print_method = ObjectName('_repr_latex_')
728
728
729
729
730 class JSONFormatter(BaseFormatter):
730 class JSONFormatter(BaseFormatter):
731 """A JSON string formatter.
731 """A JSON string formatter.
732
732
733 To define the callables that compute the JSON string representation of
733 To define the callables that compute the JSON string representation of
734 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
734 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
735 or :meth:`for_type_by_name` methods to register functions that handle
735 or :meth:`for_type_by_name` methods to register functions that handle
736 this.
736 this.
737
737
738 The return value of this formatter should be a valid JSON string.
738 The return value of this formatter should be a valid JSON string.
739 """
739 """
740 format_type = Unicode('application/json')
740 format_type = Unicode('application/json')
741
741
742 print_method = ObjectName('_repr_json_')
742 print_method = ObjectName('_repr_json_')
743
743
744
744
745 class JavascriptFormatter(BaseFormatter):
745 class JavascriptFormatter(BaseFormatter):
746 """A Javascript formatter.
746 """A Javascript formatter.
747
747
748 To define the callables that compute the Javascript representation of
748 To define the callables that compute the Javascript representation of
749 your objects, define a :meth:`_repr_javascript_` method or use the
749 your objects, define a :meth:`_repr_javascript_` method or use the
750 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
750 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
751 that handle this.
751 that handle this.
752
752
753 The return value of this formatter should be valid Javascript code and
753 The return value of this formatter should be valid Javascript code and
754 should *not* be enclosed in ```<script>``` tags.
754 should *not* be enclosed in ```<script>``` tags.
755 """
755 """
756 format_type = Unicode('application/javascript')
756 format_type = Unicode('application/javascript')
757
757
758 print_method = ObjectName('_repr_javascript_')
758 print_method = ObjectName('_repr_javascript_')
759
759
760 FormatterABC.register(BaseFormatter)
760 FormatterABC.register(BaseFormatter)
761 FormatterABC.register(PlainTextFormatter)
761 FormatterABC.register(PlainTextFormatter)
762 FormatterABC.register(HTMLFormatter)
762 FormatterABC.register(HTMLFormatter)
763 FormatterABC.register(SVGFormatter)
763 FormatterABC.register(SVGFormatter)
764 FormatterABC.register(PNGFormatter)
764 FormatterABC.register(PNGFormatter)
765 FormatterABC.register(JPEGFormatter)
765 FormatterABC.register(JPEGFormatter)
766 FormatterABC.register(LatexFormatter)
766 FormatterABC.register(LatexFormatter)
767 FormatterABC.register(JSONFormatter)
767 FormatterABC.register(JSONFormatter)
768 FormatterABC.register(JavascriptFormatter)
768 FormatterABC.register(JavascriptFormatter)
769
769
770
770
771 def format_display_data(obj, include=None, exclude=None):
771 def format_display_data(obj, include=None, exclude=None):
772 """Return a format data dict for an object.
772 """Return a format data dict for an object.
773
773
774 By default all format types will be computed.
774 By default all format types will be computed.
775
775
776 The following MIME types are currently implemented:
776 The following MIME types are currently implemented:
777
777
778 * text/plain
778 * text/plain
779 * text/html
779 * text/html
780 * text/latex
780 * text/latex
781 * application/json
781 * application/json
782 * application/javascript
782 * application/javascript
783 * image/png
783 * image/png
784 * image/jpeg
784 * image/jpeg
785 * image/svg+xml
785 * image/svg+xml
786
786
787 Parameters
787 Parameters
788 ----------
788 ----------
789 obj : object
789 obj : object
790 The Python object whose format data will be computed.
790 The Python object whose format data will be computed.
791
791
792 Returns
792 Returns
793 -------
793 -------
794 format_dict : dict
794 format_dict : dict
795 A dictionary of key/value pairs, one or each format that was
795 A dictionary of key/value pairs, one or each format that was
796 generated for the object. The keys are the format types, which
796 generated for the object. The keys are the format types, which
797 will usually be MIME type strings and the values and JSON'able
797 will usually be MIME type strings and the values and JSON'able
798 data structure containing the raw data for the representation in
798 data structure containing the raw data for the representation in
799 that format.
799 that format.
800 include : list or tuple, optional
800 include : list or tuple, optional
801 A list of format type strings (MIME types) to include in the
801 A list of format type strings (MIME types) to include in the
802 format data dict. If this is set *only* the format types included
802 format data dict. If this is set *only* the format types included
803 in this list will be computed.
803 in this list will be computed.
804 exclude : list or tuple, optional
804 exclude : list or tuple, optional
805 A list of format type string (MIME types) to exclue in the format
805 A list of format type string (MIME types) to exclue in the format
806 data dict. If this is set all format types will be computed,
806 data dict. If this is set all format types will be computed,
807 except for those included in this argument.
807 except for those included in this argument.
808 """
808 """
809 from IPython.core.interactiveshell import InteractiveShell
809 from IPython.core.interactiveshell import InteractiveShell
810
810
811 InteractiveShell.instance().display_formatter.format(
811 InteractiveShell.instance().display_formatter.format(
812 obj,
812 obj,
813 include,
813 include,
814 exclude
814 exclude
815 )
815 )
816
816
General Comments 0
You need to be logged in to leave comments. Login now