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