##// END OF EJS Templates
add missing warnings import
MinRK -
Show More
@@ -1,632 +1,633 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 # We must use StringIO, as cStringIO doesn't handle unicode properly.
30 # We must use StringIO, as cStringIO doesn't handle unicode properly.
30 from StringIO import StringIO
31 from StringIO import StringIO
31
32
32 # Our own imports
33 # Our own imports
33 from IPython.config.configurable import Configurable
34 from IPython.config.configurable import Configurable
34 from IPython.lib import pretty
35 from IPython.lib import pretty
35 from IPython.utils.traitlets import (
36 from IPython.utils.traitlets import (
36 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
37 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
37 )
38 )
38 from IPython.utils.py3compat import unicode_to_str
39 from IPython.utils.py3compat import unicode_to_str
39
40
40
41
41 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
42 # The main DisplayFormatter class
43 # The main DisplayFormatter class
43 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
44
45
45
46
46 class DisplayFormatter(Configurable):
47 class DisplayFormatter(Configurable):
47
48
48 # When set to true only the default plain text formatter will be used.
49 # When set to true only the default plain text formatter will be used.
49 plain_text_only = Bool(False, config=True)
50 plain_text_only = Bool(False, config=True)
50 def _plain_text_only_changed(self, name, old, new):
51 def _plain_text_only_changed(self, name, old, new):
51 warnings.warn("""DisplayFormatter.plain_text_only is deprecated.
52 warnings.warn("""DisplayFormatter.plain_text_only is deprecated.
52
53
53 Use DisplayFormatter.active_types = ['text/plain']
54 Use DisplayFormatter.active_types = ['text/plain']
54 for the same effect.
55 for the same effect.
55 """, DeprecationWarning)
56 """, DeprecationWarning)
56 if new:
57 if new:
57 self.active_types = ['text/plain']
58 self.active_types = ['text/plain']
58 else:
59 else:
59 self.active_types = self.format_types
60 self.active_types = self.format_types
60
61
61 active_types = List(Unicode, config=True,
62 active_types = List(Unicode, config=True,
62 help="""List of currently active mime-types""")
63 help="""List of currently active mime-types""")
63 def _active_types_default(self):
64 def _active_types_default(self):
64 return self.format_types
65 return self.format_types
65
66
66 # A dict of formatter whose keys are format types (MIME types) and whose
67 # A dict of formatter whose keys are format types (MIME types) and whose
67 # values are subclasses of BaseFormatter.
68 # values are subclasses of BaseFormatter.
68 formatters = Dict()
69 formatters = Dict()
69 def _formatters_default(self):
70 def _formatters_default(self):
70 """Activate the default formatters."""
71 """Activate the default formatters."""
71 formatter_classes = [
72 formatter_classes = [
72 PlainTextFormatter,
73 PlainTextFormatter,
73 HTMLFormatter,
74 HTMLFormatter,
74 SVGFormatter,
75 SVGFormatter,
75 PNGFormatter,
76 PNGFormatter,
76 JPEGFormatter,
77 JPEGFormatter,
77 LatexFormatter,
78 LatexFormatter,
78 JSONFormatter,
79 JSONFormatter,
79 JavascriptFormatter
80 JavascriptFormatter
80 ]
81 ]
81 d = {}
82 d = {}
82 for cls in formatter_classes:
83 for cls in formatter_classes:
83 f = cls(config=self.config)
84 f = cls(config=self.config)
84 d[f.format_type] = f
85 d[f.format_type] = f
85 return d
86 return d
86
87
87 def format(self, obj, include=None, exclude=None):
88 def format(self, obj, include=None, exclude=None):
88 """Return a format data dict for an object.
89 """Return a format data dict for an object.
89
90
90 By default all format types will be computed.
91 By default all format types will be computed.
91
92
92 The following MIME types are currently implemented:
93 The following MIME types are currently implemented:
93
94
94 * text/plain
95 * text/plain
95 * text/html
96 * text/html
96 * text/latex
97 * text/latex
97 * application/json
98 * application/json
98 * application/javascript
99 * application/javascript
99 * image/png
100 * image/png
100 * image/jpeg
101 * image/jpeg
101 * image/svg+xml
102 * image/svg+xml
102
103
103 Parameters
104 Parameters
104 ----------
105 ----------
105 obj : object
106 obj : object
106 The Python object whose format data will be computed.
107 The Python object whose format data will be computed.
107 include : list or tuple, optional
108 include : list or tuple, optional
108 A list of format type strings (MIME types) to include in the
109 A list of format type strings (MIME types) to include in the
109 format data dict. If this is set *only* the format types included
110 format data dict. If this is set *only* the format types included
110 in this list will be computed.
111 in this list will be computed.
111 If unspecified, `active_types` will be used.
112 If unspecified, `active_types` will be used.
112 exclude : list or tuple, optional
113 exclude : list or tuple, optional
113 A list of format type string (MIME types) to exclude in the format
114 A list of format type string (MIME types) to exclude in the format
114 data dict. If this is set all format types will be computed,
115 data dict. If this is set all format types will be computed,
115 except for those included in this argument.
116 except for those included in this argument.
116
117
117 Returns
118 Returns
118 -------
119 -------
119 format_dict : dict
120 format_dict : dict
120 A dictionary of key/value pairs, one or each format that was
121 A dictionary of key/value pairs, one or each format that was
121 generated for the object. The keys are the format types, which
122 generated for the object. The keys are the format types, which
122 will usually be MIME type strings and the values and JSON'able
123 will usually be MIME type strings and the values and JSON'able
123 data structure containing the raw data for the representation in
124 data structure containing the raw data for the representation in
124 that format.
125 that format.
125 """
126 """
126 format_dict = {}
127 format_dict = {}
127 if include is None:
128 if include is None:
128 include = self.active_types
129 include = self.active_types
129
130
130 for format_type, formatter in self.formatters.items():
131 for format_type, formatter in self.formatters.items():
131 if format_type not in include:
132 if format_type not in include:
132 continue
133 continue
133 if exclude is not None:
134 if exclude is not None:
134 if format_type in exclude:
135 if format_type in exclude:
135 continue
136 continue
136 try:
137 try:
137 data = formatter(obj)
138 data = formatter(obj)
138 except:
139 except:
139 # FIXME: log the exception
140 # FIXME: log the exception
140 raise
141 raise
141 if data is not None:
142 if data is not None:
142 format_dict[format_type] = data
143 format_dict[format_type] = data
143 return format_dict
144 return format_dict
144
145
145 @property
146 @property
146 def format_types(self):
147 def format_types(self):
147 """Return the format types (MIME types) of the active formatters."""
148 """Return the format types (MIME types) of the active formatters."""
148 return self.formatters.keys()
149 return self.formatters.keys()
149
150
150
151
151 #-----------------------------------------------------------------------------
152 #-----------------------------------------------------------------------------
152 # Formatters for specific format types (text, html, svg, etc.)
153 # Formatters for specific format types (text, html, svg, etc.)
153 #-----------------------------------------------------------------------------
154 #-----------------------------------------------------------------------------
154
155
155
156
156 class FormatterABC(object):
157 class FormatterABC(object):
157 """ Abstract base class for Formatters.
158 """ Abstract base class for Formatters.
158
159
159 A formatter is a callable class that is responsible for computing the
160 A formatter is a callable class that is responsible for computing the
160 raw format data for a particular format type (MIME type). For example,
161 raw format data for a particular format type (MIME type). For example,
161 an HTML formatter would have a format type of `text/html` and would return
162 an HTML formatter would have a format type of `text/html` and would return
162 the HTML representation of the object when called.
163 the HTML representation of the object when called.
163 """
164 """
164 __metaclass__ = abc.ABCMeta
165 __metaclass__ = abc.ABCMeta
165
166
166 # The format type of the data returned, usually a MIME type.
167 # The format type of the data returned, usually a MIME type.
167 format_type = 'text/plain'
168 format_type = 'text/plain'
168
169
169 # Is the formatter enabled...
170 # Is the formatter enabled...
170 enabled = True
171 enabled = True
171
172
172 @abc.abstractmethod
173 @abc.abstractmethod
173 def __call__(self, obj):
174 def __call__(self, obj):
174 """Return a JSON'able representation of the object.
175 """Return a JSON'able representation of the object.
175
176
176 If the object cannot be formatted by this formatter, then return None
177 If the object cannot be formatted by this formatter, then return None
177 """
178 """
178 try:
179 try:
179 return repr(obj)
180 return repr(obj)
180 except TypeError:
181 except TypeError:
181 return None
182 return None
182
183
183
184
184 class BaseFormatter(Configurable):
185 class BaseFormatter(Configurable):
185 """A base formatter class that is configurable.
186 """A base formatter class that is configurable.
186
187
187 This formatter should usually be used as the base class of all formatters.
188 This formatter should usually be used as the base class of all formatters.
188 It is a traited :class:`Configurable` class and includes an extensible
189 It is a traited :class:`Configurable` class and includes an extensible
189 API for users to determine how their objects are formatted. The following
190 API for users to determine how their objects are formatted. The following
190 logic is used to find a function to format an given object.
191 logic is used to find a function to format an given object.
191
192
192 1. The object is introspected to see if it has a method with the name
193 1. The object is introspected to see if it has a method with the name
193 :attr:`print_method`. If is does, that object is passed to that method
194 :attr:`print_method`. If is does, that object is passed to that method
194 for formatting.
195 for formatting.
195 2. If no print method is found, three internal dictionaries are consulted
196 2. If no print method is found, three internal dictionaries are consulted
196 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
197 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
197 and :attr:`deferred_printers`.
198 and :attr:`deferred_printers`.
198
199
199 Users should use these dictionaries to register functions that will be
200 Users should use these dictionaries to register functions that will be
200 used to compute the format data for their objects (if those objects don't
201 used to compute the format data for their objects (if those objects don't
201 have the special print methods). The easiest way of using these
202 have the special print methods). The easiest way of using these
202 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
203 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
203 methods.
204 methods.
204
205
205 If no function/callable is found to compute the format data, ``None`` is
206 If no function/callable is found to compute the format data, ``None`` is
206 returned and this format type is not used.
207 returned and this format type is not used.
207 """
208 """
208
209
209 format_type = Unicode('text/plain')
210 format_type = Unicode('text/plain')
210
211
211 enabled = Bool(True, config=True)
212 enabled = Bool(True, config=True)
212
213
213 print_method = ObjectName('__repr__')
214 print_method = ObjectName('__repr__')
214
215
215 # The singleton printers.
216 # The singleton printers.
216 # Maps the IDs of the builtin singleton objects to the format functions.
217 # Maps the IDs of the builtin singleton objects to the format functions.
217 singleton_printers = Dict(config=True)
218 singleton_printers = Dict(config=True)
218 def _singleton_printers_default(self):
219 def _singleton_printers_default(self):
219 return {}
220 return {}
220
221
221 # The type-specific printers.
222 # The type-specific printers.
222 # Map type objects to the format functions.
223 # Map type objects to the format functions.
223 type_printers = Dict(config=True)
224 type_printers = Dict(config=True)
224 def _type_printers_default(self):
225 def _type_printers_default(self):
225 return {}
226 return {}
226
227
227 # The deferred-import type-specific printers.
228 # The deferred-import type-specific printers.
228 # Map (modulename, classname) pairs to the format functions.
229 # Map (modulename, classname) pairs to the format functions.
229 deferred_printers = Dict(config=True)
230 deferred_printers = Dict(config=True)
230 def _deferred_printers_default(self):
231 def _deferred_printers_default(self):
231 return {}
232 return {}
232
233
233 def __call__(self, obj):
234 def __call__(self, obj):
234 """Compute the format for an object."""
235 """Compute the format for an object."""
235 if self.enabled:
236 if self.enabled:
236 obj_id = id(obj)
237 obj_id = id(obj)
237 try:
238 try:
238 obj_class = getattr(obj, '__class__', None) or type(obj)
239 obj_class = getattr(obj, '__class__', None) or type(obj)
239 # First try to find registered singleton printers for the type.
240 # First try to find registered singleton printers for the type.
240 try:
241 try:
241 printer = self.singleton_printers[obj_id]
242 printer = self.singleton_printers[obj_id]
242 except (TypeError, KeyError):
243 except (TypeError, KeyError):
243 pass
244 pass
244 else:
245 else:
245 return printer(obj)
246 return printer(obj)
246 # Next look for type_printers.
247 # Next look for type_printers.
247 for cls in pretty._get_mro(obj_class):
248 for cls in pretty._get_mro(obj_class):
248 if cls in self.type_printers:
249 if cls in self.type_printers:
249 return self.type_printers[cls](obj)
250 return self.type_printers[cls](obj)
250 else:
251 else:
251 printer = self._in_deferred_types(cls)
252 printer = self._in_deferred_types(cls)
252 if printer is not None:
253 if printer is not None:
253 return printer(obj)
254 return printer(obj)
254 # Finally look for special method names.
255 # Finally look for special method names.
255 if hasattr(obj_class, self.print_method):
256 if hasattr(obj_class, self.print_method):
256 printer = getattr(obj_class, self.print_method)
257 printer = getattr(obj_class, self.print_method)
257 return printer(obj)
258 return printer(obj)
258 return None
259 return None
259 except Exception:
260 except Exception:
260 pass
261 pass
261 else:
262 else:
262 return None
263 return None
263
264
264 def for_type(self, typ, func):
265 def for_type(self, typ, func):
265 """Add a format function for a given type.
266 """Add a format function for a given type.
266
267
267 Parameters
268 Parameters
268 -----------
269 -----------
269 typ : class
270 typ : class
270 The class of the object that will be formatted using `func`.
271 The class of the object that will be formatted using `func`.
271 func : callable
272 func : callable
272 The callable that will be called to compute the format data. The
273 The callable that will be called to compute the format data. The
273 call signature of this function is simple, it must take the
274 call signature of this function is simple, it must take the
274 object to be formatted and return the raw data for the given
275 object to be formatted and return the raw data for the given
275 format. Subclasses may use a different call signature for the
276 format. Subclasses may use a different call signature for the
276 `func` argument.
277 `func` argument.
277 """
278 """
278 oldfunc = self.type_printers.get(typ, None)
279 oldfunc = self.type_printers.get(typ, None)
279 if func is not None:
280 if func is not None:
280 # To support easy restoration of old printers, we need to ignore
281 # To support easy restoration of old printers, we need to ignore
281 # Nones.
282 # Nones.
282 self.type_printers[typ] = func
283 self.type_printers[typ] = func
283 return oldfunc
284 return oldfunc
284
285
285 def for_type_by_name(self, type_module, type_name, func):
286 def for_type_by_name(self, type_module, type_name, func):
286 """Add a format function for a type specified by the full dotted
287 """Add a format function for a type specified by the full dotted
287 module and name of the type, rather than the type of the object.
288 module and name of the type, rather than the type of the object.
288
289
289 Parameters
290 Parameters
290 ----------
291 ----------
291 type_module : str
292 type_module : str
292 The full dotted name of the module the type is defined in, like
293 The full dotted name of the module the type is defined in, like
293 ``numpy``.
294 ``numpy``.
294 type_name : str
295 type_name : str
295 The name of the type (the class name), like ``dtype``
296 The name of the type (the class name), like ``dtype``
296 func : callable
297 func : callable
297 The callable that will be called to compute the format data. The
298 The callable that will be called to compute the format data. The
298 call signature of this function is simple, it must take the
299 call signature of this function is simple, it must take the
299 object to be formatted and return the raw data for the given
300 object to be formatted and return the raw data for the given
300 format. Subclasses may use a different call signature for the
301 format. Subclasses may use a different call signature for the
301 `func` argument.
302 `func` argument.
302 """
303 """
303 key = (type_module, type_name)
304 key = (type_module, type_name)
304 oldfunc = self.deferred_printers.get(key, None)
305 oldfunc = self.deferred_printers.get(key, None)
305 if func is not None:
306 if func is not None:
306 # To support easy restoration of old printers, we need to ignore
307 # To support easy restoration of old printers, we need to ignore
307 # Nones.
308 # Nones.
308 self.deferred_printers[key] = func
309 self.deferred_printers[key] = func
309 return oldfunc
310 return oldfunc
310
311
311 def _in_deferred_types(self, cls):
312 def _in_deferred_types(self, cls):
312 """
313 """
313 Check if the given class is specified in the deferred type registry.
314 Check if the given class is specified in the deferred type registry.
314
315
315 Returns the printer from the registry if it exists, and None if the
316 Returns the printer from the registry if it exists, and None if the
316 class is not in the registry. Successful matches will be moved to the
317 class is not in the registry. Successful matches will be moved to the
317 regular type registry for future use.
318 regular type registry for future use.
318 """
319 """
319 mod = getattr(cls, '__module__', None)
320 mod = getattr(cls, '__module__', None)
320 name = getattr(cls, '__name__', None)
321 name = getattr(cls, '__name__', None)
321 key = (mod, name)
322 key = (mod, name)
322 printer = None
323 printer = None
323 if key in self.deferred_printers:
324 if key in self.deferred_printers:
324 # Move the printer over to the regular registry.
325 # Move the printer over to the regular registry.
325 printer = self.deferred_printers.pop(key)
326 printer = self.deferred_printers.pop(key)
326 self.type_printers[cls] = printer
327 self.type_printers[cls] = printer
327 return printer
328 return printer
328
329
329
330
330 class PlainTextFormatter(BaseFormatter):
331 class PlainTextFormatter(BaseFormatter):
331 """The default pretty-printer.
332 """The default pretty-printer.
332
333
333 This uses :mod:`IPython.lib.pretty` to compute the format data of
334 This uses :mod:`IPython.lib.pretty` to compute the format data of
334 the object. If the object cannot be pretty printed, :func:`repr` is used.
335 the object. If the object cannot be pretty printed, :func:`repr` is used.
335 See the documentation of :mod:`IPython.lib.pretty` for details on
336 See the documentation of :mod:`IPython.lib.pretty` for details on
336 how to write pretty printers. Here is a simple example::
337 how to write pretty printers. Here is a simple example::
337
338
338 def dtype_pprinter(obj, p, cycle):
339 def dtype_pprinter(obj, p, cycle):
339 if cycle:
340 if cycle:
340 return p.text('dtype(...)')
341 return p.text('dtype(...)')
341 if hasattr(obj, 'fields'):
342 if hasattr(obj, 'fields'):
342 if obj.fields is None:
343 if obj.fields is None:
343 p.text(repr(obj))
344 p.text(repr(obj))
344 else:
345 else:
345 p.begin_group(7, 'dtype([')
346 p.begin_group(7, 'dtype([')
346 for i, field in enumerate(obj.descr):
347 for i, field in enumerate(obj.descr):
347 if i > 0:
348 if i > 0:
348 p.text(',')
349 p.text(',')
349 p.breakable()
350 p.breakable()
350 p.pretty(field)
351 p.pretty(field)
351 p.end_group(7, '])')
352 p.end_group(7, '])')
352 """
353 """
353
354
354 # The format type of data returned.
355 # The format type of data returned.
355 format_type = Unicode('text/plain')
356 format_type = Unicode('text/plain')
356
357
357 # This subclass ignores this attribute as it always need to return
358 # This subclass ignores this attribute as it always need to return
358 # something.
359 # something.
359 enabled = Bool(True, config=False)
360 enabled = Bool(True, config=False)
360
361
361 # Look for a _repr_pretty_ methods to use for pretty printing.
362 # Look for a _repr_pretty_ methods to use for pretty printing.
362 print_method = ObjectName('_repr_pretty_')
363 print_method = ObjectName('_repr_pretty_')
363
364
364 # Whether to pretty-print or not.
365 # Whether to pretty-print or not.
365 pprint = Bool(True, config=True)
366 pprint = Bool(True, config=True)
366
367
367 # Whether to be verbose or not.
368 # Whether to be verbose or not.
368 verbose = Bool(False, config=True)
369 verbose = Bool(False, config=True)
369
370
370 # The maximum width.
371 # The maximum width.
371 max_width = Integer(79, config=True)
372 max_width = Integer(79, config=True)
372
373
373 # The newline character.
374 # The newline character.
374 newline = Unicode('\n', config=True)
375 newline = Unicode('\n', config=True)
375
376
376 # format-string for pprinting floats
377 # format-string for pprinting floats
377 float_format = Unicode('%r')
378 float_format = Unicode('%r')
378 # setter for float precision, either int or direct format-string
379 # setter for float precision, either int or direct format-string
379 float_precision = CUnicode('', config=True)
380 float_precision = CUnicode('', config=True)
380
381
381 def _float_precision_changed(self, name, old, new):
382 def _float_precision_changed(self, name, old, new):
382 """float_precision changed, set float_format accordingly.
383 """float_precision changed, set float_format accordingly.
383
384
384 float_precision can be set by int or str.
385 float_precision can be set by int or str.
385 This will set float_format, after interpreting input.
386 This will set float_format, after interpreting input.
386 If numpy has been imported, numpy print precision will also be set.
387 If numpy has been imported, numpy print precision will also be set.
387
388
388 integer `n` sets format to '%.nf', otherwise, format set directly.
389 integer `n` sets format to '%.nf', otherwise, format set directly.
389
390
390 An empty string returns to defaults (repr for float, 8 for numpy).
391 An empty string returns to defaults (repr for float, 8 for numpy).
391
392
392 This parameter can be set via the '%precision' magic.
393 This parameter can be set via the '%precision' magic.
393 """
394 """
394
395
395 if '%' in new:
396 if '%' in new:
396 # got explicit format string
397 # got explicit format string
397 fmt = new
398 fmt = new
398 try:
399 try:
399 fmt%3.14159
400 fmt%3.14159
400 except Exception:
401 except Exception:
401 raise ValueError("Precision must be int or format string, not %r"%new)
402 raise ValueError("Precision must be int or format string, not %r"%new)
402 elif new:
403 elif new:
403 # otherwise, should be an int
404 # otherwise, should be an int
404 try:
405 try:
405 i = int(new)
406 i = int(new)
406 assert i >= 0
407 assert i >= 0
407 except ValueError:
408 except ValueError:
408 raise ValueError("Precision must be int or format string, not %r"%new)
409 raise ValueError("Precision must be int or format string, not %r"%new)
409 except AssertionError:
410 except AssertionError:
410 raise ValueError("int precision must be non-negative, not %r"%i)
411 raise ValueError("int precision must be non-negative, not %r"%i)
411
412
412 fmt = '%%.%if'%i
413 fmt = '%%.%if'%i
413 if 'numpy' in sys.modules:
414 if 'numpy' in sys.modules:
414 # set numpy precision if it has been imported
415 # set numpy precision if it has been imported
415 import numpy
416 import numpy
416 numpy.set_printoptions(precision=i)
417 numpy.set_printoptions(precision=i)
417 else:
418 else:
418 # default back to repr
419 # default back to repr
419 fmt = '%r'
420 fmt = '%r'
420 if 'numpy' in sys.modules:
421 if 'numpy' in sys.modules:
421 import numpy
422 import numpy
422 # numpy default is 8
423 # numpy default is 8
423 numpy.set_printoptions(precision=8)
424 numpy.set_printoptions(precision=8)
424 self.float_format = fmt
425 self.float_format = fmt
425
426
426 # Use the default pretty printers from IPython.lib.pretty.
427 # Use the default pretty printers from IPython.lib.pretty.
427 def _singleton_printers_default(self):
428 def _singleton_printers_default(self):
428 return pretty._singleton_pprinters.copy()
429 return pretty._singleton_pprinters.copy()
429
430
430 def _type_printers_default(self):
431 def _type_printers_default(self):
431 d = pretty._type_pprinters.copy()
432 d = pretty._type_pprinters.copy()
432 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
433 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
433 return d
434 return d
434
435
435 def _deferred_printers_default(self):
436 def _deferred_printers_default(self):
436 return pretty._deferred_type_pprinters.copy()
437 return pretty._deferred_type_pprinters.copy()
437
438
438 #### FormatterABC interface ####
439 #### FormatterABC interface ####
439
440
440 def __call__(self, obj):
441 def __call__(self, obj):
441 """Compute the pretty representation of the object."""
442 """Compute the pretty representation of the object."""
442 if not self.pprint:
443 if not self.pprint:
443 try:
444 try:
444 return repr(obj)
445 return repr(obj)
445 except TypeError:
446 except TypeError:
446 return ''
447 return ''
447 else:
448 else:
448 # This uses use StringIO, as cStringIO doesn't handle unicode.
449 # This uses use StringIO, as cStringIO doesn't handle unicode.
449 stream = StringIO()
450 stream = StringIO()
450 # self.newline.encode() is a quick fix for issue gh-597. We need to
451 # self.newline.encode() is a quick fix for issue gh-597. We need to
451 # ensure that stream does not get a mix of unicode and bytestrings,
452 # ensure that stream does not get a mix of unicode and bytestrings,
452 # or it will cause trouble.
453 # or it will cause trouble.
453 printer = pretty.RepresentationPrinter(stream, self.verbose,
454 printer = pretty.RepresentationPrinter(stream, self.verbose,
454 self.max_width, unicode_to_str(self.newline),
455 self.max_width, unicode_to_str(self.newline),
455 singleton_pprinters=self.singleton_printers,
456 singleton_pprinters=self.singleton_printers,
456 type_pprinters=self.type_printers,
457 type_pprinters=self.type_printers,
457 deferred_pprinters=self.deferred_printers)
458 deferred_pprinters=self.deferred_printers)
458 printer.pretty(obj)
459 printer.pretty(obj)
459 printer.flush()
460 printer.flush()
460 return stream.getvalue()
461 return stream.getvalue()
461
462
462
463
463 class HTMLFormatter(BaseFormatter):
464 class HTMLFormatter(BaseFormatter):
464 """An HTML formatter.
465 """An HTML formatter.
465
466
466 To define the callables that compute the HTML representation of your
467 To define the callables that compute the HTML representation of your
467 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
468 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
468 or :meth:`for_type_by_name` methods to register functions that handle
469 or :meth:`for_type_by_name` methods to register functions that handle
469 this.
470 this.
470
471
471 The return value of this formatter should be a valid HTML snippet that
472 The return value of this formatter should be a valid HTML snippet that
472 could be injected into an existing DOM. It should *not* include the
473 could be injected into an existing DOM. It should *not* include the
473 ```<html>`` or ```<body>`` tags.
474 ```<html>`` or ```<body>`` tags.
474 """
475 """
475 format_type = Unicode('text/html')
476 format_type = Unicode('text/html')
476
477
477 print_method = ObjectName('_repr_html_')
478 print_method = ObjectName('_repr_html_')
478
479
479
480
480 class SVGFormatter(BaseFormatter):
481 class SVGFormatter(BaseFormatter):
481 """An SVG formatter.
482 """An SVG formatter.
482
483
483 To define the callables that compute the SVG representation of your
484 To define the callables that compute the SVG representation of your
484 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
485 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
485 or :meth:`for_type_by_name` methods to register functions that handle
486 or :meth:`for_type_by_name` methods to register functions that handle
486 this.
487 this.
487
488
488 The return value of this formatter should be valid SVG enclosed in
489 The return value of this formatter should be valid SVG enclosed in
489 ```<svg>``` tags, that could be injected into an existing DOM. It should
490 ```<svg>``` tags, that could be injected into an existing DOM. It should
490 *not* include the ```<html>`` or ```<body>`` tags.
491 *not* include the ```<html>`` or ```<body>`` tags.
491 """
492 """
492 format_type = Unicode('image/svg+xml')
493 format_type = Unicode('image/svg+xml')
493
494
494 print_method = ObjectName('_repr_svg_')
495 print_method = ObjectName('_repr_svg_')
495
496
496
497
497 class PNGFormatter(BaseFormatter):
498 class PNGFormatter(BaseFormatter):
498 """A PNG formatter.
499 """A PNG formatter.
499
500
500 To define the callables that compute the PNG representation of your
501 To define the callables that compute the PNG representation of your
501 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
502 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
502 or :meth:`for_type_by_name` methods to register functions that handle
503 or :meth:`for_type_by_name` methods to register functions that handle
503 this.
504 this.
504
505
505 The return value of this formatter should be raw PNG data, *not*
506 The return value of this formatter should be raw PNG data, *not*
506 base64 encoded.
507 base64 encoded.
507 """
508 """
508 format_type = Unicode('image/png')
509 format_type = Unicode('image/png')
509
510
510 print_method = ObjectName('_repr_png_')
511 print_method = ObjectName('_repr_png_')
511
512
512
513
513 class JPEGFormatter(BaseFormatter):
514 class JPEGFormatter(BaseFormatter):
514 """A JPEG formatter.
515 """A JPEG formatter.
515
516
516 To define the callables that compute the JPEG representation of your
517 To define the callables that compute the JPEG representation of your
517 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
518 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
518 or :meth:`for_type_by_name` methods to register functions that handle
519 or :meth:`for_type_by_name` methods to register functions that handle
519 this.
520 this.
520
521
521 The return value of this formatter should be raw JPEG data, *not*
522 The return value of this formatter should be raw JPEG data, *not*
522 base64 encoded.
523 base64 encoded.
523 """
524 """
524 format_type = Unicode('image/jpeg')
525 format_type = Unicode('image/jpeg')
525
526
526 print_method = ObjectName('_repr_jpeg_')
527 print_method = ObjectName('_repr_jpeg_')
527
528
528
529
529 class LatexFormatter(BaseFormatter):
530 class LatexFormatter(BaseFormatter):
530 """A LaTeX formatter.
531 """A LaTeX formatter.
531
532
532 To define the callables that compute the LaTeX representation of your
533 To define the callables that compute the LaTeX representation of your
533 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
534 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
534 or :meth:`for_type_by_name` methods to register functions that handle
535 or :meth:`for_type_by_name` methods to register functions that handle
535 this.
536 this.
536
537
537 The return value of this formatter should be a valid LaTeX equation,
538 The return value of this formatter should be a valid LaTeX equation,
538 enclosed in either ```$```, ```$$``` or another LaTeX equation
539 enclosed in either ```$```, ```$$``` or another LaTeX equation
539 environment.
540 environment.
540 """
541 """
541 format_type = Unicode('text/latex')
542 format_type = Unicode('text/latex')
542
543
543 print_method = ObjectName('_repr_latex_')
544 print_method = ObjectName('_repr_latex_')
544
545
545
546
546 class JSONFormatter(BaseFormatter):
547 class JSONFormatter(BaseFormatter):
547 """A JSON string formatter.
548 """A JSON string formatter.
548
549
549 To define the callables that compute the JSON string representation of
550 To define the callables that compute the JSON string representation of
550 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
551 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
551 or :meth:`for_type_by_name` methods to register functions that handle
552 or :meth:`for_type_by_name` methods to register functions that handle
552 this.
553 this.
553
554
554 The return value of this formatter should be a valid JSON string.
555 The return value of this formatter should be a valid JSON string.
555 """
556 """
556 format_type = Unicode('application/json')
557 format_type = Unicode('application/json')
557
558
558 print_method = ObjectName('_repr_json_')
559 print_method = ObjectName('_repr_json_')
559
560
560
561
561 class JavascriptFormatter(BaseFormatter):
562 class JavascriptFormatter(BaseFormatter):
562 """A Javascript formatter.
563 """A Javascript formatter.
563
564
564 To define the callables that compute the Javascript representation of
565 To define the callables that compute the Javascript representation of
565 your objects, define a :meth:`_repr_javascript_` method or use the
566 your objects, define a :meth:`_repr_javascript_` method or use the
566 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
567 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
567 that handle this.
568 that handle this.
568
569
569 The return value of this formatter should be valid Javascript code and
570 The return value of this formatter should be valid Javascript code and
570 should *not* be enclosed in ```<script>``` tags.
571 should *not* be enclosed in ```<script>``` tags.
571 """
572 """
572 format_type = Unicode('application/javascript')
573 format_type = Unicode('application/javascript')
573
574
574 print_method = ObjectName('_repr_javascript_')
575 print_method = ObjectName('_repr_javascript_')
575
576
576 FormatterABC.register(BaseFormatter)
577 FormatterABC.register(BaseFormatter)
577 FormatterABC.register(PlainTextFormatter)
578 FormatterABC.register(PlainTextFormatter)
578 FormatterABC.register(HTMLFormatter)
579 FormatterABC.register(HTMLFormatter)
579 FormatterABC.register(SVGFormatter)
580 FormatterABC.register(SVGFormatter)
580 FormatterABC.register(PNGFormatter)
581 FormatterABC.register(PNGFormatter)
581 FormatterABC.register(JPEGFormatter)
582 FormatterABC.register(JPEGFormatter)
582 FormatterABC.register(LatexFormatter)
583 FormatterABC.register(LatexFormatter)
583 FormatterABC.register(JSONFormatter)
584 FormatterABC.register(JSONFormatter)
584 FormatterABC.register(JavascriptFormatter)
585 FormatterABC.register(JavascriptFormatter)
585
586
586
587
587 def format_display_data(obj, include=None, exclude=None):
588 def format_display_data(obj, include=None, exclude=None):
588 """Return a format data dict for an object.
589 """Return a format data dict for an object.
589
590
590 By default all format types will be computed.
591 By default all format types will be computed.
591
592
592 The following MIME types are currently implemented:
593 The following MIME types are currently implemented:
593
594
594 * text/plain
595 * text/plain
595 * text/html
596 * text/html
596 * text/latex
597 * text/latex
597 * application/json
598 * application/json
598 * application/javascript
599 * application/javascript
599 * image/png
600 * image/png
600 * image/jpeg
601 * image/jpeg
601 * image/svg+xml
602 * image/svg+xml
602
603
603 Parameters
604 Parameters
604 ----------
605 ----------
605 obj : object
606 obj : object
606 The Python object whose format data will be computed.
607 The Python object whose format data will be computed.
607
608
608 Returns
609 Returns
609 -------
610 -------
610 format_dict : dict
611 format_dict : dict
611 A dictionary of key/value pairs, one or each format that was
612 A dictionary of key/value pairs, one or each format that was
612 generated for the object. The keys are the format types, which
613 generated for the object. The keys are the format types, which
613 will usually be MIME type strings and the values and JSON'able
614 will usually be MIME type strings and the values and JSON'able
614 data structure containing the raw data for the representation in
615 data structure containing the raw data for the representation in
615 that format.
616 that format.
616 include : list or tuple, optional
617 include : list or tuple, optional
617 A list of format type strings (MIME types) to include in the
618 A list of format type strings (MIME types) to include in the
618 format data dict. If this is set *only* the format types included
619 format data dict. If this is set *only* the format types included
619 in this list will be computed.
620 in this list will be computed.
620 exclude : list or tuple, optional
621 exclude : list or tuple, optional
621 A list of format type string (MIME types) to exclue in the format
622 A list of format type string (MIME types) to exclue in the format
622 data dict. If this is set all format types will be computed,
623 data dict. If this is set all format types will be computed,
623 except for those included in this argument.
624 except for those included in this argument.
624 """
625 """
625 from IPython.core.interactiveshell import InteractiveShell
626 from IPython.core.interactiveshell import InteractiveShell
626
627
627 InteractiveShell.instance().display_formatter.format(
628 InteractiveShell.instance().display_formatter.format(
628 obj,
629 obj,
629 include,
630 include,
630 exclude
631 exclude
631 )
632 )
632
633
General Comments 0
You need to be logged in to leave comments. Login now