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