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