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