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