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