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