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