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