##// END OF EJS Templates
handle (data, metadata) in @check_return
MinRK -
Show More
@@ -1,815 +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,
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):
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 return r
196 return r
196 else:
197 else:
197 warn("%s formatter returned invalid type %s for object: %s" % (
198 warn("%s formatter returned invalid type %s for object: %s" % (
198 self.format_type, type(r), pretty._safe_repr(obj)
199 self.format_type, type(r), pretty._safe_repr(args[0])
199 ))
200 ))
200
201
201
202
202
203
203 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
204 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
204 """ Abstract base class for Formatters.
205 """ Abstract base class for Formatters.
205
206
206 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
207 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,
208 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
209 the HTML representation of the object when called.
210 the HTML representation of the object when called.
210 """
211 """
211
212
212 # The format type of the data returned, usually a MIME type.
213 # The format type of the data returned, usually a MIME type.
213 format_type = 'text/plain'
214 format_type = 'text/plain'
214
215
215 # Is the formatter enabled...
216 # Is the formatter enabled...
216 enabled = True
217 enabled = True
217
218
218 @abc.abstractmethod
219 @abc.abstractmethod
219 @warn_format_error
220 @warn_format_error
220 def __call__(self, obj):
221 def __call__(self, obj):
221 """Return a JSON'able representation of the object.
222 """Return a JSON'able representation of the object.
222
223
223 If the object cannot be formatted by this formatter,
224 If the object cannot be formatted by this formatter,
224 warn and return None.
225 warn and return None.
225 """
226 """
226 return repr(obj)
227 return repr(obj)
227
228
228
229
229 def _mod_name_key(typ):
230 def _mod_name_key(typ):
230 """Return a (__module__, __name__) tuple for a type.
231 """Return a (__module__, __name__) tuple for a type.
231
232
232 Used as key in Formatter.deferred_printers.
233 Used as key in Formatter.deferred_printers.
233 """
234 """
234 module = getattr(typ, '__module__', None)
235 module = getattr(typ, '__module__', None)
235 name = getattr(typ, '__name__', None)
236 name = getattr(typ, '__name__', None)
236 return (module, name)
237 return (module, name)
237
238
238
239
239 def _get_type(obj):
240 def _get_type(obj):
240 """Return the type of an instance (old and new-style)"""
241 """Return the type of an instance (old and new-style)"""
241 return getattr(obj, '__class__', None) or type(obj)
242 return getattr(obj, '__class__', None) or type(obj)
242
243
243 _raise_key_error = object()
244 _raise_key_error = object()
244
245
245
246
246 class BaseFormatter(Configurable):
247 class BaseFormatter(Configurable):
247 """A base formatter class that is configurable.
248 """A base formatter class that is configurable.
248
249
249 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.
250 It is a traited :class:`Configurable` class and includes an extensible
251 It is a traited :class:`Configurable` class and includes an extensible
251 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
252 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.
253
254
254 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
255 :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
256 for formatting.
257 for formatting.
257 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
258 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
259 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
259 and :attr:`deferred_printers`.
260 and :attr:`deferred_printers`.
260
261
261 Users should use these dictionaries to register functions that will be
262 Users should use these dictionaries to register functions that will be
262 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
263 have the special print methods). The easiest way of using these
264 have the special print methods). The easiest way of using these
264 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`
265 methods.
266 methods.
266
267
267 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
268 returned and this format type is not used.
269 returned and this format type is not used.
269 """
270 """
270
271
271 format_type = Unicode('text/plain')
272 format_type = Unicode('text/plain')
272 _return_type = string_types
273 _return_type = string_types
273
274
274 enabled = Bool(True, config=True)
275 enabled = Bool(True, config=True)
275
276
276 print_method = ObjectName('__repr__')
277 print_method = ObjectName('__repr__')
277
278
278 # The singleton printers.
279 # The singleton printers.
279 # 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.
280 singleton_printers = Dict(config=True)
281 singleton_printers = Dict(config=True)
281
282
282 # The type-specific printers.
283 # The type-specific printers.
283 # Map type objects to the format functions.
284 # Map type objects to the format functions.
284 type_printers = Dict(config=True)
285 type_printers = Dict(config=True)
285
286
286 # The deferred-import type-specific printers.
287 # The deferred-import type-specific printers.
287 # Map (modulename, classname) pairs to the format functions.
288 # Map (modulename, classname) pairs to the format functions.
288 deferred_printers = Dict(config=True)
289 deferred_printers = Dict(config=True)
289
290
290 @warn_format_error
291 @warn_format_error
291 def __call__(self, obj):
292 def __call__(self, obj):
292 """Compute the format for an object."""
293 """Compute the format for an object."""
293 if self.enabled:
294 if self.enabled:
294 # lookup registered printer
295 # lookup registered printer
295 try:
296 try:
296 printer = self.lookup(obj)
297 printer = self.lookup(obj)
297 except KeyError:
298 except KeyError:
298 pass
299 pass
299 else:
300 else:
300 return printer(obj)
301 return printer(obj)
301 # Finally look for special method names
302 # Finally look for special method names
302 method = pretty._safe_getattr(obj, self.print_method, None)
303 method = pretty._safe_getattr(obj, self.print_method, None)
303 if method is not None:
304 if method is not None:
304 return method()
305 return method()
305 return None
306 return None
306 else:
307 else:
307 return None
308 return None
308
309
309 def __contains__(self, typ):
310 def __contains__(self, typ):
310 """map in to lookup_by_type"""
311 """map in to lookup_by_type"""
311 try:
312 try:
312 self.lookup_by_type(typ)
313 self.lookup_by_type(typ)
313 except KeyError:
314 except KeyError:
314 return False
315 return False
315 else:
316 else:
316 return True
317 return True
317
318
318 def lookup(self, obj):
319 def lookup(self, obj):
319 """Look up the formatter for a given instance.
320 """Look up the formatter for a given instance.
320
321
321 Parameters
322 Parameters
322 ----------
323 ----------
323 obj : object instance
324 obj : object instance
324
325
325 Returns
326 Returns
326 -------
327 -------
327 f : callable
328 f : callable
328 The registered formatting callable for the type.
329 The registered formatting callable for the type.
329
330
330 Raises
331 Raises
331 ------
332 ------
332 KeyError if the type has not been registered.
333 KeyError if the type has not been registered.
333 """
334 """
334 # look for singleton first
335 # look for singleton first
335 obj_id = id(obj)
336 obj_id = id(obj)
336 if obj_id in self.singleton_printers:
337 if obj_id in self.singleton_printers:
337 return self.singleton_printers[obj_id]
338 return self.singleton_printers[obj_id]
338 # then lookup by type
339 # then lookup by type
339 return self.lookup_by_type(_get_type(obj))
340 return self.lookup_by_type(_get_type(obj))
340
341
341 def lookup_by_type(self, typ):
342 def lookup_by_type(self, typ):
342 """Look up the registered formatter for a type.
343 """Look up the registered formatter for a type.
343
344
344 Parameters
345 Parameters
345 ----------
346 ----------
346 typ : type or '__module__.__name__' string for a type
347 typ : type or '__module__.__name__' string for a type
347
348
348 Returns
349 Returns
349 -------
350 -------
350 f : callable
351 f : callable
351 The registered formatting callable for the type.
352 The registered formatting callable for the type.
352
353
353 Raises
354 Raises
354 ------
355 ------
355 KeyError if the type has not been registered.
356 KeyError if the type has not been registered.
356 """
357 """
357 if isinstance(typ, string_types):
358 if isinstance(typ, string_types):
358 typ_key = tuple(typ.rsplit('.',1))
359 typ_key = tuple(typ.rsplit('.',1))
359 if typ_key not in self.deferred_printers:
360 if typ_key not in self.deferred_printers:
360 # 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
361 # iterate over all of the types to check.
362 # iterate over all of the types to check.
362 for cls in self.type_printers:
363 for cls in self.type_printers:
363 if _mod_name_key(cls) == typ_key:
364 if _mod_name_key(cls) == typ_key:
364 return self.type_printers[cls]
365 return self.type_printers[cls]
365 else:
366 else:
366 return self.deferred_printers[typ_key]
367 return self.deferred_printers[typ_key]
367 else:
368 else:
368 for cls in pretty._get_mro(typ):
369 for cls in pretty._get_mro(typ):
369 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):
370 return self.type_printers[cls]
371 return self.type_printers[cls]
371
372
372 # If we have reached here, the lookup failed.
373 # If we have reached here, the lookup failed.
373 raise KeyError("No registered printer for {0!r}".format(typ))
374 raise KeyError("No registered printer for {0!r}".format(typ))
374
375
375 def for_type(self, typ, func=None):
376 def for_type(self, typ, func=None):
376 """Add a format function for a given type.
377 """Add a format function for a given type.
377
378
378 Parameters
379 Parameters
379 -----------
380 -----------
380 typ : type or '__module__.__name__' string for a type
381 typ : type or '__module__.__name__' string for a type
381 The class of the object that will be formatted using `func`.
382 The class of the object that will be formatted using `func`.
382 func : callable
383 func : callable
383 A callable for computing the format data.
384 A callable for computing the format data.
384 `func` will be called with the object to be formatted,
385 `func` will be called with the object to be formatted,
385 and will return the raw data in this formatter's format.
386 and will return the raw data in this formatter's format.
386 Subclasses may use a different call signature for the
387 Subclasses may use a different call signature for the
387 `func` argument.
388 `func` argument.
388
389
389 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,
390 only returning the current value.
391 only returning the current value.
391
392
392 Returns
393 Returns
393 -------
394 -------
394 oldfunc : callable
395 oldfunc : callable
395 The currently registered callable.
396 The currently registered callable.
396 If you are registering a new formatter,
397 If you are registering a new formatter,
397 this will be the previous value (to enable restoring later).
398 this will be the previous value (to enable restoring later).
398 """
399 """
399 # if string given, interpret as 'pkg.module.class_name'
400 # if string given, interpret as 'pkg.module.class_name'
400 if isinstance(typ, string_types):
401 if isinstance(typ, string_types):
401 type_module, type_name = typ.rsplit('.', 1)
402 type_module, type_name = typ.rsplit('.', 1)
402 return self.for_type_by_name(type_module, type_name, func)
403 return self.for_type_by_name(type_module, type_name, func)
403
404
404 try:
405 try:
405 oldfunc = self.lookup_by_type(typ)
406 oldfunc = self.lookup_by_type(typ)
406 except KeyError:
407 except KeyError:
407 oldfunc = None
408 oldfunc = None
408
409
409 if func is not None:
410 if func is not None:
410 self.type_printers[typ] = func
411 self.type_printers[typ] = func
411
412
412 return oldfunc
413 return oldfunc
413
414
414 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):
415 """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
416 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.
417
418
418 Parameters
419 Parameters
419 ----------
420 ----------
420 type_module : str
421 type_module : str
421 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
422 ``numpy``.
423 ``numpy``.
423 type_name : str
424 type_name : str
424 The name of the type (the class name), like ``dtype``
425 The name of the type (the class name), like ``dtype``
425 func : callable
426 func : callable
426 A callable for computing the format data.
427 A callable for computing the format data.
427 `func` will be called with the object to be formatted,
428 `func` will be called with the object to be formatted,
428 and will return the raw data in this formatter's format.
429 and will return the raw data in this formatter's format.
429 Subclasses may use a different call signature for the
430 Subclasses may use a different call signature for the
430 `func` argument.
431 `func` argument.
431
432
432 If `func` is None or unspecified, there will be no change,
433 If `func` is None or unspecified, there will be no change,
433 only returning the current value.
434 only returning the current value.
434
435
435 Returns
436 Returns
436 -------
437 -------
437 oldfunc : callable
438 oldfunc : callable
438 The currently registered callable.
439 The currently registered callable.
439 If you are registering a new formatter,
440 If you are registering a new formatter,
440 this will be the previous value (to enable restoring later).
441 this will be the previous value (to enable restoring later).
441 """
442 """
442 key = (type_module, type_name)
443 key = (type_module, type_name)
443
444
444 try:
445 try:
445 oldfunc = self.lookup_by_type("%s.%s" % key)
446 oldfunc = self.lookup_by_type("%s.%s" % key)
446 except KeyError:
447 except KeyError:
447 oldfunc = None
448 oldfunc = None
448
449
449 if func is not None:
450 if func is not None:
450 self.deferred_printers[key] = func
451 self.deferred_printers[key] = func
451 return oldfunc
452 return oldfunc
452
453
453 def pop(self, typ, default=_raise_key_error):
454 def pop(self, typ, default=_raise_key_error):
454 """Pop a formatter for the given type.
455 """Pop a formatter for the given type.
455
456
456 Parameters
457 Parameters
457 ----------
458 ----------
458 typ : type or '__module__.__name__' string for a type
459 typ : type or '__module__.__name__' string for a type
459 default : object
460 default : object
460 value to be returned if no formatter is registered for typ.
461 value to be returned if no formatter is registered for typ.
461
462
462 Returns
463 Returns
463 -------
464 -------
464 obj : object
465 obj : object
465 The last registered object for the type.
466 The last registered object for the type.
466
467
467 Raises
468 Raises
468 ------
469 ------
469 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.
470 """
471 """
471
472
472 if isinstance(typ, string_types):
473 if isinstance(typ, string_types):
473 typ_key = tuple(typ.rsplit('.',1))
474 typ_key = tuple(typ.rsplit('.',1))
474 if typ_key not in self.deferred_printers:
475 if typ_key not in self.deferred_printers:
475 # 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
476 # iterate over all of the types to check.
477 # iterate over all of the types to check.
477 for cls in self.type_printers:
478 for cls in self.type_printers:
478 if _mod_name_key(cls) == typ_key:
479 if _mod_name_key(cls) == typ_key:
479 old = self.type_printers.pop(cls)
480 old = self.type_printers.pop(cls)
480 break
481 break
481 else:
482 else:
482 old = default
483 old = default
483 else:
484 else:
484 old = self.deferred_printers.pop(typ_key)
485 old = self.deferred_printers.pop(typ_key)
485 else:
486 else:
486 if typ in self.type_printers:
487 if typ in self.type_printers:
487 old = self.type_printers.pop(typ)
488 old = self.type_printers.pop(typ)
488 else:
489 else:
489 old = self.deferred_printers.pop(_mod_name_key(typ), default)
490 old = self.deferred_printers.pop(_mod_name_key(typ), default)
490 if old is _raise_key_error:
491 if old is _raise_key_error:
491 raise KeyError("No registered value for {0!r}".format(typ))
492 raise KeyError("No registered value for {0!r}".format(typ))
492 return old
493 return old
493
494
494 def _in_deferred_types(self, cls):
495 def _in_deferred_types(self, cls):
495 """
496 """
496 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.
497
498
498 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.
499 """
500 """
500 mod = getattr(cls, '__module__', None)
501 mod = getattr(cls, '__module__', None)
501 name = getattr(cls, '__name__', None)
502 name = getattr(cls, '__name__', None)
502 key = (mod, name)
503 key = (mod, name)
503 if key in self.deferred_printers:
504 if key in self.deferred_printers:
504 # Move the printer over to the regular registry.
505 # Move the printer over to the regular registry.
505 printer = self.deferred_printers.pop(key)
506 printer = self.deferred_printers.pop(key)
506 self.type_printers[cls] = printer
507 self.type_printers[cls] = printer
507 return True
508 return True
508 return False
509 return False
509
510
510
511
511 class PlainTextFormatter(BaseFormatter):
512 class PlainTextFormatter(BaseFormatter):
512 """The default pretty-printer.
513 """The default pretty-printer.
513
514
514 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
515 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.
516 See the documentation of :mod:`IPython.lib.pretty` for details on
517 See the documentation of :mod:`IPython.lib.pretty` for details on
517 how to write pretty printers. Here is a simple example::
518 how to write pretty printers. Here is a simple example::
518
519
519 def dtype_pprinter(obj, p, cycle):
520 def dtype_pprinter(obj, p, cycle):
520 if cycle:
521 if cycle:
521 return p.text('dtype(...)')
522 return p.text('dtype(...)')
522 if hasattr(obj, 'fields'):
523 if hasattr(obj, 'fields'):
523 if obj.fields is None:
524 if obj.fields is None:
524 p.text(repr(obj))
525 p.text(repr(obj))
525 else:
526 else:
526 p.begin_group(7, 'dtype([')
527 p.begin_group(7, 'dtype([')
527 for i, field in enumerate(obj.descr):
528 for i, field in enumerate(obj.descr):
528 if i > 0:
529 if i > 0:
529 p.text(',')
530 p.text(',')
530 p.breakable()
531 p.breakable()
531 p.pretty(field)
532 p.pretty(field)
532 p.end_group(7, '])')
533 p.end_group(7, '])')
533 """
534 """
534
535
535 # The format type of data returned.
536 # The format type of data returned.
536 format_type = Unicode('text/plain')
537 format_type = Unicode('text/plain')
537
538
538 # This subclass ignores this attribute as it always need to return
539 # This subclass ignores this attribute as it always need to return
539 # something.
540 # something.
540 enabled = Bool(True, config=False)
541 enabled = Bool(True, config=False)
541
542
542 # Look for a _repr_pretty_ methods to use for pretty printing.
543 # Look for a _repr_pretty_ methods to use for pretty printing.
543 print_method = ObjectName('_repr_pretty_')
544 print_method = ObjectName('_repr_pretty_')
544
545
545 # Whether to pretty-print or not.
546 # Whether to pretty-print or not.
546 pprint = Bool(True, config=True)
547 pprint = Bool(True, config=True)
547
548
548 # Whether to be verbose or not.
549 # Whether to be verbose or not.
549 verbose = Bool(False, config=True)
550 verbose = Bool(False, config=True)
550
551
551 # The maximum width.
552 # The maximum width.
552 max_width = Integer(79, config=True)
553 max_width = Integer(79, config=True)
553
554
554 # The newline character.
555 # The newline character.
555 newline = Unicode('\n', config=True)
556 newline = Unicode('\n', config=True)
556
557
557 # format-string for pprinting floats
558 # format-string for pprinting floats
558 float_format = Unicode('%r')
559 float_format = Unicode('%r')
559 # setter for float precision, either int or direct format-string
560 # setter for float precision, either int or direct format-string
560 float_precision = CUnicode('', config=True)
561 float_precision = CUnicode('', config=True)
561
562
562 def _float_precision_changed(self, name, old, new):
563 def _float_precision_changed(self, name, old, new):
563 """float_precision changed, set float_format accordingly.
564 """float_precision changed, set float_format accordingly.
564
565
565 float_precision can be set by int or str.
566 float_precision can be set by int or str.
566 This will set float_format, after interpreting input.
567 This will set float_format, after interpreting input.
567 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.
568
569
569 integer `n` sets format to '%.nf', otherwise, format set directly.
570 integer `n` sets format to '%.nf', otherwise, format set directly.
570
571
571 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).
572
573
573 This parameter can be set via the '%precision' magic.
574 This parameter can be set via the '%precision' magic.
574 """
575 """
575
576
576 if '%' in new:
577 if '%' in new:
577 # got explicit format string
578 # got explicit format string
578 fmt = new
579 fmt = new
579 try:
580 try:
580 fmt%3.14159
581 fmt%3.14159
581 except Exception:
582 except Exception:
582 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)
583 elif new:
584 elif new:
584 # otherwise, should be an int
585 # otherwise, should be an int
585 try:
586 try:
586 i = int(new)
587 i = int(new)
587 assert i >= 0
588 assert i >= 0
588 except ValueError:
589 except ValueError:
589 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)
590 except AssertionError:
591 except AssertionError:
591 raise ValueError("int precision must be non-negative, not %r"%i)
592 raise ValueError("int precision must be non-negative, not %r"%i)
592
593
593 fmt = '%%.%if'%i
594 fmt = '%%.%if'%i
594 if 'numpy' in sys.modules:
595 if 'numpy' in sys.modules:
595 # set numpy precision if it has been imported
596 # set numpy precision if it has been imported
596 import numpy
597 import numpy
597 numpy.set_printoptions(precision=i)
598 numpy.set_printoptions(precision=i)
598 else:
599 else:
599 # default back to repr
600 # default back to repr
600 fmt = '%r'
601 fmt = '%r'
601 if 'numpy' in sys.modules:
602 if 'numpy' in sys.modules:
602 import numpy
603 import numpy
603 # numpy default is 8
604 # numpy default is 8
604 numpy.set_printoptions(precision=8)
605 numpy.set_printoptions(precision=8)
605 self.float_format = fmt
606 self.float_format = fmt
606
607
607 # Use the default pretty printers from IPython.lib.pretty.
608 # Use the default pretty printers from IPython.lib.pretty.
608 def _singleton_printers_default(self):
609 def _singleton_printers_default(self):
609 return pretty._singleton_pprinters.copy()
610 return pretty._singleton_pprinters.copy()
610
611
611 def _type_printers_default(self):
612 def _type_printers_default(self):
612 d = pretty._type_pprinters.copy()
613 d = pretty._type_pprinters.copy()
613 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)
614 return d
615 return d
615
616
616 def _deferred_printers_default(self):
617 def _deferred_printers_default(self):
617 return pretty._deferred_type_pprinters.copy()
618 return pretty._deferred_type_pprinters.copy()
618
619
619 #### FormatterABC interface ####
620 #### FormatterABC interface ####
620
621
621 @warn_format_error
622 @warn_format_error
622 def __call__(self, obj):
623 def __call__(self, obj):
623 """Compute the pretty representation of the object."""
624 """Compute the pretty representation of the object."""
624 if not self.pprint:
625 if not self.pprint:
625 return pretty._safe_repr(obj)
626 return pretty._safe_repr(obj)
626 else:
627 else:
627 # This uses use StringIO, as cStringIO doesn't handle unicode.
628 # This uses use StringIO, as cStringIO doesn't handle unicode.
628 stream = StringIO()
629 stream = StringIO()
629 # 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
630 # 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,
631 # or it will cause trouble.
632 # or it will cause trouble.
632 printer = pretty.RepresentationPrinter(stream, self.verbose,
633 printer = pretty.RepresentationPrinter(stream, self.verbose,
633 self.max_width, unicode_to_str(self.newline),
634 self.max_width, unicode_to_str(self.newline),
634 singleton_pprinters=self.singleton_printers,
635 singleton_pprinters=self.singleton_printers,
635 type_pprinters=self.type_printers,
636 type_pprinters=self.type_printers,
636 deferred_pprinters=self.deferred_printers)
637 deferred_pprinters=self.deferred_printers)
637 printer.pretty(obj)
638 printer.pretty(obj)
638 printer.flush()
639 printer.flush()
639 return stream.getvalue()
640 return stream.getvalue()
640
641
641
642
642 class HTMLFormatter(BaseFormatter):
643 class HTMLFormatter(BaseFormatter):
643 """An HTML formatter.
644 """An HTML formatter.
644
645
645 To define the callables that compute the HTML representation of your
646 To define the callables that compute the HTML representation of your
646 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`
647 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
648 this.
649 this.
649
650
650 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
651 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
652 ```<html>`` or ```<body>`` tags.
653 ```<html>`` or ```<body>`` tags.
653 """
654 """
654 format_type = Unicode('text/html')
655 format_type = Unicode('text/html')
655
656
656 print_method = ObjectName('_repr_html_')
657 print_method = ObjectName('_repr_html_')
657
658
658
659
659 class SVGFormatter(BaseFormatter):
660 class SVGFormatter(BaseFormatter):
660 """An SVG formatter.
661 """An SVG formatter.
661
662
662 To define the callables that compute the SVG representation of your
663 To define the callables that compute the SVG representation of your
663 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`
664 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
665 this.
666 this.
666
667
667 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
668 ```<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
669 *not* include the ```<html>`` or ```<body>`` tags.
670 *not* include the ```<html>`` or ```<body>`` tags.
670 """
671 """
671 format_type = Unicode('image/svg+xml')
672 format_type = Unicode('image/svg+xml')
672
673
673 print_method = ObjectName('_repr_svg_')
674 print_method = ObjectName('_repr_svg_')
674
675
675
676
676 class PNGFormatter(BaseFormatter):
677 class PNGFormatter(BaseFormatter):
677 """A PNG formatter.
678 """A PNG formatter.
678
679
679 To define the callables that compute the PNG representation of your
680 To define the callables that compute the PNG representation of your
680 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`
681 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
682 this.
683 this.
683
684
684 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*
685 base64 encoded.
686 base64 encoded.
686 """
687 """
687 format_type = Unicode('image/png')
688 format_type = Unicode('image/png')
688
689
689 print_method = ObjectName('_repr_png_')
690 print_method = ObjectName('_repr_png_')
690
691
691 _return_type = bytes
692 _return_type = bytes
692
693
693
694
694 class JPEGFormatter(BaseFormatter):
695 class JPEGFormatter(BaseFormatter):
695 """A JPEG formatter.
696 """A JPEG formatter.
696
697
697 To define the callables that compute the JPEG representation of your
698 To define the callables that compute the JPEG representation of your
698 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`
699 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
700 this.
701 this.
701
702
702 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*
703 base64 encoded.
704 base64 encoded.
704 """
705 """
705 format_type = Unicode('image/jpeg')
706 format_type = Unicode('image/jpeg')
706
707
707 print_method = ObjectName('_repr_jpeg_')
708 print_method = ObjectName('_repr_jpeg_')
708
709
709 _return_type = bytes
710 _return_type = bytes
710
711
711
712
712 class LatexFormatter(BaseFormatter):
713 class LatexFormatter(BaseFormatter):
713 """A LaTeX formatter.
714 """A LaTeX formatter.
714
715
715 To define the callables that compute the LaTeX representation of your
716 To define the callables that compute the LaTeX representation of your
716 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`
717 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
718 this.
719 this.
719
720
720 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,
721 enclosed in either ```$```, ```$$``` or another LaTeX equation
722 enclosed in either ```$```, ```$$``` or another LaTeX equation
722 environment.
723 environment.
723 """
724 """
724 format_type = Unicode('text/latex')
725 format_type = Unicode('text/latex')
725
726
726 print_method = ObjectName('_repr_latex_')
727 print_method = ObjectName('_repr_latex_')
727
728
728
729
729 class JSONFormatter(BaseFormatter):
730 class JSONFormatter(BaseFormatter):
730 """A JSON string formatter.
731 """A JSON string formatter.
731
732
732 To define the callables that compute the JSON string representation of
733 To define the callables that compute the JSON string representation of
733 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`
734 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
735 this.
736 this.
736
737
737 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.
738 """
739 """
739 format_type = Unicode('application/json')
740 format_type = Unicode('application/json')
740
741
741 print_method = ObjectName('_repr_json_')
742 print_method = ObjectName('_repr_json_')
742
743
743
744
744 class JavascriptFormatter(BaseFormatter):
745 class JavascriptFormatter(BaseFormatter):
745 """A Javascript formatter.
746 """A Javascript formatter.
746
747
747 To define the callables that compute the Javascript representation of
748 To define the callables that compute the Javascript representation of
748 your objects, define a :meth:`_repr_javascript_` method or use the
749 your objects, define a :meth:`_repr_javascript_` method or use the
749 :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
750 that handle this.
751 that handle this.
751
752
752 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
753 should *not* be enclosed in ```<script>``` tags.
754 should *not* be enclosed in ```<script>``` tags.
754 """
755 """
755 format_type = Unicode('application/javascript')
756 format_type = Unicode('application/javascript')
756
757
757 print_method = ObjectName('_repr_javascript_')
758 print_method = ObjectName('_repr_javascript_')
758
759
759 FormatterABC.register(BaseFormatter)
760 FormatterABC.register(BaseFormatter)
760 FormatterABC.register(PlainTextFormatter)
761 FormatterABC.register(PlainTextFormatter)
761 FormatterABC.register(HTMLFormatter)
762 FormatterABC.register(HTMLFormatter)
762 FormatterABC.register(SVGFormatter)
763 FormatterABC.register(SVGFormatter)
763 FormatterABC.register(PNGFormatter)
764 FormatterABC.register(PNGFormatter)
764 FormatterABC.register(JPEGFormatter)
765 FormatterABC.register(JPEGFormatter)
765 FormatterABC.register(LatexFormatter)
766 FormatterABC.register(LatexFormatter)
766 FormatterABC.register(JSONFormatter)
767 FormatterABC.register(JSONFormatter)
767 FormatterABC.register(JavascriptFormatter)
768 FormatterABC.register(JavascriptFormatter)
768
769
769
770
770 def format_display_data(obj, include=None, exclude=None):
771 def format_display_data(obj, include=None, exclude=None):
771 """Return a format data dict for an object.
772 """Return a format data dict for an object.
772
773
773 By default all format types will be computed.
774 By default all format types will be computed.
774
775
775 The following MIME types are currently implemented:
776 The following MIME types are currently implemented:
776
777
777 * text/plain
778 * text/plain
778 * text/html
779 * text/html
779 * text/latex
780 * text/latex
780 * application/json
781 * application/json
781 * application/javascript
782 * application/javascript
782 * image/png
783 * image/png
783 * image/jpeg
784 * image/jpeg
784 * image/svg+xml
785 * image/svg+xml
785
786
786 Parameters
787 Parameters
787 ----------
788 ----------
788 obj : object
789 obj : object
789 The Python object whose format data will be computed.
790 The Python object whose format data will be computed.
790
791
791 Returns
792 Returns
792 -------
793 -------
793 format_dict : dict
794 format_dict : dict
794 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
795 generated for the object. The keys are the format types, which
796 generated for the object. The keys are the format types, which
796 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
797 data structure containing the raw data for the representation in
798 data structure containing the raw data for the representation in
798 that format.
799 that format.
799 include : list or tuple, optional
800 include : list or tuple, optional
800 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
801 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
802 in this list will be computed.
803 in this list will be computed.
803 exclude : list or tuple, optional
804 exclude : list or tuple, optional
804 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
805 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,
806 except for those included in this argument.
807 except for those included in this argument.
807 """
808 """
808 from IPython.core.interactiveshell import InteractiveShell
809 from IPython.core.interactiveshell import InteractiveShell
809
810
810 InteractiveShell.instance().display_formatter.format(
811 InteractiveShell.instance().display_formatter.format(
811 obj,
812 obj,
812 include,
813 include,
813 exclude
814 exclude
814 )
815 )
815
816
General Comments 0
You need to be logged in to leave comments. Login now