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