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