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