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