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