Show More
@@ -1,778 +1,779 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Top-level display functions for displaying object in different formats. |
|
2 | """Top-level display functions for displaying object in different formats. | |
3 |
|
3 | |||
4 | Authors: |
|
4 | Authors: | |
5 |
|
5 | |||
6 | * Brian Granger |
|
6 | * Brian Granger | |
7 | """ |
|
7 | """ | |
8 |
|
8 | |||
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 | # Copyright (C) 2013 The IPython Development Team |
|
10 | # Copyright (C) 2013 The IPython Development Team | |
11 | # |
|
11 | # | |
12 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | # Distributed under the terms of the BSD License. The full license is in | |
13 | # the file COPYING, distributed as part of this software. |
|
13 | # the file COPYING, distributed as part of this software. | |
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 |
|
15 | |||
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 | # Imports |
|
17 | # Imports | |
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 |
|
19 | |||
20 | from __future__ import print_function |
|
20 | from __future__ import print_function | |
21 |
|
21 | |||
22 | import os |
|
22 | import os | |
23 | import struct |
|
23 | import struct | |
24 |
|
24 | |||
|
25 | from IPython.core.formatters import _safe_get_formatter_method | |||
25 | from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode, |
|
26 | from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode, | |
26 | unicode_type) |
|
27 | unicode_type) | |
27 | from IPython.testing.skipdoctest import skip_doctest |
|
28 | from IPython.testing.skipdoctest import skip_doctest | |
28 | from .displaypub import publish_display_data |
|
29 | from .displaypub import publish_display_data | |
29 |
|
30 | |||
30 | #----------------------------------------------------------------------------- |
|
31 | #----------------------------------------------------------------------------- | |
31 | # utility functions |
|
32 | # utility functions | |
32 | #----------------------------------------------------------------------------- |
|
33 | #----------------------------------------------------------------------------- | |
33 |
|
34 | |||
34 | def _safe_exists(path): |
|
35 | def _safe_exists(path): | |
35 | """Check path, but don't let exceptions raise""" |
|
36 | """Check path, but don't let exceptions raise""" | |
36 | try: |
|
37 | try: | |
37 | return os.path.exists(path) |
|
38 | return os.path.exists(path) | |
38 | except Exception: |
|
39 | except Exception: | |
39 | return False |
|
40 | return False | |
40 |
|
41 | |||
41 | def _merge(d1, d2): |
|
42 | def _merge(d1, d2): | |
42 | """Like update, but merges sub-dicts instead of clobbering at the top level. |
|
43 | """Like update, but merges sub-dicts instead of clobbering at the top level. | |
43 |
|
44 | |||
44 | Updates d1 in-place |
|
45 | Updates d1 in-place | |
45 | """ |
|
46 | """ | |
46 |
|
47 | |||
47 | if not isinstance(d2, dict) or not isinstance(d1, dict): |
|
48 | if not isinstance(d2, dict) or not isinstance(d1, dict): | |
48 | return d2 |
|
49 | return d2 | |
49 | for key, value in d2.items(): |
|
50 | for key, value in d2.items(): | |
50 | d1[key] = _merge(d1.get(key), value) |
|
51 | d1[key] = _merge(d1.get(key), value) | |
51 | return d1 |
|
52 | return d1 | |
52 |
|
53 | |||
53 | def _display_mimetype(mimetype, objs, raw=False, metadata=None): |
|
54 | def _display_mimetype(mimetype, objs, raw=False, metadata=None): | |
54 | """internal implementation of all display_foo methods |
|
55 | """internal implementation of all display_foo methods | |
55 |
|
56 | |||
56 | Parameters |
|
57 | Parameters | |
57 | ---------- |
|
58 | ---------- | |
58 | mimetype : str |
|
59 | mimetype : str | |
59 | The mimetype to be published (e.g. 'image/png') |
|
60 | The mimetype to be published (e.g. 'image/png') | |
60 | objs : tuple of objects |
|
61 | objs : tuple of objects | |
61 | The Python objects to display, or if raw=True raw text data to |
|
62 | The Python objects to display, or if raw=True raw text data to | |
62 | display. |
|
63 | display. | |
63 | raw : bool |
|
64 | raw : bool | |
64 | Are the data objects raw data or Python objects that need to be |
|
65 | Are the data objects raw data or Python objects that need to be | |
65 | formatted before display? [default: False] |
|
66 | formatted before display? [default: False] | |
66 | metadata : dict (optional) |
|
67 | metadata : dict (optional) | |
67 | Metadata to be associated with the specific mimetype output. |
|
68 | Metadata to be associated with the specific mimetype output. | |
68 | """ |
|
69 | """ | |
69 | if metadata: |
|
70 | if metadata: | |
70 | metadata = {mimetype: metadata} |
|
71 | metadata = {mimetype: metadata} | |
71 | if raw: |
|
72 | if raw: | |
72 | # turn list of pngdata into list of { 'image/png': pngdata } |
|
73 | # turn list of pngdata into list of { 'image/png': pngdata } | |
73 | objs = [ {mimetype: obj} for obj in objs ] |
|
74 | objs = [ {mimetype: obj} for obj in objs ] | |
74 | display(*objs, raw=raw, metadata=metadata, include=[mimetype]) |
|
75 | display(*objs, raw=raw, metadata=metadata, include=[mimetype]) | |
75 |
|
76 | |||
76 | #----------------------------------------------------------------------------- |
|
77 | #----------------------------------------------------------------------------- | |
77 | # Main functions |
|
78 | # Main functions | |
78 | #----------------------------------------------------------------------------- |
|
79 | #----------------------------------------------------------------------------- | |
79 |
|
80 | |||
80 | def display(*objs, **kwargs): |
|
81 | def display(*objs, **kwargs): | |
81 | """Display a Python object in all frontends. |
|
82 | """Display a Python object in all frontends. | |
82 |
|
83 | |||
83 | By default all representations will be computed and sent to the frontends. |
|
84 | By default all representations will be computed and sent to the frontends. | |
84 | Frontends can decide which representation is used and how. |
|
85 | Frontends can decide which representation is used and how. | |
85 |
|
86 | |||
86 | Parameters |
|
87 | Parameters | |
87 | ---------- |
|
88 | ---------- | |
88 | objs : tuple of objects |
|
89 | objs : tuple of objects | |
89 | The Python objects to display. |
|
90 | The Python objects to display. | |
90 | raw : bool, optional |
|
91 | raw : bool, optional | |
91 | Are the objects to be displayed already mimetype-keyed dicts of raw display data, |
|
92 | Are the objects to be displayed already mimetype-keyed dicts of raw display data, | |
92 | or Python objects that need to be formatted before display? [default: False] |
|
93 | or Python objects that need to be formatted before display? [default: False] | |
93 | include : list or tuple, optional |
|
94 | include : list or tuple, optional | |
94 | A list of format type strings (MIME types) to include in the |
|
95 | A list of format type strings (MIME types) to include in the | |
95 | format data dict. If this is set *only* the format types included |
|
96 | format data dict. If this is set *only* the format types included | |
96 | in this list will be computed. |
|
97 | in this list will be computed. | |
97 | exclude : list or tuple, optional |
|
98 | exclude : list or tuple, optional | |
98 | A list of format type strings (MIME types) to exclude in the format |
|
99 | A list of format type strings (MIME types) to exclude in the format | |
99 | data dict. If this is set all format types will be computed, |
|
100 | data dict. If this is set all format types will be computed, | |
100 | except for those included in this argument. |
|
101 | except for those included in this argument. | |
101 | metadata : dict, optional |
|
102 | metadata : dict, optional | |
102 | A dictionary of metadata to associate with the output. |
|
103 | A dictionary of metadata to associate with the output. | |
103 | mime-type keys in this dictionary will be associated with the individual |
|
104 | mime-type keys in this dictionary will be associated with the individual | |
104 | representation formats, if they exist. |
|
105 | representation formats, if they exist. | |
105 | """ |
|
106 | """ | |
106 | raw = kwargs.get('raw', False) |
|
107 | raw = kwargs.get('raw', False) | |
107 | include = kwargs.get('include') |
|
108 | include = kwargs.get('include') | |
108 | exclude = kwargs.get('exclude') |
|
109 | exclude = kwargs.get('exclude') | |
109 | metadata = kwargs.get('metadata') |
|
110 | metadata = kwargs.get('metadata') | |
110 |
|
111 | |||
111 | from IPython.core.interactiveshell import InteractiveShell |
|
112 | from IPython.core.interactiveshell import InteractiveShell | |
112 |
|
113 | |||
113 | if not raw: |
|
114 | if not raw: | |
114 | format = InteractiveShell.instance().display_formatter.format |
|
115 | format = InteractiveShell.instance().display_formatter.format | |
115 |
|
116 | |||
116 | for obj in objs: |
|
117 | for obj in objs: | |
117 |
|
118 | |||
118 | # If _ipython_display_ is defined, use that to display this object. |
|
119 | # If _ipython_display_ is defined, use that to display this object. | |
119 |
display_method = getattr(obj, '_ipython_display_' |
|
120 | display_method = _safe_get_formatter_method(obj, '_ipython_display_') | |
120 | if display_method is not None: |
|
121 | if display_method is not None: | |
121 | try: |
|
122 | try: | |
122 | display_method(**kwargs) |
|
123 | display_method(**kwargs) | |
123 | except NotImplementedError: |
|
124 | except NotImplementedError: | |
124 | pass |
|
125 | pass | |
125 | else: |
|
126 | else: | |
126 | continue |
|
127 | continue | |
127 | if raw: |
|
128 | if raw: | |
128 | publish_display_data('display', obj, metadata) |
|
129 | publish_display_data('display', obj, metadata) | |
129 | else: |
|
130 | else: | |
130 | format_dict, md_dict = format(obj, include=include, exclude=exclude) |
|
131 | format_dict, md_dict = format(obj, include=include, exclude=exclude) | |
131 | if metadata: |
|
132 | if metadata: | |
132 | # kwarg-specified metadata gets precedence |
|
133 | # kwarg-specified metadata gets precedence | |
133 | _merge(md_dict, metadata) |
|
134 | _merge(md_dict, metadata) | |
134 | publish_display_data('display', format_dict, md_dict) |
|
135 | publish_display_data('display', format_dict, md_dict) | |
135 |
|
136 | |||
136 |
|
137 | |||
137 | def display_pretty(*objs, **kwargs): |
|
138 | def display_pretty(*objs, **kwargs): | |
138 | """Display the pretty (default) representation of an object. |
|
139 | """Display the pretty (default) representation of an object. | |
139 |
|
140 | |||
140 | Parameters |
|
141 | Parameters | |
141 | ---------- |
|
142 | ---------- | |
142 | objs : tuple of objects |
|
143 | objs : tuple of objects | |
143 | The Python objects to display, or if raw=True raw text data to |
|
144 | The Python objects to display, or if raw=True raw text data to | |
144 | display. |
|
145 | display. | |
145 | raw : bool |
|
146 | raw : bool | |
146 | Are the data objects raw data or Python objects that need to be |
|
147 | Are the data objects raw data or Python objects that need to be | |
147 | formatted before display? [default: False] |
|
148 | formatted before display? [default: False] | |
148 | metadata : dict (optional) |
|
149 | metadata : dict (optional) | |
149 | Metadata to be associated with the specific mimetype output. |
|
150 | Metadata to be associated with the specific mimetype output. | |
150 | """ |
|
151 | """ | |
151 | _display_mimetype('text/plain', objs, **kwargs) |
|
152 | _display_mimetype('text/plain', objs, **kwargs) | |
152 |
|
153 | |||
153 |
|
154 | |||
154 | def display_html(*objs, **kwargs): |
|
155 | def display_html(*objs, **kwargs): | |
155 | """Display the HTML representation of an object. |
|
156 | """Display the HTML representation of an object. | |
156 |
|
157 | |||
157 | Parameters |
|
158 | Parameters | |
158 | ---------- |
|
159 | ---------- | |
159 | objs : tuple of objects |
|
160 | objs : tuple of objects | |
160 | The Python objects to display, or if raw=True raw HTML data to |
|
161 | The Python objects to display, or if raw=True raw HTML data to | |
161 | display. |
|
162 | display. | |
162 | raw : bool |
|
163 | raw : bool | |
163 | Are the data objects raw data or Python objects that need to be |
|
164 | Are the data objects raw data or Python objects that need to be | |
164 | formatted before display? [default: False] |
|
165 | formatted before display? [default: False] | |
165 | metadata : dict (optional) |
|
166 | metadata : dict (optional) | |
166 | Metadata to be associated with the specific mimetype output. |
|
167 | Metadata to be associated with the specific mimetype output. | |
167 | """ |
|
168 | """ | |
168 | _display_mimetype('text/html', objs, **kwargs) |
|
169 | _display_mimetype('text/html', objs, **kwargs) | |
169 |
|
170 | |||
170 |
|
171 | |||
171 | def display_svg(*objs, **kwargs): |
|
172 | def display_svg(*objs, **kwargs): | |
172 | """Display the SVG representation of an object. |
|
173 | """Display the SVG representation of an object. | |
173 |
|
174 | |||
174 | Parameters |
|
175 | Parameters | |
175 | ---------- |
|
176 | ---------- | |
176 | objs : tuple of objects |
|
177 | objs : tuple of objects | |
177 | The Python objects to display, or if raw=True raw svg data to |
|
178 | The Python objects to display, or if raw=True raw svg data to | |
178 | display. |
|
179 | display. | |
179 | raw : bool |
|
180 | raw : bool | |
180 | Are the data objects raw data or Python objects that need to be |
|
181 | Are the data objects raw data or Python objects that need to be | |
181 | formatted before display? [default: False] |
|
182 | formatted before display? [default: False] | |
182 | metadata : dict (optional) |
|
183 | metadata : dict (optional) | |
183 | Metadata to be associated with the specific mimetype output. |
|
184 | Metadata to be associated with the specific mimetype output. | |
184 | """ |
|
185 | """ | |
185 | _display_mimetype('image/svg+xml', objs, **kwargs) |
|
186 | _display_mimetype('image/svg+xml', objs, **kwargs) | |
186 |
|
187 | |||
187 |
|
188 | |||
188 | def display_png(*objs, **kwargs): |
|
189 | def display_png(*objs, **kwargs): | |
189 | """Display the PNG representation of an object. |
|
190 | """Display the PNG representation of an object. | |
190 |
|
191 | |||
191 | Parameters |
|
192 | Parameters | |
192 | ---------- |
|
193 | ---------- | |
193 | objs : tuple of objects |
|
194 | objs : tuple of objects | |
194 | The Python objects to display, or if raw=True raw png data to |
|
195 | The Python objects to display, or if raw=True raw png data to | |
195 | display. |
|
196 | display. | |
196 | raw : bool |
|
197 | raw : bool | |
197 | Are the data objects raw data or Python objects that need to be |
|
198 | Are the data objects raw data or Python objects that need to be | |
198 | formatted before display? [default: False] |
|
199 | formatted before display? [default: False] | |
199 | metadata : dict (optional) |
|
200 | metadata : dict (optional) | |
200 | Metadata to be associated with the specific mimetype output. |
|
201 | Metadata to be associated with the specific mimetype output. | |
201 | """ |
|
202 | """ | |
202 | _display_mimetype('image/png', objs, **kwargs) |
|
203 | _display_mimetype('image/png', objs, **kwargs) | |
203 |
|
204 | |||
204 |
|
205 | |||
205 | def display_jpeg(*objs, **kwargs): |
|
206 | def display_jpeg(*objs, **kwargs): | |
206 | """Display the JPEG representation of an object. |
|
207 | """Display the JPEG representation of an object. | |
207 |
|
208 | |||
208 | Parameters |
|
209 | Parameters | |
209 | ---------- |
|
210 | ---------- | |
210 | objs : tuple of objects |
|
211 | objs : tuple of objects | |
211 | The Python objects to display, or if raw=True raw JPEG data to |
|
212 | The Python objects to display, or if raw=True raw JPEG data to | |
212 | display. |
|
213 | display. | |
213 | raw : bool |
|
214 | raw : bool | |
214 | Are the data objects raw data or Python objects that need to be |
|
215 | Are the data objects raw data or Python objects that need to be | |
215 | formatted before display? [default: False] |
|
216 | formatted before display? [default: False] | |
216 | metadata : dict (optional) |
|
217 | metadata : dict (optional) | |
217 | Metadata to be associated with the specific mimetype output. |
|
218 | Metadata to be associated with the specific mimetype output. | |
218 | """ |
|
219 | """ | |
219 | _display_mimetype('image/jpeg', objs, **kwargs) |
|
220 | _display_mimetype('image/jpeg', objs, **kwargs) | |
220 |
|
221 | |||
221 |
|
222 | |||
222 | def display_latex(*objs, **kwargs): |
|
223 | def display_latex(*objs, **kwargs): | |
223 | """Display the LaTeX representation of an object. |
|
224 | """Display the LaTeX representation of an object. | |
224 |
|
225 | |||
225 | Parameters |
|
226 | Parameters | |
226 | ---------- |
|
227 | ---------- | |
227 | objs : tuple of objects |
|
228 | objs : tuple of objects | |
228 | The Python objects to display, or if raw=True raw latex data to |
|
229 | The Python objects to display, or if raw=True raw latex data to | |
229 | display. |
|
230 | display. | |
230 | raw : bool |
|
231 | raw : bool | |
231 | Are the data objects raw data or Python objects that need to be |
|
232 | Are the data objects raw data or Python objects that need to be | |
232 | formatted before display? [default: False] |
|
233 | formatted before display? [default: False] | |
233 | metadata : dict (optional) |
|
234 | metadata : dict (optional) | |
234 | Metadata to be associated with the specific mimetype output. |
|
235 | Metadata to be associated with the specific mimetype output. | |
235 | """ |
|
236 | """ | |
236 | _display_mimetype('text/latex', objs, **kwargs) |
|
237 | _display_mimetype('text/latex', objs, **kwargs) | |
237 |
|
238 | |||
238 |
|
239 | |||
239 | def display_json(*objs, **kwargs): |
|
240 | def display_json(*objs, **kwargs): | |
240 | """Display the JSON representation of an object. |
|
241 | """Display the JSON representation of an object. | |
241 |
|
242 | |||
242 | Note that not many frontends support displaying JSON. |
|
243 | Note that not many frontends support displaying JSON. | |
243 |
|
244 | |||
244 | Parameters |
|
245 | Parameters | |
245 | ---------- |
|
246 | ---------- | |
246 | objs : tuple of objects |
|
247 | objs : tuple of objects | |
247 | The Python objects to display, or if raw=True raw json data to |
|
248 | The Python objects to display, or if raw=True raw json data to | |
248 | display. |
|
249 | display. | |
249 | raw : bool |
|
250 | raw : bool | |
250 | Are the data objects raw data or Python objects that need to be |
|
251 | Are the data objects raw data or Python objects that need to be | |
251 | formatted before display? [default: False] |
|
252 | formatted before display? [default: False] | |
252 | metadata : dict (optional) |
|
253 | metadata : dict (optional) | |
253 | Metadata to be associated with the specific mimetype output. |
|
254 | Metadata to be associated with the specific mimetype output. | |
254 | """ |
|
255 | """ | |
255 | _display_mimetype('application/json', objs, **kwargs) |
|
256 | _display_mimetype('application/json', objs, **kwargs) | |
256 |
|
257 | |||
257 |
|
258 | |||
258 | def display_javascript(*objs, **kwargs): |
|
259 | def display_javascript(*objs, **kwargs): | |
259 | """Display the Javascript representation of an object. |
|
260 | """Display the Javascript representation of an object. | |
260 |
|
261 | |||
261 | Parameters |
|
262 | Parameters | |
262 | ---------- |
|
263 | ---------- | |
263 | objs : tuple of objects |
|
264 | objs : tuple of objects | |
264 | The Python objects to display, or if raw=True raw javascript data to |
|
265 | The Python objects to display, or if raw=True raw javascript data to | |
265 | display. |
|
266 | display. | |
266 | raw : bool |
|
267 | raw : bool | |
267 | Are the data objects raw data or Python objects that need to be |
|
268 | Are the data objects raw data or Python objects that need to be | |
268 | formatted before display? [default: False] |
|
269 | formatted before display? [default: False] | |
269 | metadata : dict (optional) |
|
270 | metadata : dict (optional) | |
270 | Metadata to be associated with the specific mimetype output. |
|
271 | Metadata to be associated with the specific mimetype output. | |
271 | """ |
|
272 | """ | |
272 | _display_mimetype('application/javascript', objs, **kwargs) |
|
273 | _display_mimetype('application/javascript', objs, **kwargs) | |
273 |
|
274 | |||
274 |
|
275 | |||
275 | def display_pdf(*objs, **kwargs): |
|
276 | def display_pdf(*objs, **kwargs): | |
276 | """Display the PDF representation of an object. |
|
277 | """Display the PDF representation of an object. | |
277 |
|
278 | |||
278 | Parameters |
|
279 | Parameters | |
279 | ---------- |
|
280 | ---------- | |
280 | objs : tuple of objects |
|
281 | objs : tuple of objects | |
281 | The Python objects to display, or if raw=True raw javascript data to |
|
282 | The Python objects to display, or if raw=True raw javascript data to | |
282 | display. |
|
283 | display. | |
283 | raw : bool |
|
284 | raw : bool | |
284 | Are the data objects raw data or Python objects that need to be |
|
285 | Are the data objects raw data or Python objects that need to be | |
285 | formatted before display? [default: False] |
|
286 | formatted before display? [default: False] | |
286 | metadata : dict (optional) |
|
287 | metadata : dict (optional) | |
287 | Metadata to be associated with the specific mimetype output. |
|
288 | Metadata to be associated with the specific mimetype output. | |
288 | """ |
|
289 | """ | |
289 | _display_mimetype('application/pdf', objs, **kwargs) |
|
290 | _display_mimetype('application/pdf', objs, **kwargs) | |
290 |
|
291 | |||
291 |
|
292 | |||
292 | #----------------------------------------------------------------------------- |
|
293 | #----------------------------------------------------------------------------- | |
293 | # Smart classes |
|
294 | # Smart classes | |
294 | #----------------------------------------------------------------------------- |
|
295 | #----------------------------------------------------------------------------- | |
295 |
|
296 | |||
296 |
|
297 | |||
297 | class DisplayObject(object): |
|
298 | class DisplayObject(object): | |
298 | """An object that wraps data to be displayed.""" |
|
299 | """An object that wraps data to be displayed.""" | |
299 |
|
300 | |||
300 | _read_flags = 'r' |
|
301 | _read_flags = 'r' | |
301 |
|
302 | |||
302 | def __init__(self, data=None, url=None, filename=None): |
|
303 | def __init__(self, data=None, url=None, filename=None): | |
303 | """Create a display object given raw data. |
|
304 | """Create a display object given raw data. | |
304 |
|
305 | |||
305 | When this object is returned by an expression or passed to the |
|
306 | When this object is returned by an expression or passed to the | |
306 | display function, it will result in the data being displayed |
|
307 | display function, it will result in the data being displayed | |
307 | in the frontend. The MIME type of the data should match the |
|
308 | in the frontend. The MIME type of the data should match the | |
308 | subclasses used, so the Png subclass should be used for 'image/png' |
|
309 | subclasses used, so the Png subclass should be used for 'image/png' | |
309 | data. If the data is a URL, the data will first be downloaded |
|
310 | data. If the data is a URL, the data will first be downloaded | |
310 | and then displayed. If |
|
311 | and then displayed. If | |
311 |
|
312 | |||
312 | Parameters |
|
313 | Parameters | |
313 | ---------- |
|
314 | ---------- | |
314 | data : unicode, str or bytes |
|
315 | data : unicode, str or bytes | |
315 | The raw data or a URL or file to load the data from |
|
316 | The raw data or a URL or file to load the data from | |
316 | url : unicode |
|
317 | url : unicode | |
317 | A URL to download the data from. |
|
318 | A URL to download the data from. | |
318 | filename : unicode |
|
319 | filename : unicode | |
319 | Path to a local file to load the data from. |
|
320 | Path to a local file to load the data from. | |
320 | """ |
|
321 | """ | |
321 | if data is not None and isinstance(data, string_types): |
|
322 | if data is not None and isinstance(data, string_types): | |
322 | if data.startswith('http') and url is None: |
|
323 | if data.startswith('http') and url is None: | |
323 | url = data |
|
324 | url = data | |
324 | filename = None |
|
325 | filename = None | |
325 | data = None |
|
326 | data = None | |
326 | elif _safe_exists(data) and filename is None: |
|
327 | elif _safe_exists(data) and filename is None: | |
327 | url = None |
|
328 | url = None | |
328 | filename = data |
|
329 | filename = data | |
329 | data = None |
|
330 | data = None | |
330 |
|
331 | |||
331 | self.data = data |
|
332 | self.data = data | |
332 | self.url = url |
|
333 | self.url = url | |
333 | self.filename = None if filename is None else unicode_type(filename) |
|
334 | self.filename = None if filename is None else unicode_type(filename) | |
334 |
|
335 | |||
335 | self.reload() |
|
336 | self.reload() | |
336 | self._check_data() |
|
337 | self._check_data() | |
337 |
|
338 | |||
338 | def _check_data(self): |
|
339 | def _check_data(self): | |
339 | """Override in subclasses if there's something to check.""" |
|
340 | """Override in subclasses if there's something to check.""" | |
340 | pass |
|
341 | pass | |
341 |
|
342 | |||
342 | def reload(self): |
|
343 | def reload(self): | |
343 | """Reload the raw data from file or URL.""" |
|
344 | """Reload the raw data from file or URL.""" | |
344 | if self.filename is not None: |
|
345 | if self.filename is not None: | |
345 | with open(self.filename, self._read_flags) as f: |
|
346 | with open(self.filename, self._read_flags) as f: | |
346 | self.data = f.read() |
|
347 | self.data = f.read() | |
347 | elif self.url is not None: |
|
348 | elif self.url is not None: | |
348 | try: |
|
349 | try: | |
349 | try: |
|
350 | try: | |
350 | from urllib.request import urlopen # Py3 |
|
351 | from urllib.request import urlopen # Py3 | |
351 | except ImportError: |
|
352 | except ImportError: | |
352 | from urllib2 import urlopen |
|
353 | from urllib2 import urlopen | |
353 | response = urlopen(self.url) |
|
354 | response = urlopen(self.url) | |
354 | self.data = response.read() |
|
355 | self.data = response.read() | |
355 | # extract encoding from header, if there is one: |
|
356 | # extract encoding from header, if there is one: | |
356 | encoding = None |
|
357 | encoding = None | |
357 | for sub in response.headers['content-type'].split(';'): |
|
358 | for sub in response.headers['content-type'].split(';'): | |
358 | sub = sub.strip() |
|
359 | sub = sub.strip() | |
359 | if sub.startswith('charset'): |
|
360 | if sub.startswith('charset'): | |
360 | encoding = sub.split('=')[-1].strip() |
|
361 | encoding = sub.split('=')[-1].strip() | |
361 | break |
|
362 | break | |
362 | # decode data, if an encoding was specified |
|
363 | # decode data, if an encoding was specified | |
363 | if encoding: |
|
364 | if encoding: | |
364 | self.data = self.data.decode(encoding, 'replace') |
|
365 | self.data = self.data.decode(encoding, 'replace') | |
365 | except: |
|
366 | except: | |
366 | self.data = None |
|
367 | self.data = None | |
367 |
|
368 | |||
368 | class TextDisplayObject(DisplayObject): |
|
369 | class TextDisplayObject(DisplayObject): | |
369 | """Validate that display data is text""" |
|
370 | """Validate that display data is text""" | |
370 | def _check_data(self): |
|
371 | def _check_data(self): | |
371 | if self.data is not None and not isinstance(self.data, string_types): |
|
372 | if self.data is not None and not isinstance(self.data, string_types): | |
372 | raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data)) |
|
373 | raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data)) | |
373 |
|
374 | |||
374 | class Pretty(TextDisplayObject): |
|
375 | class Pretty(TextDisplayObject): | |
375 |
|
376 | |||
376 | def _repr_pretty_(self): |
|
377 | def _repr_pretty_(self): | |
377 | return self.data |
|
378 | return self.data | |
378 |
|
379 | |||
379 |
|
380 | |||
380 | class HTML(TextDisplayObject): |
|
381 | class HTML(TextDisplayObject): | |
381 |
|
382 | |||
382 | def _repr_html_(self): |
|
383 | def _repr_html_(self): | |
383 | return self.data |
|
384 | return self.data | |
384 |
|
385 | |||
385 | def __html__(self): |
|
386 | def __html__(self): | |
386 | """ |
|
387 | """ | |
387 | This method exists to inform other HTML-using modules (e.g. Markupsafe, |
|
388 | This method exists to inform other HTML-using modules (e.g. Markupsafe, | |
388 | htmltag, etc) that this object is HTML and does not need things like |
|
389 | htmltag, etc) that this object is HTML and does not need things like | |
389 | special characters (<>&) escaped. |
|
390 | special characters (<>&) escaped. | |
390 | """ |
|
391 | """ | |
391 | return self._repr_html_() |
|
392 | return self._repr_html_() | |
392 |
|
393 | |||
393 |
|
394 | |||
394 | class Math(TextDisplayObject): |
|
395 | class Math(TextDisplayObject): | |
395 |
|
396 | |||
396 | def _repr_latex_(self): |
|
397 | def _repr_latex_(self): | |
397 | s = self.data.strip('$') |
|
398 | s = self.data.strip('$') | |
398 | return "$$%s$$" % s |
|
399 | return "$$%s$$" % s | |
399 |
|
400 | |||
400 |
|
401 | |||
401 | class Latex(TextDisplayObject): |
|
402 | class Latex(TextDisplayObject): | |
402 |
|
403 | |||
403 | def _repr_latex_(self): |
|
404 | def _repr_latex_(self): | |
404 | return self.data |
|
405 | return self.data | |
405 |
|
406 | |||
406 |
|
407 | |||
407 | class SVG(DisplayObject): |
|
408 | class SVG(DisplayObject): | |
408 |
|
409 | |||
409 | # wrap data in a property, which extracts the <svg> tag, discarding |
|
410 | # wrap data in a property, which extracts the <svg> tag, discarding | |
410 | # document headers |
|
411 | # document headers | |
411 | _data = None |
|
412 | _data = None | |
412 |
|
413 | |||
413 | @property |
|
414 | @property | |
414 | def data(self): |
|
415 | def data(self): | |
415 | return self._data |
|
416 | return self._data | |
416 |
|
417 | |||
417 | @data.setter |
|
418 | @data.setter | |
418 | def data(self, svg): |
|
419 | def data(self, svg): | |
419 | if svg is None: |
|
420 | if svg is None: | |
420 | self._data = None |
|
421 | self._data = None | |
421 | return |
|
422 | return | |
422 | # parse into dom object |
|
423 | # parse into dom object | |
423 | from xml.dom import minidom |
|
424 | from xml.dom import minidom | |
424 | svg = cast_bytes_py2(svg) |
|
425 | svg = cast_bytes_py2(svg) | |
425 | x = minidom.parseString(svg) |
|
426 | x = minidom.parseString(svg) | |
426 | # get svg tag (should be 1) |
|
427 | # get svg tag (should be 1) | |
427 | found_svg = x.getElementsByTagName('svg') |
|
428 | found_svg = x.getElementsByTagName('svg') | |
428 | if found_svg: |
|
429 | if found_svg: | |
429 | svg = found_svg[0].toxml() |
|
430 | svg = found_svg[0].toxml() | |
430 | else: |
|
431 | else: | |
431 | # fallback on the input, trust the user |
|
432 | # fallback on the input, trust the user | |
432 | # but this is probably an error. |
|
433 | # but this is probably an error. | |
433 | pass |
|
434 | pass | |
434 | svg = cast_unicode(svg) |
|
435 | svg = cast_unicode(svg) | |
435 | self._data = svg |
|
436 | self._data = svg | |
436 |
|
437 | |||
437 | def _repr_svg_(self): |
|
438 | def _repr_svg_(self): | |
438 | return self.data |
|
439 | return self.data | |
439 |
|
440 | |||
440 |
|
441 | |||
441 | class JSON(TextDisplayObject): |
|
442 | class JSON(TextDisplayObject): | |
442 |
|
443 | |||
443 | def _repr_json_(self): |
|
444 | def _repr_json_(self): | |
444 | return self.data |
|
445 | return self.data | |
445 |
|
446 | |||
446 | css_t = """$("head").append($("<link/>").attr({ |
|
447 | css_t = """$("head").append($("<link/>").attr({ | |
447 | rel: "stylesheet", |
|
448 | rel: "stylesheet", | |
448 | type: "text/css", |
|
449 | type: "text/css", | |
449 | href: "%s" |
|
450 | href: "%s" | |
450 | })); |
|
451 | })); | |
451 | """ |
|
452 | """ | |
452 |
|
453 | |||
453 | lib_t1 = """$.getScript("%s", function () { |
|
454 | lib_t1 = """$.getScript("%s", function () { | |
454 | """ |
|
455 | """ | |
455 | lib_t2 = """}); |
|
456 | lib_t2 = """}); | |
456 | """ |
|
457 | """ | |
457 |
|
458 | |||
458 | class Javascript(TextDisplayObject): |
|
459 | class Javascript(TextDisplayObject): | |
459 |
|
460 | |||
460 | def __init__(self, data=None, url=None, filename=None, lib=None, css=None): |
|
461 | def __init__(self, data=None, url=None, filename=None, lib=None, css=None): | |
461 | """Create a Javascript display object given raw data. |
|
462 | """Create a Javascript display object given raw data. | |
462 |
|
463 | |||
463 | When this object is returned by an expression or passed to the |
|
464 | When this object is returned by an expression or passed to the | |
464 | display function, it will result in the data being displayed |
|
465 | display function, it will result in the data being displayed | |
465 | in the frontend. If the data is a URL, the data will first be |
|
466 | in the frontend. If the data is a URL, the data will first be | |
466 | downloaded and then displayed. |
|
467 | downloaded and then displayed. | |
467 |
|
468 | |||
468 | In the Notebook, the containing element will be available as `element`, |
|
469 | In the Notebook, the containing element will be available as `element`, | |
469 | and jQuery will be available. The output area starts hidden, so if |
|
470 | and jQuery will be available. The output area starts hidden, so if | |
470 | the js appends content to `element` that should be visible, then |
|
471 | the js appends content to `element` that should be visible, then | |
471 | it must call `container.show()` to unhide the area. |
|
472 | it must call `container.show()` to unhide the area. | |
472 |
|
473 | |||
473 | Parameters |
|
474 | Parameters | |
474 | ---------- |
|
475 | ---------- | |
475 | data : unicode, str or bytes |
|
476 | data : unicode, str or bytes | |
476 | The Javascript source code or a URL to download it from. |
|
477 | The Javascript source code or a URL to download it from. | |
477 | url : unicode |
|
478 | url : unicode | |
478 | A URL to download the data from. |
|
479 | A URL to download the data from. | |
479 | filename : unicode |
|
480 | filename : unicode | |
480 | Path to a local file to load the data from. |
|
481 | Path to a local file to load the data from. | |
481 | lib : list or str |
|
482 | lib : list or str | |
482 | A sequence of Javascript library URLs to load asynchronously before |
|
483 | A sequence of Javascript library URLs to load asynchronously before | |
483 | running the source code. The full URLs of the libraries should |
|
484 | running the source code. The full URLs of the libraries should | |
484 | be given. A single Javascript library URL can also be given as a |
|
485 | be given. A single Javascript library URL can also be given as a | |
485 | string. |
|
486 | string. | |
486 | css: : list or str |
|
487 | css: : list or str | |
487 | A sequence of css files to load before running the source code. |
|
488 | A sequence of css files to load before running the source code. | |
488 | The full URLs of the css files should be given. A single css URL |
|
489 | The full URLs of the css files should be given. A single css URL | |
489 | can also be given as a string. |
|
490 | can also be given as a string. | |
490 | """ |
|
491 | """ | |
491 | if isinstance(lib, string_types): |
|
492 | if isinstance(lib, string_types): | |
492 | lib = [lib] |
|
493 | lib = [lib] | |
493 | elif lib is None: |
|
494 | elif lib is None: | |
494 | lib = [] |
|
495 | lib = [] | |
495 | if isinstance(css, string_types): |
|
496 | if isinstance(css, string_types): | |
496 | css = [css] |
|
497 | css = [css] | |
497 | elif css is None: |
|
498 | elif css is None: | |
498 | css = [] |
|
499 | css = [] | |
499 | if not isinstance(lib, (list,tuple)): |
|
500 | if not isinstance(lib, (list,tuple)): | |
500 | raise TypeError('expected sequence, got: %r' % lib) |
|
501 | raise TypeError('expected sequence, got: %r' % lib) | |
501 | if not isinstance(css, (list,tuple)): |
|
502 | if not isinstance(css, (list,tuple)): | |
502 | raise TypeError('expected sequence, got: %r' % css) |
|
503 | raise TypeError('expected sequence, got: %r' % css) | |
503 | self.lib = lib |
|
504 | self.lib = lib | |
504 | self.css = css |
|
505 | self.css = css | |
505 | super(Javascript, self).__init__(data=data, url=url, filename=filename) |
|
506 | super(Javascript, self).__init__(data=data, url=url, filename=filename) | |
506 |
|
507 | |||
507 | def _repr_javascript_(self): |
|
508 | def _repr_javascript_(self): | |
508 | r = '' |
|
509 | r = '' | |
509 | for c in self.css: |
|
510 | for c in self.css: | |
510 | r += css_t % c |
|
511 | r += css_t % c | |
511 | for l in self.lib: |
|
512 | for l in self.lib: | |
512 | r += lib_t1 % l |
|
513 | r += lib_t1 % l | |
513 | r += self.data |
|
514 | r += self.data | |
514 | r += lib_t2*len(self.lib) |
|
515 | r += lib_t2*len(self.lib) | |
515 | return r |
|
516 | return r | |
516 |
|
517 | |||
517 | # constants for identifying png/jpeg data |
|
518 | # constants for identifying png/jpeg data | |
518 | _PNG = b'\x89PNG\r\n\x1a\n' |
|
519 | _PNG = b'\x89PNG\r\n\x1a\n' | |
519 | _JPEG = b'\xff\xd8' |
|
520 | _JPEG = b'\xff\xd8' | |
520 |
|
521 | |||
521 | def _pngxy(data): |
|
522 | def _pngxy(data): | |
522 | """read the (width, height) from a PNG header""" |
|
523 | """read the (width, height) from a PNG header""" | |
523 | ihdr = data.index(b'IHDR') |
|
524 | ihdr = data.index(b'IHDR') | |
524 | # next 8 bytes are width/height |
|
525 | # next 8 bytes are width/height | |
525 | w4h4 = data[ihdr+4:ihdr+12] |
|
526 | w4h4 = data[ihdr+4:ihdr+12] | |
526 | return struct.unpack('>ii', w4h4) |
|
527 | return struct.unpack('>ii', w4h4) | |
527 |
|
528 | |||
528 | def _jpegxy(data): |
|
529 | def _jpegxy(data): | |
529 | """read the (width, height) from a JPEG header""" |
|
530 | """read the (width, height) from a JPEG header""" | |
530 | # adapted from http://www.64lines.com/jpeg-width-height |
|
531 | # adapted from http://www.64lines.com/jpeg-width-height | |
531 |
|
532 | |||
532 | idx = 4 |
|
533 | idx = 4 | |
533 | while True: |
|
534 | while True: | |
534 | block_size = struct.unpack('>H', data[idx:idx+2])[0] |
|
535 | block_size = struct.unpack('>H', data[idx:idx+2])[0] | |
535 | idx = idx + block_size |
|
536 | idx = idx + block_size | |
536 | if data[idx:idx+2] == b'\xFF\xC0': |
|
537 | if data[idx:idx+2] == b'\xFF\xC0': | |
537 | # found Start of Frame |
|
538 | # found Start of Frame | |
538 | iSOF = idx |
|
539 | iSOF = idx | |
539 | break |
|
540 | break | |
540 | else: |
|
541 | else: | |
541 | # read another block |
|
542 | # read another block | |
542 | idx += 2 |
|
543 | idx += 2 | |
543 |
|
544 | |||
544 | h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9]) |
|
545 | h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9]) | |
545 | return w, h |
|
546 | return w, h | |
546 |
|
547 | |||
547 | class Image(DisplayObject): |
|
548 | class Image(DisplayObject): | |
548 |
|
549 | |||
549 | _read_flags = 'rb' |
|
550 | _read_flags = 'rb' | |
550 | _FMT_JPEG = u'jpeg' |
|
551 | _FMT_JPEG = u'jpeg' | |
551 | _FMT_PNG = u'png' |
|
552 | _FMT_PNG = u'png' | |
552 | _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG] |
|
553 | _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG] | |
553 |
|
554 | |||
554 | def __init__(self, data=None, url=None, filename=None, format=u'png', embed=None, width=None, height=None, retina=False): |
|
555 | def __init__(self, data=None, url=None, filename=None, format=u'png', embed=None, width=None, height=None, retina=False): | |
555 | """Create a PNG/JPEG image object given raw data. |
|
556 | """Create a PNG/JPEG image object given raw data. | |
556 |
|
557 | |||
557 | When this object is returned by an input cell or passed to the |
|
558 | When this object is returned by an input cell or passed to the | |
558 | display function, it will result in the image being displayed |
|
559 | display function, it will result in the image being displayed | |
559 | in the frontend. |
|
560 | in the frontend. | |
560 |
|
561 | |||
561 | Parameters |
|
562 | Parameters | |
562 | ---------- |
|
563 | ---------- | |
563 | data : unicode, str or bytes |
|
564 | data : unicode, str or bytes | |
564 | The raw image data or a URL or filename to load the data from. |
|
565 | The raw image data or a URL or filename to load the data from. | |
565 | This always results in embedded image data. |
|
566 | This always results in embedded image data. | |
566 | url : unicode |
|
567 | url : unicode | |
567 | A URL to download the data from. If you specify `url=`, |
|
568 | A URL to download the data from. If you specify `url=`, | |
568 | the image data will not be embedded unless you also specify `embed=True`. |
|
569 | the image data will not be embedded unless you also specify `embed=True`. | |
569 | filename : unicode |
|
570 | filename : unicode | |
570 | Path to a local file to load the data from. |
|
571 | Path to a local file to load the data from. | |
571 | Images from a file are always embedded. |
|
572 | Images from a file are always embedded. | |
572 | format : unicode |
|
573 | format : unicode | |
573 | The format of the image data (png/jpeg/jpg). If a filename or URL is given |
|
574 | The format of the image data (png/jpeg/jpg). If a filename or URL is given | |
574 | for format will be inferred from the filename extension. |
|
575 | for format will be inferred from the filename extension. | |
575 | embed : bool |
|
576 | embed : bool | |
576 | Should the image data be embedded using a data URI (True) or be |
|
577 | Should the image data be embedded using a data URI (True) or be | |
577 | loaded using an <img> tag. Set this to True if you want the image |
|
578 | loaded using an <img> tag. Set this to True if you want the image | |
578 | to be viewable later with no internet connection in the notebook. |
|
579 | to be viewable later with no internet connection in the notebook. | |
579 |
|
580 | |||
580 | Default is `True`, unless the keyword argument `url` is set, then |
|
581 | Default is `True`, unless the keyword argument `url` is set, then | |
581 | default value is `False`. |
|
582 | default value is `False`. | |
582 |
|
583 | |||
583 | Note that QtConsole is not able to display images if `embed` is set to `False` |
|
584 | Note that QtConsole is not able to display images if `embed` is set to `False` | |
584 | width : int |
|
585 | width : int | |
585 | Width to which to constrain the image in html |
|
586 | Width to which to constrain the image in html | |
586 | height : int |
|
587 | height : int | |
587 | Height to which to constrain the image in html |
|
588 | Height to which to constrain the image in html | |
588 | retina : bool |
|
589 | retina : bool | |
589 | Automatically set the width and height to half of the measured |
|
590 | Automatically set the width and height to half of the measured | |
590 | width and height. |
|
591 | width and height. | |
591 | This only works for embedded images because it reads the width/height |
|
592 | This only works for embedded images because it reads the width/height | |
592 | from image data. |
|
593 | from image data. | |
593 | For non-embedded images, you can just set the desired display width |
|
594 | For non-embedded images, you can just set the desired display width | |
594 | and height directly. |
|
595 | and height directly. | |
595 |
|
596 | |||
596 | Examples |
|
597 | Examples | |
597 | -------- |
|
598 | -------- | |
598 | # embedded image data, works in qtconsole and notebook |
|
599 | # embedded image data, works in qtconsole and notebook | |
599 | # when passed positionally, the first arg can be any of raw image data, |
|
600 | # when passed positionally, the first arg can be any of raw image data, | |
600 | # a URL, or a filename from which to load image data. |
|
601 | # a URL, or a filename from which to load image data. | |
601 | # The result is always embedding image data for inline images. |
|
602 | # The result is always embedding image data for inline images. | |
602 | Image('http://www.google.fr/images/srpr/logo3w.png') |
|
603 | Image('http://www.google.fr/images/srpr/logo3w.png') | |
603 | Image('/path/to/image.jpg') |
|
604 | Image('/path/to/image.jpg') | |
604 | Image(b'RAW_PNG_DATA...') |
|
605 | Image(b'RAW_PNG_DATA...') | |
605 |
|
606 | |||
606 | # Specifying Image(url=...) does not embed the image data, |
|
607 | # Specifying Image(url=...) does not embed the image data, | |
607 | # it only generates `<img>` tag with a link to the source. |
|
608 | # it only generates `<img>` tag with a link to the source. | |
608 | # This will not work in the qtconsole or offline. |
|
609 | # This will not work in the qtconsole or offline. | |
609 | Image(url='http://www.google.fr/images/srpr/logo3w.png') |
|
610 | Image(url='http://www.google.fr/images/srpr/logo3w.png') | |
610 |
|
611 | |||
611 | """ |
|
612 | """ | |
612 | if filename is not None: |
|
613 | if filename is not None: | |
613 | ext = self._find_ext(filename) |
|
614 | ext = self._find_ext(filename) | |
614 | elif url is not None: |
|
615 | elif url is not None: | |
615 | ext = self._find_ext(url) |
|
616 | ext = self._find_ext(url) | |
616 | elif data is None: |
|
617 | elif data is None: | |
617 | raise ValueError("No image data found. Expecting filename, url, or data.") |
|
618 | raise ValueError("No image data found. Expecting filename, url, or data.") | |
618 | elif isinstance(data, string_types) and ( |
|
619 | elif isinstance(data, string_types) and ( | |
619 | data.startswith('http') or _safe_exists(data) |
|
620 | data.startswith('http') or _safe_exists(data) | |
620 | ): |
|
621 | ): | |
621 | ext = self._find_ext(data) |
|
622 | ext = self._find_ext(data) | |
622 | else: |
|
623 | else: | |
623 | ext = None |
|
624 | ext = None | |
624 |
|
625 | |||
625 | if ext is not None: |
|
626 | if ext is not None: | |
626 | format = ext.lower() |
|
627 | format = ext.lower() | |
627 | if ext == u'jpg' or ext == u'jpeg': |
|
628 | if ext == u'jpg' or ext == u'jpeg': | |
628 | format = self._FMT_JPEG |
|
629 | format = self._FMT_JPEG | |
629 | if ext == u'png': |
|
630 | if ext == u'png': | |
630 | format = self._FMT_PNG |
|
631 | format = self._FMT_PNG | |
631 | elif isinstance(data, bytes) and format == 'png': |
|
632 | elif isinstance(data, bytes) and format == 'png': | |
632 | # infer image type from image data header, |
|
633 | # infer image type from image data header, | |
633 | # only if format might not have been specified. |
|
634 | # only if format might not have been specified. | |
634 | if data[:2] == _JPEG: |
|
635 | if data[:2] == _JPEG: | |
635 | format = 'jpeg' |
|
636 | format = 'jpeg' | |
636 |
|
637 | |||
637 | self.format = unicode_type(format).lower() |
|
638 | self.format = unicode_type(format).lower() | |
638 | self.embed = embed if embed is not None else (url is None) |
|
639 | self.embed = embed if embed is not None else (url is None) | |
639 |
|
640 | |||
640 | if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS: |
|
641 | if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS: | |
641 | raise ValueError("Cannot embed the '%s' image format" % (self.format)) |
|
642 | raise ValueError("Cannot embed the '%s' image format" % (self.format)) | |
642 | self.width = width |
|
643 | self.width = width | |
643 | self.height = height |
|
644 | self.height = height | |
644 | self.retina = retina |
|
645 | self.retina = retina | |
645 | super(Image, self).__init__(data=data, url=url, filename=filename) |
|
646 | super(Image, self).__init__(data=data, url=url, filename=filename) | |
646 |
|
647 | |||
647 | if retina: |
|
648 | if retina: | |
648 | self._retina_shape() |
|
649 | self._retina_shape() | |
649 |
|
650 | |||
650 | def _retina_shape(self): |
|
651 | def _retina_shape(self): | |
651 | """load pixel-doubled width and height from image data""" |
|
652 | """load pixel-doubled width and height from image data""" | |
652 | if not self.embed: |
|
653 | if not self.embed: | |
653 | return |
|
654 | return | |
654 | if self.format == 'png': |
|
655 | if self.format == 'png': | |
655 | w, h = _pngxy(self.data) |
|
656 | w, h = _pngxy(self.data) | |
656 | elif self.format == 'jpeg': |
|
657 | elif self.format == 'jpeg': | |
657 | w, h = _jpegxy(self.data) |
|
658 | w, h = _jpegxy(self.data) | |
658 | else: |
|
659 | else: | |
659 | # retina only supports png |
|
660 | # retina only supports png | |
660 | return |
|
661 | return | |
661 | self.width = w // 2 |
|
662 | self.width = w // 2 | |
662 | self.height = h // 2 |
|
663 | self.height = h // 2 | |
663 |
|
664 | |||
664 | def reload(self): |
|
665 | def reload(self): | |
665 | """Reload the raw data from file or URL.""" |
|
666 | """Reload the raw data from file or URL.""" | |
666 | if self.embed: |
|
667 | if self.embed: | |
667 | super(Image,self).reload() |
|
668 | super(Image,self).reload() | |
668 | if self.retina: |
|
669 | if self.retina: | |
669 | self._retina_shape() |
|
670 | self._retina_shape() | |
670 |
|
671 | |||
671 | def _repr_html_(self): |
|
672 | def _repr_html_(self): | |
672 | if not self.embed: |
|
673 | if not self.embed: | |
673 | width = height = '' |
|
674 | width = height = '' | |
674 | if self.width: |
|
675 | if self.width: | |
675 | width = ' width="%d"' % self.width |
|
676 | width = ' width="%d"' % self.width | |
676 | if self.height: |
|
677 | if self.height: | |
677 | height = ' height="%d"' % self.height |
|
678 | height = ' height="%d"' % self.height | |
678 | return u'<img src="%s"%s%s/>' % (self.url, width, height) |
|
679 | return u'<img src="%s"%s%s/>' % (self.url, width, height) | |
679 |
|
680 | |||
680 | def _data_and_metadata(self): |
|
681 | def _data_and_metadata(self): | |
681 | """shortcut for returning metadata with shape information, if defined""" |
|
682 | """shortcut for returning metadata with shape information, if defined""" | |
682 | md = {} |
|
683 | md = {} | |
683 | if self.width: |
|
684 | if self.width: | |
684 | md['width'] = self.width |
|
685 | md['width'] = self.width | |
685 | if self.height: |
|
686 | if self.height: | |
686 | md['height'] = self.height |
|
687 | md['height'] = self.height | |
687 | if md: |
|
688 | if md: | |
688 | return self.data, md |
|
689 | return self.data, md | |
689 | else: |
|
690 | else: | |
690 | return self.data |
|
691 | return self.data | |
691 |
|
692 | |||
692 | def _repr_png_(self): |
|
693 | def _repr_png_(self): | |
693 | if self.embed and self.format == u'png': |
|
694 | if self.embed and self.format == u'png': | |
694 | return self._data_and_metadata() |
|
695 | return self._data_and_metadata() | |
695 |
|
696 | |||
696 | def _repr_jpeg_(self): |
|
697 | def _repr_jpeg_(self): | |
697 | if self.embed and (self.format == u'jpeg' or self.format == u'jpg'): |
|
698 | if self.embed and (self.format == u'jpeg' or self.format == u'jpg'): | |
698 | return self._data_and_metadata() |
|
699 | return self._data_and_metadata() | |
699 |
|
700 | |||
700 | def _find_ext(self, s): |
|
701 | def _find_ext(self, s): | |
701 | return unicode_type(s.split('.')[-1].lower()) |
|
702 | return unicode_type(s.split('.')[-1].lower()) | |
702 |
|
703 | |||
703 |
|
704 | |||
704 | def clear_output(wait=False): |
|
705 | def clear_output(wait=False): | |
705 | """Clear the output of the current cell receiving output. |
|
706 | """Clear the output of the current cell receiving output. | |
706 |
|
707 | |||
707 | Parameters |
|
708 | Parameters | |
708 | ---------- |
|
709 | ---------- | |
709 | wait : bool [default: false] |
|
710 | wait : bool [default: false] | |
710 | Wait to clear the output until new output is available to replace it.""" |
|
711 | Wait to clear the output until new output is available to replace it.""" | |
711 | from IPython.core.interactiveshell import InteractiveShell |
|
712 | from IPython.core.interactiveshell import InteractiveShell | |
712 | if InteractiveShell.initialized(): |
|
713 | if InteractiveShell.initialized(): | |
713 | InteractiveShell.instance().display_pub.clear_output(wait) |
|
714 | InteractiveShell.instance().display_pub.clear_output(wait) | |
714 | else: |
|
715 | else: | |
715 | from IPython.utils import io |
|
716 | from IPython.utils import io | |
716 | print('\033[2K\r', file=io.stdout, end='') |
|
717 | print('\033[2K\r', file=io.stdout, end='') | |
717 | io.stdout.flush() |
|
718 | io.stdout.flush() | |
718 | print('\033[2K\r', file=io.stderr, end='') |
|
719 | print('\033[2K\r', file=io.stderr, end='') | |
719 | io.stderr.flush() |
|
720 | io.stderr.flush() | |
720 |
|
721 | |||
721 |
|
722 | |||
722 | @skip_doctest |
|
723 | @skip_doctest | |
723 | def set_matplotlib_formats(*formats, **kwargs): |
|
724 | def set_matplotlib_formats(*formats, **kwargs): | |
724 | """Select figure formats for the inline backend. Optionally pass quality for JPEG. |
|
725 | """Select figure formats for the inline backend. Optionally pass quality for JPEG. | |
725 |
|
726 | |||
726 | For example, this enables PNG and JPEG output with a JPEG quality of 90%:: |
|
727 | For example, this enables PNG and JPEG output with a JPEG quality of 90%:: | |
727 |
|
728 | |||
728 | In [1]: set_matplotlib_formats('png', 'jpeg', quality=90) |
|
729 | In [1]: set_matplotlib_formats('png', 'jpeg', quality=90) | |
729 |
|
730 | |||
730 | To set this in your config files use the following:: |
|
731 | To set this in your config files use the following:: | |
731 |
|
732 | |||
732 | c.InlineBackend.figure_formats = {'png', 'jpeg'} |
|
733 | c.InlineBackend.figure_formats = {'png', 'jpeg'} | |
733 | c.InlineBackend.print_figure_kwargs.update({'quality' : 90}) |
|
734 | c.InlineBackend.print_figure_kwargs.update({'quality' : 90}) | |
734 |
|
735 | |||
735 | Parameters |
|
736 | Parameters | |
736 | ---------- |
|
737 | ---------- | |
737 | *formats : strs |
|
738 | *formats : strs | |
738 | One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. |
|
739 | One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. | |
739 | **kwargs : |
|
740 | **kwargs : | |
740 | Keyword args will be relayed to ``figure.canvas.print_figure``. |
|
741 | Keyword args will be relayed to ``figure.canvas.print_figure``. | |
741 | """ |
|
742 | """ | |
742 | from IPython.core.interactiveshell import InteractiveShell |
|
743 | from IPython.core.interactiveshell import InteractiveShell | |
743 | from IPython.core.pylabtools import select_figure_formats |
|
744 | from IPython.core.pylabtools import select_figure_formats | |
744 | from IPython.kernel.zmq.pylab.config import InlineBackend |
|
745 | from IPython.kernel.zmq.pylab.config import InlineBackend | |
745 | # build kwargs, starting with InlineBackend config |
|
746 | # build kwargs, starting with InlineBackend config | |
746 | kw = {} |
|
747 | kw = {} | |
747 | cfg = InlineBackend.instance() |
|
748 | cfg = InlineBackend.instance() | |
748 | kw.update(cfg.print_figure_kwargs) |
|
749 | kw.update(cfg.print_figure_kwargs) | |
749 | kw.update(**kwargs) |
|
750 | kw.update(**kwargs) | |
750 | shell = InteractiveShell.instance() |
|
751 | shell = InteractiveShell.instance() | |
751 | select_figure_formats(shell, formats, **kw) |
|
752 | select_figure_formats(shell, formats, **kw) | |
752 |
|
753 | |||
753 | @skip_doctest |
|
754 | @skip_doctest | |
754 | def set_matplotlib_close(close=True): |
|
755 | def set_matplotlib_close(close=True): | |
755 | """Set whether the inline backend closes all figures automatically or not. |
|
756 | """Set whether the inline backend closes all figures automatically or not. | |
756 |
|
757 | |||
757 | By default, the inline backend used in the IPython Notebook will close all |
|
758 | By default, the inline backend used in the IPython Notebook will close all | |
758 | matplotlib figures automatically after each cell is run. This means that |
|
759 | matplotlib figures automatically after each cell is run. This means that | |
759 | plots in different cells won't interfere. Sometimes, you may want to make |
|
760 | plots in different cells won't interfere. Sometimes, you may want to make | |
760 | a plot in one cell and then refine it in later cells. This can be accomplished |
|
761 | a plot in one cell and then refine it in later cells. This can be accomplished | |
761 | by:: |
|
762 | by:: | |
762 |
|
763 | |||
763 | In [1]: set_matplotlib_close(False) |
|
764 | In [1]: set_matplotlib_close(False) | |
764 |
|
765 | |||
765 | To set this in your config files use the following:: |
|
766 | To set this in your config files use the following:: | |
766 |
|
767 | |||
767 | c.InlineBackend.close_figures = False |
|
768 | c.InlineBackend.close_figures = False | |
768 |
|
769 | |||
769 | Parameters |
|
770 | Parameters | |
770 | ---------- |
|
771 | ---------- | |
771 | close : bool |
|
772 | close : bool | |
772 | Should all matplotlib figures be automatically closed after each cell is |
|
773 | Should all matplotlib figures be automatically closed after each cell is | |
773 | run? |
|
774 | run? | |
774 | """ |
|
775 | """ | |
775 | from IPython.kernel.zmq.pylab.config import InlineBackend |
|
776 | from IPython.kernel.zmq.pylab.config import InlineBackend | |
776 | cfg = InlineBackend.instance() |
|
777 | cfg = InlineBackend.instance() | |
777 | cfg.close_figures = close |
|
778 | cfg.close_figures = close | |
778 |
|
779 |
@@ -1,287 +1,287 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Displayhook for IPython. |
|
2 | """Displayhook for IPython. | |
3 |
|
3 | |||
4 | This defines a callable class that IPython uses for `sys.displayhook`. |
|
4 | This defines a callable class that IPython uses for `sys.displayhook`. | |
5 |
|
5 | |||
6 | Authors: |
|
6 | Authors: | |
7 |
|
7 | |||
8 | * Fernando Perez |
|
8 | * Fernando Perez | |
9 | * Brian Granger |
|
9 | * Brian Granger | |
10 | * Robert Kern |
|
10 | * Robert Kern | |
11 | """ |
|
11 | """ | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Copyright (C) 2008-2011 The IPython Development Team |
|
14 | # Copyright (C) 2008-2011 The IPython Development Team | |
15 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
15 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> | |
16 | # |
|
16 | # | |
17 | # Distributed under the terms of the BSD License. The full license is in |
|
17 | # Distributed under the terms of the BSD License. The full license is in | |
18 | # the file COPYING, distributed as part of this software. |
|
18 | # the file COPYING, distributed as part of this software. | |
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 |
|
20 | |||
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 | # Imports |
|
22 | # Imports | |
23 | #----------------------------------------------------------------------------- |
|
23 | #----------------------------------------------------------------------------- | |
24 | from __future__ import print_function |
|
24 | from __future__ import print_function | |
25 |
|
25 | |||
26 | import sys |
|
26 | import sys | |
27 |
|
27 | |||
28 |
|
28 | from IPython.core.formatters import _safe_get_formatter_method | ||
29 | from IPython.config.configurable import Configurable |
|
29 | from IPython.config.configurable import Configurable | |
30 | from IPython.utils import io |
|
30 | from IPython.utils import io | |
31 | from IPython.utils.py3compat import builtin_mod |
|
31 | from IPython.utils.py3compat import builtin_mod | |
32 | from IPython.utils.traitlets import Instance |
|
32 | from IPython.utils.traitlets import Instance | |
33 | from IPython.utils.warn import warn |
|
33 | from IPython.utils.warn import warn | |
34 |
|
34 | |||
35 | #----------------------------------------------------------------------------- |
|
35 | #----------------------------------------------------------------------------- | |
36 | # Main displayhook class |
|
36 | # Main displayhook class | |
37 | #----------------------------------------------------------------------------- |
|
37 | #----------------------------------------------------------------------------- | |
38 |
|
38 | |||
39 | # TODO: Move the various attributes (cache_size, [others now moved]). Some |
|
39 | # TODO: Move the various attributes (cache_size, [others now moved]). Some | |
40 | # of these are also attributes of InteractiveShell. They should be on ONE object |
|
40 | # of these are also attributes of InteractiveShell. They should be on ONE object | |
41 | # only and the other objects should ask that one object for their values. |
|
41 | # only and the other objects should ask that one object for their values. | |
42 |
|
42 | |||
43 | class DisplayHook(Configurable): |
|
43 | class DisplayHook(Configurable): | |
44 | """The custom IPython displayhook to replace sys.displayhook. |
|
44 | """The custom IPython displayhook to replace sys.displayhook. | |
45 |
|
45 | |||
46 | This class does many things, but the basic idea is that it is a callable |
|
46 | This class does many things, but the basic idea is that it is a callable | |
47 | that gets called anytime user code returns a value. |
|
47 | that gets called anytime user code returns a value. | |
48 | """ |
|
48 | """ | |
49 |
|
49 | |||
50 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
50 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
51 |
|
51 | |||
52 | def __init__(self, shell=None, cache_size=1000, **kwargs): |
|
52 | def __init__(self, shell=None, cache_size=1000, **kwargs): | |
53 | super(DisplayHook, self).__init__(shell=shell, **kwargs) |
|
53 | super(DisplayHook, self).__init__(shell=shell, **kwargs) | |
54 |
|
54 | |||
55 | cache_size_min = 3 |
|
55 | cache_size_min = 3 | |
56 | if cache_size <= 0: |
|
56 | if cache_size <= 0: | |
57 | self.do_full_cache = 0 |
|
57 | self.do_full_cache = 0 | |
58 | cache_size = 0 |
|
58 | cache_size = 0 | |
59 | elif cache_size < cache_size_min: |
|
59 | elif cache_size < cache_size_min: | |
60 | self.do_full_cache = 0 |
|
60 | self.do_full_cache = 0 | |
61 | cache_size = 0 |
|
61 | cache_size = 0 | |
62 | warn('caching was disabled (min value for cache size is %s).' % |
|
62 | warn('caching was disabled (min value for cache size is %s).' % | |
63 | cache_size_min,level=3) |
|
63 | cache_size_min,level=3) | |
64 | else: |
|
64 | else: | |
65 | self.do_full_cache = 1 |
|
65 | self.do_full_cache = 1 | |
66 |
|
66 | |||
67 | self.cache_size = cache_size |
|
67 | self.cache_size = cache_size | |
68 |
|
68 | |||
69 | # we need a reference to the user-level namespace |
|
69 | # we need a reference to the user-level namespace | |
70 | self.shell = shell |
|
70 | self.shell = shell | |
71 |
|
71 | |||
72 | self._,self.__,self.___ = '','','' |
|
72 | self._,self.__,self.___ = '','','' | |
73 |
|
73 | |||
74 | # these are deliberately global: |
|
74 | # these are deliberately global: | |
75 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} |
|
75 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} | |
76 | self.shell.user_ns.update(to_user_ns) |
|
76 | self.shell.user_ns.update(to_user_ns) | |
77 |
|
77 | |||
78 | @property |
|
78 | @property | |
79 | def prompt_count(self): |
|
79 | def prompt_count(self): | |
80 | return self.shell.execution_count |
|
80 | return self.shell.execution_count | |
81 |
|
81 | |||
82 | #------------------------------------------------------------------------- |
|
82 | #------------------------------------------------------------------------- | |
83 | # Methods used in __call__. Override these methods to modify the behavior |
|
83 | # Methods used in __call__. Override these methods to modify the behavior | |
84 | # of the displayhook. |
|
84 | # of the displayhook. | |
85 | #------------------------------------------------------------------------- |
|
85 | #------------------------------------------------------------------------- | |
86 |
|
86 | |||
87 | def check_for_underscore(self): |
|
87 | def check_for_underscore(self): | |
88 | """Check if the user has set the '_' variable by hand.""" |
|
88 | """Check if the user has set the '_' variable by hand.""" | |
89 | # If something injected a '_' variable in __builtin__, delete |
|
89 | # If something injected a '_' variable in __builtin__, delete | |
90 | # ipython's automatic one so we don't clobber that. gettext() in |
|
90 | # ipython's automatic one so we don't clobber that. gettext() in | |
91 | # particular uses _, so we need to stay away from it. |
|
91 | # particular uses _, so we need to stay away from it. | |
92 | if '_' in builtin_mod.__dict__: |
|
92 | if '_' in builtin_mod.__dict__: | |
93 | try: |
|
93 | try: | |
94 | del self.shell.user_ns['_'] |
|
94 | del self.shell.user_ns['_'] | |
95 | except KeyError: |
|
95 | except KeyError: | |
96 | pass |
|
96 | pass | |
97 |
|
97 | |||
98 | def quiet(self): |
|
98 | def quiet(self): | |
99 | """Should we silence the display hook because of ';'?""" |
|
99 | """Should we silence the display hook because of ';'?""" | |
100 | # do not print output if input ends in ';' |
|
100 | # do not print output if input ends in ';' | |
101 | try: |
|
101 | try: | |
102 | cell = self.shell.history_manager.input_hist_parsed[self.prompt_count] |
|
102 | cell = self.shell.history_manager.input_hist_parsed[self.prompt_count] | |
103 | if cell.rstrip().endswith(';'): |
|
103 | if cell.rstrip().endswith(';'): | |
104 | return True |
|
104 | return True | |
105 | except IndexError: |
|
105 | except IndexError: | |
106 | # some uses of ipshellembed may fail here |
|
106 | # some uses of ipshellembed may fail here | |
107 | pass |
|
107 | pass | |
108 | return False |
|
108 | return False | |
109 |
|
109 | |||
110 | def start_displayhook(self): |
|
110 | def start_displayhook(self): | |
111 | """Start the displayhook, initializing resources.""" |
|
111 | """Start the displayhook, initializing resources.""" | |
112 | pass |
|
112 | pass | |
113 |
|
113 | |||
114 | def write_output_prompt(self): |
|
114 | def write_output_prompt(self): | |
115 | """Write the output prompt. |
|
115 | """Write the output prompt. | |
116 |
|
116 | |||
117 | The default implementation simply writes the prompt to |
|
117 | The default implementation simply writes the prompt to | |
118 | ``io.stdout``. |
|
118 | ``io.stdout``. | |
119 | """ |
|
119 | """ | |
120 | # Use write, not print which adds an extra space. |
|
120 | # Use write, not print which adds an extra space. | |
121 | io.stdout.write(self.shell.separate_out) |
|
121 | io.stdout.write(self.shell.separate_out) | |
122 | outprompt = self.shell.prompt_manager.render('out') |
|
122 | outprompt = self.shell.prompt_manager.render('out') | |
123 | if self.do_full_cache: |
|
123 | if self.do_full_cache: | |
124 | io.stdout.write(outprompt) |
|
124 | io.stdout.write(outprompt) | |
125 |
|
125 | |||
126 | def compute_format_data(self, result): |
|
126 | def compute_format_data(self, result): | |
127 | """Compute format data of the object to be displayed. |
|
127 | """Compute format data of the object to be displayed. | |
128 |
|
128 | |||
129 | The format data is a generalization of the :func:`repr` of an object. |
|
129 | The format data is a generalization of the :func:`repr` of an object. | |
130 | In the default implementation the format data is a :class:`dict` of |
|
130 | In the default implementation the format data is a :class:`dict` of | |
131 | key value pair where the keys are valid MIME types and the values |
|
131 | key value pair where the keys are valid MIME types and the values | |
132 | are JSON'able data structure containing the raw data for that MIME |
|
132 | are JSON'able data structure containing the raw data for that MIME | |
133 | type. It is up to frontends to determine pick a MIME to to use and |
|
133 | type. It is up to frontends to determine pick a MIME to to use and | |
134 | display that data in an appropriate manner. |
|
134 | display that data in an appropriate manner. | |
135 |
|
135 | |||
136 | This method only computes the format data for the object and should |
|
136 | This method only computes the format data for the object and should | |
137 | NOT actually print or write that to a stream. |
|
137 | NOT actually print or write that to a stream. | |
138 |
|
138 | |||
139 | Parameters |
|
139 | Parameters | |
140 | ---------- |
|
140 | ---------- | |
141 | result : object |
|
141 | result : object | |
142 | The Python object passed to the display hook, whose format will be |
|
142 | The Python object passed to the display hook, whose format will be | |
143 | computed. |
|
143 | computed. | |
144 |
|
144 | |||
145 | Returns |
|
145 | Returns | |
146 | ------- |
|
146 | ------- | |
147 | (format_dict, md_dict) : dict |
|
147 | (format_dict, md_dict) : dict | |
148 | format_dict is a :class:`dict` whose keys are valid MIME types and values are |
|
148 | format_dict is a :class:`dict` whose keys are valid MIME types and values are | |
149 | JSON'able raw data for that MIME type. It is recommended that |
|
149 | JSON'able raw data for that MIME type. It is recommended that | |
150 | all return values of this should always include the "text/plain" |
|
150 | all return values of this should always include the "text/plain" | |
151 | MIME type representation of the object. |
|
151 | MIME type representation of the object. | |
152 | md_dict is a :class:`dict` with the same MIME type keys |
|
152 | md_dict is a :class:`dict` with the same MIME type keys | |
153 | of metadata associated with each output. |
|
153 | of metadata associated with each output. | |
154 |
|
154 | |||
155 | """ |
|
155 | """ | |
156 | return self.shell.display_formatter.format(result) |
|
156 | return self.shell.display_formatter.format(result) | |
157 |
|
157 | |||
158 | def write_format_data(self, format_dict, md_dict=None): |
|
158 | def write_format_data(self, format_dict, md_dict=None): | |
159 | """Write the format data dict to the frontend. |
|
159 | """Write the format data dict to the frontend. | |
160 |
|
160 | |||
161 | This default version of this method simply writes the plain text |
|
161 | This default version of this method simply writes the plain text | |
162 | representation of the object to ``io.stdout``. Subclasses should |
|
162 | representation of the object to ``io.stdout``. Subclasses should | |
163 | override this method to send the entire `format_dict` to the |
|
163 | override this method to send the entire `format_dict` to the | |
164 | frontends. |
|
164 | frontends. | |
165 |
|
165 | |||
166 | Parameters |
|
166 | Parameters | |
167 | ---------- |
|
167 | ---------- | |
168 | format_dict : dict |
|
168 | format_dict : dict | |
169 | The format dict for the object passed to `sys.displayhook`. |
|
169 | The format dict for the object passed to `sys.displayhook`. | |
170 | md_dict : dict (optional) |
|
170 | md_dict : dict (optional) | |
171 | The metadata dict to be associated with the display data. |
|
171 | The metadata dict to be associated with the display data. | |
172 | """ |
|
172 | """ | |
173 | # We want to print because we want to always make sure we have a |
|
173 | # We want to print because we want to always make sure we have a | |
174 | # newline, even if all the prompt separators are ''. This is the |
|
174 | # newline, even if all the prompt separators are ''. This is the | |
175 | # standard IPython behavior. |
|
175 | # standard IPython behavior. | |
176 | result_repr = format_dict['text/plain'] |
|
176 | result_repr = format_dict['text/plain'] | |
177 | if '\n' in result_repr: |
|
177 | if '\n' in result_repr: | |
178 | # So that multi-line strings line up with the left column of |
|
178 | # So that multi-line strings line up with the left column of | |
179 | # the screen, instead of having the output prompt mess up |
|
179 | # the screen, instead of having the output prompt mess up | |
180 | # their first line. |
|
180 | # their first line. | |
181 | # We use the prompt template instead of the expanded prompt |
|
181 | # We use the prompt template instead of the expanded prompt | |
182 | # because the expansion may add ANSI escapes that will interfere |
|
182 | # because the expansion may add ANSI escapes that will interfere | |
183 | # with our ability to determine whether or not we should add |
|
183 | # with our ability to determine whether or not we should add | |
184 | # a newline. |
|
184 | # a newline. | |
185 | prompt_template = self.shell.prompt_manager.out_template |
|
185 | prompt_template = self.shell.prompt_manager.out_template | |
186 | if prompt_template and not prompt_template.endswith('\n'): |
|
186 | if prompt_template and not prompt_template.endswith('\n'): | |
187 | # But avoid extraneous empty lines. |
|
187 | # But avoid extraneous empty lines. | |
188 | result_repr = '\n' + result_repr |
|
188 | result_repr = '\n' + result_repr | |
189 |
|
189 | |||
190 | print(result_repr, file=io.stdout) |
|
190 | print(result_repr, file=io.stdout) | |
191 |
|
191 | |||
192 | def update_user_ns(self, result): |
|
192 | def update_user_ns(self, result): | |
193 | """Update user_ns with various things like _, __, _1, etc.""" |
|
193 | """Update user_ns with various things like _, __, _1, etc.""" | |
194 |
|
194 | |||
195 | # Avoid recursive reference when displaying _oh/Out |
|
195 | # Avoid recursive reference when displaying _oh/Out | |
196 | if result is not self.shell.user_ns['_oh']: |
|
196 | if result is not self.shell.user_ns['_oh']: | |
197 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: |
|
197 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: | |
198 | warn('Output cache limit (currently '+ |
|
198 | warn('Output cache limit (currently '+ | |
199 | repr(self.cache_size)+' entries) hit.\n' |
|
199 | repr(self.cache_size)+' entries) hit.\n' | |
200 | 'Flushing cache and resetting history counter...\n' |
|
200 | 'Flushing cache and resetting history counter...\n' | |
201 | 'The only history variables available will be _,__,___ and _1\n' |
|
201 | 'The only history variables available will be _,__,___ and _1\n' | |
202 | 'with the current result.') |
|
202 | 'with the current result.') | |
203 |
|
203 | |||
204 | self.flush() |
|
204 | self.flush() | |
205 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise |
|
205 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise | |
206 | # we cause buggy behavior for things like gettext). |
|
206 | # we cause buggy behavior for things like gettext). | |
207 |
|
207 | |||
208 | if '_' not in builtin_mod.__dict__: |
|
208 | if '_' not in builtin_mod.__dict__: | |
209 | self.___ = self.__ |
|
209 | self.___ = self.__ | |
210 | self.__ = self._ |
|
210 | self.__ = self._ | |
211 | self._ = result |
|
211 | self._ = result | |
212 | self.shell.push({'_':self._, |
|
212 | self.shell.push({'_':self._, | |
213 | '__':self.__, |
|
213 | '__':self.__, | |
214 | '___':self.___}, interactive=False) |
|
214 | '___':self.___}, interactive=False) | |
215 |
|
215 | |||
216 | # hackish access to top-level namespace to create _1,_2... dynamically |
|
216 | # hackish access to top-level namespace to create _1,_2... dynamically | |
217 | to_main = {} |
|
217 | to_main = {} | |
218 | if self.do_full_cache: |
|
218 | if self.do_full_cache: | |
219 | new_result = '_'+repr(self.prompt_count) |
|
219 | new_result = '_'+repr(self.prompt_count) | |
220 | to_main[new_result] = result |
|
220 | to_main[new_result] = result | |
221 | self.shell.push(to_main, interactive=False) |
|
221 | self.shell.push(to_main, interactive=False) | |
222 | self.shell.user_ns['_oh'][self.prompt_count] = result |
|
222 | self.shell.user_ns['_oh'][self.prompt_count] = result | |
223 |
|
223 | |||
224 | def log_output(self, format_dict): |
|
224 | def log_output(self, format_dict): | |
225 | """Log the output.""" |
|
225 | """Log the output.""" | |
226 | if self.shell.logger.log_output: |
|
226 | if self.shell.logger.log_output: | |
227 | self.shell.logger.log_write(format_dict['text/plain'], 'output') |
|
227 | self.shell.logger.log_write(format_dict['text/plain'], 'output') | |
228 | self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ |
|
228 | self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ | |
229 | format_dict['text/plain'] |
|
229 | format_dict['text/plain'] | |
230 |
|
230 | |||
231 | def finish_displayhook(self): |
|
231 | def finish_displayhook(self): | |
232 | """Finish up all displayhook activities.""" |
|
232 | """Finish up all displayhook activities.""" | |
233 | io.stdout.write(self.shell.separate_out2) |
|
233 | io.stdout.write(self.shell.separate_out2) | |
234 | io.stdout.flush() |
|
234 | io.stdout.flush() | |
235 |
|
235 | |||
236 | def __call__(self, result=None): |
|
236 | def __call__(self, result=None): | |
237 | """Printing with history cache management. |
|
237 | """Printing with history cache management. | |
238 |
|
238 | |||
239 | This is invoked everytime the interpreter needs to print, and is |
|
239 | This is invoked everytime the interpreter needs to print, and is | |
240 | activated by setting the variable sys.displayhook to it. |
|
240 | activated by setting the variable sys.displayhook to it. | |
241 | """ |
|
241 | """ | |
242 | self.check_for_underscore() |
|
242 | self.check_for_underscore() | |
243 | if result is not None and not self.quiet(): |
|
243 | if result is not None and not self.quiet(): | |
244 | # If _ipython_display_ is defined, use that to display this object. |
|
244 | # If _ipython_display_ is defined, use that to display this object. | |
245 |
display_method = getattr(result, '_ipython_display_' |
|
245 | display_method = _safe_get_formatter_method(result, '_ipython_display_') | |
246 | if display_method is not None: |
|
246 | if display_method is not None: | |
247 | try: |
|
247 | try: | |
248 | return display_method() |
|
248 | return display_method() | |
249 | except NotImplementedError: |
|
249 | except NotImplementedError: | |
250 | pass |
|
250 | pass | |
251 |
|
251 | |||
252 | self.start_displayhook() |
|
252 | self.start_displayhook() | |
253 | self.write_output_prompt() |
|
253 | self.write_output_prompt() | |
254 | format_dict, md_dict = self.compute_format_data(result) |
|
254 | format_dict, md_dict = self.compute_format_data(result) | |
255 | self.write_format_data(format_dict, md_dict) |
|
255 | self.write_format_data(format_dict, md_dict) | |
256 | self.update_user_ns(result) |
|
256 | self.update_user_ns(result) | |
257 | self.log_output(format_dict) |
|
257 | self.log_output(format_dict) | |
258 | self.finish_displayhook() |
|
258 | self.finish_displayhook() | |
259 |
|
259 | |||
260 | def flush(self): |
|
260 | def flush(self): | |
261 | if not self.do_full_cache: |
|
261 | if not self.do_full_cache: | |
262 | raise ValueError("You shouldn't have reached the cache flush " |
|
262 | raise ValueError("You shouldn't have reached the cache flush " | |
263 | "if full caching is not enabled!") |
|
263 | "if full caching is not enabled!") | |
264 | # delete auto-generated vars from global namespace |
|
264 | # delete auto-generated vars from global namespace | |
265 |
|
265 | |||
266 | for n in range(1,self.prompt_count + 1): |
|
266 | for n in range(1,self.prompt_count + 1): | |
267 | key = '_'+repr(n) |
|
267 | key = '_'+repr(n) | |
268 | try: |
|
268 | try: | |
269 | del self.shell.user_ns[key] |
|
269 | del self.shell.user_ns[key] | |
270 | except: pass |
|
270 | except: pass | |
271 | # In some embedded circumstances, the user_ns doesn't have the |
|
271 | # In some embedded circumstances, the user_ns doesn't have the | |
272 | # '_oh' key set up. |
|
272 | # '_oh' key set up. | |
273 | oh = self.shell.user_ns.get('_oh', None) |
|
273 | oh = self.shell.user_ns.get('_oh', None) | |
274 | if oh is not None: |
|
274 | if oh is not None: | |
275 | oh.clear() |
|
275 | oh.clear() | |
276 |
|
276 | |||
277 | # Release our own references to objects: |
|
277 | # Release our own references to objects: | |
278 | self._, self.__, self.___ = '', '', '' |
|
278 | self._, self.__, self.___ = '', '', '' | |
279 |
|
279 | |||
280 | if '_' not in builtin_mod.__dict__: |
|
280 | if '_' not in builtin_mod.__dict__: | |
281 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) |
|
281 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) | |
282 | import gc |
|
282 | import gc | |
283 | # TODO: Is this really needed? |
|
283 | # TODO: Is this really needed? | |
284 | # IronPython blocks here forever |
|
284 | # IronPython blocks here forever | |
285 | if sys.platform != "cli": |
|
285 | if sys.platform != "cli": | |
286 | gc.collect() |
|
286 | gc.collect() | |
287 |
|
287 |
@@ -1,875 +1,884 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 inspect |
|
28 | import inspect | |
29 | import sys |
|
29 | import sys | |
30 | import types |
|
30 | import types | |
31 | import warnings |
|
31 | import warnings | |
32 |
|
32 | |||
33 | from IPython.external.decorator import decorator |
|
33 | from IPython.external.decorator import decorator | |
34 |
|
34 | |||
35 | # Our own imports |
|
35 | # Our own imports | |
36 | from IPython.config.configurable import Configurable |
|
36 | from IPython.config.configurable import Configurable | |
37 | from IPython.lib import pretty |
|
37 | from IPython.lib import pretty | |
38 | from IPython.utils import io |
|
38 | from IPython.utils import io | |
39 | from IPython.utils.traitlets import ( |
|
39 | from IPython.utils.traitlets import ( | |
40 | Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, |
|
40 | Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, | |
41 | ) |
|
41 | ) | |
42 | from IPython.utils.warn import warn |
|
42 | from IPython.utils.warn import warn | |
43 | from IPython.utils.py3compat import ( |
|
43 | from IPython.utils.py3compat import ( | |
44 | unicode_to_str, with_metaclass, PY3, string_types, unicode_type, |
|
44 | unicode_to_str, with_metaclass, PY3, string_types, unicode_type, | |
45 | ) |
|
45 | ) | |
46 |
|
46 | |||
47 | if PY3: |
|
47 | if PY3: | |
48 | from io import StringIO |
|
48 | from io import StringIO | |
49 | else: |
|
49 | else: | |
50 | from StringIO import StringIO |
|
50 | from StringIO import StringIO | |
51 |
|
51 | |||
52 |
|
52 | |||
53 | #----------------------------------------------------------------------------- |
|
53 | #----------------------------------------------------------------------------- | |
54 | # The main DisplayFormatter class |
|
54 | # The main DisplayFormatter class | |
55 | #----------------------------------------------------------------------------- |
|
55 | #----------------------------------------------------------------------------- | |
56 |
|
56 | |||
57 |
|
57 | |||
58 | def _valid_formatter(f): |
|
58 | def _valid_formatter(f): | |
59 | """Return whether an object is a valid formatter |
|
59 | """Return whether an object is a valid formatter | |
60 |
|
60 | |||
61 | Cases checked: |
|
61 | Cases checked: | |
62 |
|
62 | |||
63 | - bound methods OK |
|
63 | - bound methods OK | |
64 | - unbound methods NO |
|
64 | - unbound methods NO | |
65 | - callable with zero args OK |
|
65 | - callable with zero args OK | |
66 | """ |
|
66 | """ | |
67 | if isinstance(f, type(str.find)): |
|
67 | if f is None: | |
|
68 | return False | |||
|
69 | elif isinstance(f, type(str.find)): | |||
68 | # unbound methods on compiled classes have type method_descriptor |
|
70 | # unbound methods on compiled classes have type method_descriptor | |
69 | return False |
|
71 | return False | |
70 | elif isinstance(f, types.BuiltinFunctionType): |
|
72 | elif isinstance(f, types.BuiltinFunctionType): | |
71 | # bound methods on compiled classes have type builtin_function |
|
73 | # bound methods on compiled classes have type builtin_function | |
72 | return True |
|
74 | return True | |
73 | elif callable(f): |
|
75 | elif callable(f): | |
74 | # anything that works with zero args should be okay |
|
76 | # anything that works with zero args should be okay | |
75 | try: |
|
77 | try: | |
76 | inspect.getcallargs(f) |
|
78 | inspect.getcallargs(f) | |
77 | except TypeError: |
|
79 | except TypeError: | |
78 | return False |
|
80 | return False | |
79 | else: |
|
81 | else: | |
80 | return True |
|
82 | return True | |
81 | return False |
|
83 | return False | |
82 |
|
84 | |||
|
85 | def _safe_get_formatter_method(obj, name): | |||
|
86 | """Safely get a formatter method""" | |||
|
87 | method = pretty._safe_getattr(obj, name, None) | |||
|
88 | # formatter methods must be bound | |||
|
89 | if _valid_formatter(method): | |||
|
90 | return method | |||
|
91 | ||||
|
92 | ||||
83 | class DisplayFormatter(Configurable): |
|
93 | class DisplayFormatter(Configurable): | |
84 |
|
94 | |||
85 | # When set to true only the default plain text formatter will be used. |
|
95 | # When set to true only the default plain text formatter will be used. | |
86 | plain_text_only = Bool(False, config=True) |
|
96 | plain_text_only = Bool(False, config=True) | |
87 | def _plain_text_only_changed(self, name, old, new): |
|
97 | def _plain_text_only_changed(self, name, old, new): | |
88 | warnings.warn("""DisplayFormatter.plain_text_only is deprecated. |
|
98 | warnings.warn("""DisplayFormatter.plain_text_only is deprecated. | |
89 |
|
99 | |||
90 | Use DisplayFormatter.active_types = ['text/plain'] |
|
100 | Use DisplayFormatter.active_types = ['text/plain'] | |
91 | for the same effect. |
|
101 | for the same effect. | |
92 | """, DeprecationWarning) |
|
102 | """, DeprecationWarning) | |
93 | if new: |
|
103 | if new: | |
94 | self.active_types = ['text/plain'] |
|
104 | self.active_types = ['text/plain'] | |
95 | else: |
|
105 | else: | |
96 | self.active_types = self.format_types |
|
106 | self.active_types = self.format_types | |
97 |
|
107 | |||
98 | active_types = List(Unicode, config=True, |
|
108 | active_types = List(Unicode, config=True, | |
99 | help="""List of currently active mime-types to display. |
|
109 | help="""List of currently active mime-types to display. | |
100 | You can use this to set a white-list for formats to display. |
|
110 | You can use this to set a white-list for formats to display. | |
101 |
|
111 | |||
102 | Most users will not need to change this value. |
|
112 | Most users will not need to change this value. | |
103 | """) |
|
113 | """) | |
104 | def _active_types_default(self): |
|
114 | def _active_types_default(self): | |
105 | return self.format_types |
|
115 | return self.format_types | |
106 |
|
116 | |||
107 | def _active_types_changed(self, name, old, new): |
|
117 | def _active_types_changed(self, name, old, new): | |
108 | for key, formatter in self.formatters.items(): |
|
118 | for key, formatter in self.formatters.items(): | |
109 | if key in new: |
|
119 | if key in new: | |
110 | formatter.enabled = True |
|
120 | formatter.enabled = True | |
111 | else: |
|
121 | else: | |
112 | formatter.enabled = False |
|
122 | formatter.enabled = False | |
113 |
|
123 | |||
114 | # A dict of formatter whose keys are format types (MIME types) and whose |
|
124 | # A dict of formatter whose keys are format types (MIME types) and whose | |
115 | # values are subclasses of BaseFormatter. |
|
125 | # values are subclasses of BaseFormatter. | |
116 | formatters = Dict() |
|
126 | formatters = Dict() | |
117 | def _formatters_default(self): |
|
127 | def _formatters_default(self): | |
118 | """Activate the default formatters.""" |
|
128 | """Activate the default formatters.""" | |
119 | formatter_classes = [ |
|
129 | formatter_classes = [ | |
120 | PlainTextFormatter, |
|
130 | PlainTextFormatter, | |
121 | HTMLFormatter, |
|
131 | HTMLFormatter, | |
122 | SVGFormatter, |
|
132 | SVGFormatter, | |
123 | PNGFormatter, |
|
133 | PNGFormatter, | |
124 | PDFFormatter, |
|
134 | PDFFormatter, | |
125 | JPEGFormatter, |
|
135 | JPEGFormatter, | |
126 | LatexFormatter, |
|
136 | LatexFormatter, | |
127 | JSONFormatter, |
|
137 | JSONFormatter, | |
128 | JavascriptFormatter |
|
138 | JavascriptFormatter | |
129 | ] |
|
139 | ] | |
130 | d = {} |
|
140 | d = {} | |
131 | for cls in formatter_classes: |
|
141 | for cls in formatter_classes: | |
132 | f = cls(parent=self) |
|
142 | f = cls(parent=self) | |
133 | d[f.format_type] = f |
|
143 | d[f.format_type] = f | |
134 | return d |
|
144 | return d | |
135 |
|
145 | |||
136 | def format(self, obj, include=None, exclude=None): |
|
146 | def format(self, obj, include=None, exclude=None): | |
137 | """Return a format data dict for an object. |
|
147 | """Return a format data dict for an object. | |
138 |
|
148 | |||
139 | By default all format types will be computed. |
|
149 | By default all format types will be computed. | |
140 |
|
150 | |||
141 | The following MIME types are currently implemented: |
|
151 | The following MIME types are currently implemented: | |
142 |
|
152 | |||
143 | * text/plain |
|
153 | * text/plain | |
144 | * text/html |
|
154 | * text/html | |
145 | * text/latex |
|
155 | * text/latex | |
146 | * application/json |
|
156 | * application/json | |
147 | * application/javascript |
|
157 | * application/javascript | |
148 | * application/pdf |
|
158 | * application/pdf | |
149 | * image/png |
|
159 | * image/png | |
150 | * image/jpeg |
|
160 | * image/jpeg | |
151 | * image/svg+xml |
|
161 | * image/svg+xml | |
152 |
|
162 | |||
153 | Parameters |
|
163 | Parameters | |
154 | ---------- |
|
164 | ---------- | |
155 | obj : object |
|
165 | obj : object | |
156 | The Python object whose format data will be computed. |
|
166 | The Python object whose format data will be computed. | |
157 | include : list or tuple, optional |
|
167 | include : list or tuple, optional | |
158 | A list of format type strings (MIME types) to include in the |
|
168 | A list of format type strings (MIME types) to include in the | |
159 | format data dict. If this is set *only* the format types included |
|
169 | format data dict. If this is set *only* the format types included | |
160 | in this list will be computed. |
|
170 | in this list will be computed. | |
161 | exclude : list or tuple, optional |
|
171 | exclude : list or tuple, optional | |
162 | A list of format type string (MIME types) to exclude in the format |
|
172 | A list of format type string (MIME types) to exclude in the format | |
163 | data dict. If this is set all format types will be computed, |
|
173 | data dict. If this is set all format types will be computed, | |
164 | except for those included in this argument. |
|
174 | except for those included in this argument. | |
165 |
|
175 | |||
166 | Returns |
|
176 | Returns | |
167 | ------- |
|
177 | ------- | |
168 | (format_dict, metadata_dict) : tuple of two dicts |
|
178 | (format_dict, metadata_dict) : tuple of two dicts | |
169 |
|
179 | |||
170 | format_dict is a dictionary of key/value pairs, one of each format that was |
|
180 | format_dict is a dictionary of key/value pairs, one of each format that was | |
171 | generated for the object. The keys are the format types, which |
|
181 | generated for the object. The keys are the format types, which | |
172 | will usually be MIME type strings and the values and JSON'able |
|
182 | will usually be MIME type strings and the values and JSON'able | |
173 | data structure containing the raw data for the representation in |
|
183 | data structure containing the raw data for the representation in | |
174 | that format. |
|
184 | that format. | |
175 |
|
185 | |||
176 | metadata_dict is a dictionary of metadata about each mime-type output. |
|
186 | metadata_dict is a dictionary of metadata about each mime-type output. | |
177 | Its keys will be a strict subset of the keys in format_dict. |
|
187 | Its keys will be a strict subset of the keys in format_dict. | |
178 | """ |
|
188 | """ | |
179 | format_dict = {} |
|
189 | format_dict = {} | |
180 | md_dict = {} |
|
190 | md_dict = {} | |
181 |
|
191 | |||
182 | for format_type, formatter in self.formatters.items(): |
|
192 | for format_type, formatter in self.formatters.items(): | |
183 | if include and format_type not in include: |
|
193 | if include and format_type not in include: | |
184 | continue |
|
194 | continue | |
185 | if exclude and format_type in exclude: |
|
195 | if exclude and format_type in exclude: | |
186 | continue |
|
196 | continue | |
187 |
|
197 | |||
188 | md = None |
|
198 | md = None | |
189 | try: |
|
199 | try: | |
190 | data = formatter(obj) |
|
200 | data = formatter(obj) | |
191 | except: |
|
201 | except: | |
192 | # FIXME: log the exception |
|
202 | # FIXME: log the exception | |
193 | raise |
|
203 | raise | |
194 |
|
204 | |||
195 | # formatters can return raw data or (data, metadata) |
|
205 | # formatters can return raw data or (data, metadata) | |
196 | if isinstance(data, tuple) and len(data) == 2: |
|
206 | if isinstance(data, tuple) and len(data) == 2: | |
197 | data, md = data |
|
207 | data, md = data | |
198 |
|
208 | |||
199 | if data is not None: |
|
209 | if data is not None: | |
200 | format_dict[format_type] = data |
|
210 | format_dict[format_type] = data | |
201 | if md is not None: |
|
211 | if md is not None: | |
202 | md_dict[format_type] = md |
|
212 | md_dict[format_type] = md | |
203 |
|
213 | |||
204 | return format_dict, md_dict |
|
214 | return format_dict, md_dict | |
205 |
|
215 | |||
206 | @property |
|
216 | @property | |
207 | def format_types(self): |
|
217 | def format_types(self): | |
208 | """Return the format types (MIME types) of the active formatters.""" |
|
218 | """Return the format types (MIME types) of the active formatters.""" | |
209 | return list(self.formatters.keys()) |
|
219 | return list(self.formatters.keys()) | |
210 |
|
220 | |||
211 |
|
221 | |||
212 | #----------------------------------------------------------------------------- |
|
222 | #----------------------------------------------------------------------------- | |
213 | # Formatters for specific format types (text, html, svg, etc.) |
|
223 | # Formatters for specific format types (text, html, svg, etc.) | |
214 | #----------------------------------------------------------------------------- |
|
224 | #----------------------------------------------------------------------------- | |
215 |
|
225 | |||
216 | class FormatterWarning(UserWarning): |
|
226 | class FormatterWarning(UserWarning): | |
217 | """Warning class for errors in formatters""" |
|
227 | """Warning class for errors in formatters""" | |
218 |
|
228 | |||
219 | @decorator |
|
229 | @decorator | |
220 | def warn_format_error(method, self, *args, **kwargs): |
|
230 | def warn_format_error(method, self, *args, **kwargs): | |
221 | """decorator for warning on failed format call""" |
|
231 | """decorator for warning on failed format call""" | |
222 | try: |
|
232 | try: | |
223 | r = method(self, *args, **kwargs) |
|
233 | r = method(self, *args, **kwargs) | |
224 | except NotImplementedError as e: |
|
234 | except NotImplementedError as e: | |
225 | # don't warn on NotImplementedErrors |
|
235 | # don't warn on NotImplementedErrors | |
226 | return None |
|
236 | return None | |
227 | except Exception as e: |
|
237 | except Exception as e: | |
228 | warnings.warn("Exception in %s formatter: %s" % (self.format_type, e), |
|
238 | warnings.warn("Exception in %s formatter: %s" % (self.format_type, e), | |
229 | FormatterWarning, |
|
239 | FormatterWarning, | |
230 | ) |
|
240 | ) | |
231 | return None |
|
241 | return None | |
232 | if r is None or isinstance(r, self._return_type) or \ |
|
242 | if r is None or isinstance(r, self._return_type) or \ | |
233 | (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)): |
|
243 | (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)): | |
234 | return r |
|
244 | return r | |
235 | else: |
|
245 | else: | |
236 | warnings.warn( |
|
246 | warnings.warn( | |
237 | "%s formatter returned invalid type %s (expected %s) for object: %s" % \ |
|
247 | "%s formatter returned invalid type %s (expected %s) for object: %s" % \ | |
238 | (self.format_type, type(r), self._return_type, pretty._safe_repr(args[0])), |
|
248 | (self.format_type, type(r), self._return_type, pretty._safe_repr(args[0])), | |
239 | FormatterWarning |
|
249 | FormatterWarning | |
240 | ) |
|
250 | ) | |
241 |
|
251 | |||
242 |
|
252 | |||
243 | class FormatterABC(with_metaclass(abc.ABCMeta, object)): |
|
253 | class FormatterABC(with_metaclass(abc.ABCMeta, object)): | |
244 | """ Abstract base class for Formatters. |
|
254 | """ Abstract base class for Formatters. | |
245 |
|
255 | |||
246 | A formatter is a callable class that is responsible for computing the |
|
256 | A formatter is a callable class that is responsible for computing the | |
247 | raw format data for a particular format type (MIME type). For example, |
|
257 | raw format data for a particular format type (MIME type). For example, | |
248 | an HTML formatter would have a format type of `text/html` and would return |
|
258 | an HTML formatter would have a format type of `text/html` and would return | |
249 | the HTML representation of the object when called. |
|
259 | the HTML representation of the object when called. | |
250 | """ |
|
260 | """ | |
251 |
|
261 | |||
252 | # The format type of the data returned, usually a MIME type. |
|
262 | # The format type of the data returned, usually a MIME type. | |
253 | format_type = 'text/plain' |
|
263 | format_type = 'text/plain' | |
254 |
|
264 | |||
255 | # Is the formatter enabled... |
|
265 | # Is the formatter enabled... | |
256 | enabled = True |
|
266 | enabled = True | |
257 |
|
267 | |||
258 | @abc.abstractmethod |
|
268 | @abc.abstractmethod | |
259 | @warn_format_error |
|
269 | @warn_format_error | |
260 | def __call__(self, obj): |
|
270 | def __call__(self, obj): | |
261 | """Return a JSON'able representation of the object. |
|
271 | """Return a JSON'able representation of the object. | |
262 |
|
272 | |||
263 | If the object cannot be formatted by this formatter, |
|
273 | If the object cannot be formatted by this formatter, | |
264 | warn and return None. |
|
274 | warn and return None. | |
265 | """ |
|
275 | """ | |
266 | return repr(obj) |
|
276 | return repr(obj) | |
267 |
|
277 | |||
268 |
|
278 | |||
269 | def _mod_name_key(typ): |
|
279 | def _mod_name_key(typ): | |
270 | """Return a (__module__, __name__) tuple for a type. |
|
280 | """Return a (__module__, __name__) tuple for a type. | |
271 |
|
281 | |||
272 | Used as key in Formatter.deferred_printers. |
|
282 | Used as key in Formatter.deferred_printers. | |
273 | """ |
|
283 | """ | |
274 | module = getattr(typ, '__module__', None) |
|
284 | module = getattr(typ, '__module__', None) | |
275 | name = getattr(typ, '__name__', None) |
|
285 | name = getattr(typ, '__name__', None) | |
276 | return (module, name) |
|
286 | return (module, name) | |
277 |
|
287 | |||
278 |
|
288 | |||
279 | def _get_type(obj): |
|
289 | def _get_type(obj): | |
280 | """Return the type of an instance (old and new-style)""" |
|
290 | """Return the type of an instance (old and new-style)""" | |
281 | return getattr(obj, '__class__', None) or type(obj) |
|
291 | return getattr(obj, '__class__', None) or type(obj) | |
282 |
|
292 | |||
283 | _raise_key_error = object() |
|
293 | _raise_key_error = object() | |
284 |
|
294 | |||
285 |
|
295 | |||
286 | class BaseFormatter(Configurable): |
|
296 | class BaseFormatter(Configurable): | |
287 | """A base formatter class that is configurable. |
|
297 | """A base formatter class that is configurable. | |
288 |
|
298 | |||
289 | This formatter should usually be used as the base class of all formatters. |
|
299 | This formatter should usually be used as the base class of all formatters. | |
290 | It is a traited :class:`Configurable` class and includes an extensible |
|
300 | It is a traited :class:`Configurable` class and includes an extensible | |
291 | API for users to determine how their objects are formatted. The following |
|
301 | API for users to determine how their objects are formatted. The following | |
292 | logic is used to find a function to format an given object. |
|
302 | logic is used to find a function to format an given object. | |
293 |
|
303 | |||
294 | 1. The object is introspected to see if it has a method with the name |
|
304 | 1. The object is introspected to see if it has a method with the name | |
295 | :attr:`print_method`. If is does, that object is passed to that method |
|
305 | :attr:`print_method`. If is does, that object is passed to that method | |
296 | for formatting. |
|
306 | for formatting. | |
297 | 2. If no print method is found, three internal dictionaries are consulted |
|
307 | 2. If no print method is found, three internal dictionaries are consulted | |
298 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` |
|
308 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` | |
299 | and :attr:`deferred_printers`. |
|
309 | and :attr:`deferred_printers`. | |
300 |
|
310 | |||
301 | Users should use these dictionaries to register functions that will be |
|
311 | Users should use these dictionaries to register functions that will be | |
302 | used to compute the format data for their objects (if those objects don't |
|
312 | used to compute the format data for their objects (if those objects don't | |
303 | have the special print methods). The easiest way of using these |
|
313 | have the special print methods). The easiest way of using these | |
304 | dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` |
|
314 | dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` | |
305 | methods. |
|
315 | methods. | |
306 |
|
316 | |||
307 | If no function/callable is found to compute the format data, ``None`` is |
|
317 | If no function/callable is found to compute the format data, ``None`` is | |
308 | returned and this format type is not used. |
|
318 | returned and this format type is not used. | |
309 | """ |
|
319 | """ | |
310 |
|
320 | |||
311 | format_type = Unicode('text/plain') |
|
321 | format_type = Unicode('text/plain') | |
312 | _return_type = string_types |
|
322 | _return_type = string_types | |
313 |
|
323 | |||
314 | enabled = Bool(True, config=True) |
|
324 | enabled = Bool(True, config=True) | |
315 |
|
325 | |||
316 | print_method = ObjectName('__repr__') |
|
326 | print_method = ObjectName('__repr__') | |
317 |
|
327 | |||
318 | # The singleton printers. |
|
328 | # The singleton printers. | |
319 | # Maps the IDs of the builtin singleton objects to the format functions. |
|
329 | # Maps the IDs of the builtin singleton objects to the format functions. | |
320 | singleton_printers = Dict(config=True) |
|
330 | singleton_printers = Dict(config=True) | |
321 |
|
331 | |||
322 | # The type-specific printers. |
|
332 | # The type-specific printers. | |
323 | # Map type objects to the format functions. |
|
333 | # Map type objects to the format functions. | |
324 | type_printers = Dict(config=True) |
|
334 | type_printers = Dict(config=True) | |
325 |
|
335 | |||
326 | # The deferred-import type-specific printers. |
|
336 | # The deferred-import type-specific printers. | |
327 | # Map (modulename, classname) pairs to the format functions. |
|
337 | # Map (modulename, classname) pairs to the format functions. | |
328 | deferred_printers = Dict(config=True) |
|
338 | deferred_printers = Dict(config=True) | |
329 |
|
339 | |||
330 | @warn_format_error |
|
340 | @warn_format_error | |
331 | def __call__(self, obj): |
|
341 | def __call__(self, obj): | |
332 | """Compute the format for an object.""" |
|
342 | """Compute the format for an object.""" | |
333 | if self.enabled: |
|
343 | if self.enabled: | |
334 | # lookup registered printer |
|
344 | # lookup registered printer | |
335 | try: |
|
345 | try: | |
336 | printer = self.lookup(obj) |
|
346 | printer = self.lookup(obj) | |
337 | except KeyError: |
|
347 | except KeyError: | |
338 | pass |
|
348 | pass | |
339 | else: |
|
349 | else: | |
340 | return printer(obj) |
|
350 | return printer(obj) | |
341 | # Finally look for special method names |
|
351 | # Finally look for special method names | |
342 |
method = |
|
352 | method = _safe_get_formatter_method(obj, self.print_method) | |
343 | # print_method must be a bound method: |
|
353 | if method is not None: | |
344 | if _valid_formatter(method): |
|
|||
345 | return method() |
|
354 | return method() | |
346 | return None |
|
355 | return None | |
347 | else: |
|
356 | else: | |
348 | return None |
|
357 | return None | |
349 |
|
358 | |||
350 | def __contains__(self, typ): |
|
359 | def __contains__(self, typ): | |
351 | """map in to lookup_by_type""" |
|
360 | """map in to lookup_by_type""" | |
352 | try: |
|
361 | try: | |
353 | self.lookup_by_type(typ) |
|
362 | self.lookup_by_type(typ) | |
354 | except KeyError: |
|
363 | except KeyError: | |
355 | return False |
|
364 | return False | |
356 | else: |
|
365 | else: | |
357 | return True |
|
366 | return True | |
358 |
|
367 | |||
359 | def lookup(self, obj): |
|
368 | def lookup(self, obj): | |
360 | """Look up the formatter for a given instance. |
|
369 | """Look up the formatter for a given instance. | |
361 |
|
370 | |||
362 | Parameters |
|
371 | Parameters | |
363 | ---------- |
|
372 | ---------- | |
364 | obj : object instance |
|
373 | obj : object instance | |
365 |
|
374 | |||
366 | Returns |
|
375 | Returns | |
367 | ------- |
|
376 | ------- | |
368 | f : callable |
|
377 | f : callable | |
369 | The registered formatting callable for the type. |
|
378 | The registered formatting callable for the type. | |
370 |
|
379 | |||
371 | Raises |
|
380 | Raises | |
372 | ------ |
|
381 | ------ | |
373 | KeyError if the type has not been registered. |
|
382 | KeyError if the type has not been registered. | |
374 | """ |
|
383 | """ | |
375 | # look for singleton first |
|
384 | # look for singleton first | |
376 | obj_id = id(obj) |
|
385 | obj_id = id(obj) | |
377 | if obj_id in self.singleton_printers: |
|
386 | if obj_id in self.singleton_printers: | |
378 | return self.singleton_printers[obj_id] |
|
387 | return self.singleton_printers[obj_id] | |
379 | # then lookup by type |
|
388 | # then lookup by type | |
380 | return self.lookup_by_type(_get_type(obj)) |
|
389 | return self.lookup_by_type(_get_type(obj)) | |
381 |
|
390 | |||
382 | def lookup_by_type(self, typ): |
|
391 | def lookup_by_type(self, typ): | |
383 | """Look up the registered formatter for a type. |
|
392 | """Look up the registered formatter for a type. | |
384 |
|
393 | |||
385 | Parameters |
|
394 | Parameters | |
386 | ---------- |
|
395 | ---------- | |
387 | typ : type or '__module__.__name__' string for a type |
|
396 | typ : type or '__module__.__name__' string for a type | |
388 |
|
397 | |||
389 | Returns |
|
398 | Returns | |
390 | ------- |
|
399 | ------- | |
391 | f : callable |
|
400 | f : callable | |
392 | The registered formatting callable for the type. |
|
401 | The registered formatting callable for the type. | |
393 |
|
402 | |||
394 | Raises |
|
403 | Raises | |
395 | ------ |
|
404 | ------ | |
396 | KeyError if the type has not been registered. |
|
405 | KeyError if the type has not been registered. | |
397 | """ |
|
406 | """ | |
398 | if isinstance(typ, string_types): |
|
407 | if isinstance(typ, string_types): | |
399 | typ_key = tuple(typ.rsplit('.',1)) |
|
408 | typ_key = tuple(typ.rsplit('.',1)) | |
400 | if typ_key not in self.deferred_printers: |
|
409 | if typ_key not in self.deferred_printers: | |
401 | # We may have it cached in the type map. We will have to |
|
410 | # We may have it cached in the type map. We will have to | |
402 | # iterate over all of the types to check. |
|
411 | # iterate over all of the types to check. | |
403 | for cls in self.type_printers: |
|
412 | for cls in self.type_printers: | |
404 | if _mod_name_key(cls) == typ_key: |
|
413 | if _mod_name_key(cls) == typ_key: | |
405 | return self.type_printers[cls] |
|
414 | return self.type_printers[cls] | |
406 | else: |
|
415 | else: | |
407 | return self.deferred_printers[typ_key] |
|
416 | return self.deferred_printers[typ_key] | |
408 | else: |
|
417 | else: | |
409 | for cls in pretty._get_mro(typ): |
|
418 | for cls in pretty._get_mro(typ): | |
410 | if cls in self.type_printers or self._in_deferred_types(cls): |
|
419 | if cls in self.type_printers or self._in_deferred_types(cls): | |
411 | return self.type_printers[cls] |
|
420 | return self.type_printers[cls] | |
412 |
|
421 | |||
413 | # If we have reached here, the lookup failed. |
|
422 | # If we have reached here, the lookup failed. | |
414 | raise KeyError("No registered printer for {0!r}".format(typ)) |
|
423 | raise KeyError("No registered printer for {0!r}".format(typ)) | |
415 |
|
424 | |||
416 | def for_type(self, typ, func=None): |
|
425 | def for_type(self, typ, func=None): | |
417 | """Add a format function for a given type. |
|
426 | """Add a format function for a given type. | |
418 |
|
427 | |||
419 | Parameters |
|
428 | Parameters | |
420 | ----------- |
|
429 | ----------- | |
421 | typ : type or '__module__.__name__' string for a type |
|
430 | typ : type or '__module__.__name__' string for a type | |
422 | The class of the object that will be formatted using `func`. |
|
431 | The class of the object that will be formatted using `func`. | |
423 | func : callable |
|
432 | func : callable | |
424 | A callable for computing the format data. |
|
433 | A callable for computing the format data. | |
425 | `func` will be called with the object to be formatted, |
|
434 | `func` will be called with the object to be formatted, | |
426 | and will return the raw data in this formatter's format. |
|
435 | and will return the raw data in this formatter's format. | |
427 | Subclasses may use a different call signature for the |
|
436 | Subclasses may use a different call signature for the | |
428 | `func` argument. |
|
437 | `func` argument. | |
429 |
|
438 | |||
430 | If `func` is None or not specified, there will be no change, |
|
439 | If `func` is None or not specified, there will be no change, | |
431 | only returning the current value. |
|
440 | only returning the current value. | |
432 |
|
441 | |||
433 | Returns |
|
442 | Returns | |
434 | ------- |
|
443 | ------- | |
435 | oldfunc : callable |
|
444 | oldfunc : callable | |
436 | The currently registered callable. |
|
445 | The currently registered callable. | |
437 | If you are registering a new formatter, |
|
446 | If you are registering a new formatter, | |
438 | this will be the previous value (to enable restoring later). |
|
447 | this will be the previous value (to enable restoring later). | |
439 | """ |
|
448 | """ | |
440 | # if string given, interpret as 'pkg.module.class_name' |
|
449 | # if string given, interpret as 'pkg.module.class_name' | |
441 | if isinstance(typ, string_types): |
|
450 | if isinstance(typ, string_types): | |
442 | type_module, type_name = typ.rsplit('.', 1) |
|
451 | type_module, type_name = typ.rsplit('.', 1) | |
443 | return self.for_type_by_name(type_module, type_name, func) |
|
452 | return self.for_type_by_name(type_module, type_name, func) | |
444 |
|
453 | |||
445 | try: |
|
454 | try: | |
446 | oldfunc = self.lookup_by_type(typ) |
|
455 | oldfunc = self.lookup_by_type(typ) | |
447 | except KeyError: |
|
456 | except KeyError: | |
448 | oldfunc = None |
|
457 | oldfunc = None | |
449 |
|
458 | |||
450 | if func is not None: |
|
459 | if func is not None: | |
451 | self.type_printers[typ] = func |
|
460 | self.type_printers[typ] = func | |
452 |
|
461 | |||
453 | return oldfunc |
|
462 | return oldfunc | |
454 |
|
463 | |||
455 | def for_type_by_name(self, type_module, type_name, func=None): |
|
464 | def for_type_by_name(self, type_module, type_name, func=None): | |
456 | """Add a format function for a type specified by the full dotted |
|
465 | """Add a format function for a type specified by the full dotted | |
457 | module and name of the type, rather than the type of the object. |
|
466 | module and name of the type, rather than the type of the object. | |
458 |
|
467 | |||
459 | Parameters |
|
468 | Parameters | |
460 | ---------- |
|
469 | ---------- | |
461 | type_module : str |
|
470 | type_module : str | |
462 | The full dotted name of the module the type is defined in, like |
|
471 | The full dotted name of the module the type is defined in, like | |
463 | ``numpy``. |
|
472 | ``numpy``. | |
464 | type_name : str |
|
473 | type_name : str | |
465 | The name of the type (the class name), like ``dtype`` |
|
474 | The name of the type (the class name), like ``dtype`` | |
466 | func : callable |
|
475 | func : callable | |
467 | A callable for computing the format data. |
|
476 | A callable for computing the format data. | |
468 | `func` will be called with the object to be formatted, |
|
477 | `func` will be called with the object to be formatted, | |
469 | and will return the raw data in this formatter's format. |
|
478 | and will return the raw data in this formatter's format. | |
470 | Subclasses may use a different call signature for the |
|
479 | Subclasses may use a different call signature for the | |
471 | `func` argument. |
|
480 | `func` argument. | |
472 |
|
481 | |||
473 | If `func` is None or unspecified, there will be no change, |
|
482 | If `func` is None or unspecified, there will be no change, | |
474 | only returning the current value. |
|
483 | only returning the current value. | |
475 |
|
484 | |||
476 | Returns |
|
485 | Returns | |
477 | ------- |
|
486 | ------- | |
478 | oldfunc : callable |
|
487 | oldfunc : callable | |
479 | The currently registered callable. |
|
488 | The currently registered callable. | |
480 | If you are registering a new formatter, |
|
489 | If you are registering a new formatter, | |
481 | this will be the previous value (to enable restoring later). |
|
490 | this will be the previous value (to enable restoring later). | |
482 | """ |
|
491 | """ | |
483 | key = (type_module, type_name) |
|
492 | key = (type_module, type_name) | |
484 |
|
493 | |||
485 | try: |
|
494 | try: | |
486 | oldfunc = self.lookup_by_type("%s.%s" % key) |
|
495 | oldfunc = self.lookup_by_type("%s.%s" % key) | |
487 | except KeyError: |
|
496 | except KeyError: | |
488 | oldfunc = None |
|
497 | oldfunc = None | |
489 |
|
498 | |||
490 | if func is not None: |
|
499 | if func is not None: | |
491 | self.deferred_printers[key] = func |
|
500 | self.deferred_printers[key] = func | |
492 | return oldfunc |
|
501 | return oldfunc | |
493 |
|
502 | |||
494 | def pop(self, typ, default=_raise_key_error): |
|
503 | def pop(self, typ, default=_raise_key_error): | |
495 | """Pop a formatter for the given type. |
|
504 | """Pop a formatter for the given type. | |
496 |
|
505 | |||
497 | Parameters |
|
506 | Parameters | |
498 | ---------- |
|
507 | ---------- | |
499 | typ : type or '__module__.__name__' string for a type |
|
508 | typ : type or '__module__.__name__' string for a type | |
500 | default : object |
|
509 | default : object | |
501 | value to be returned if no formatter is registered for typ. |
|
510 | value to be returned if no formatter is registered for typ. | |
502 |
|
511 | |||
503 | Returns |
|
512 | Returns | |
504 | ------- |
|
513 | ------- | |
505 | obj : object |
|
514 | obj : object | |
506 | The last registered object for the type. |
|
515 | The last registered object for the type. | |
507 |
|
516 | |||
508 | Raises |
|
517 | Raises | |
509 | ------ |
|
518 | ------ | |
510 | KeyError if the type is not registered and default is not specified. |
|
519 | KeyError if the type is not registered and default is not specified. | |
511 | """ |
|
520 | """ | |
512 |
|
521 | |||
513 | if isinstance(typ, string_types): |
|
522 | if isinstance(typ, string_types): | |
514 | typ_key = tuple(typ.rsplit('.',1)) |
|
523 | typ_key = tuple(typ.rsplit('.',1)) | |
515 | if typ_key not in self.deferred_printers: |
|
524 | if typ_key not in self.deferred_printers: | |
516 | # We may have it cached in the type map. We will have to |
|
525 | # We may have it cached in the type map. We will have to | |
517 | # iterate over all of the types to check. |
|
526 | # iterate over all of the types to check. | |
518 | for cls in self.type_printers: |
|
527 | for cls in self.type_printers: | |
519 | if _mod_name_key(cls) == typ_key: |
|
528 | if _mod_name_key(cls) == typ_key: | |
520 | old = self.type_printers.pop(cls) |
|
529 | old = self.type_printers.pop(cls) | |
521 | break |
|
530 | break | |
522 | else: |
|
531 | else: | |
523 | old = default |
|
532 | old = default | |
524 | else: |
|
533 | else: | |
525 | old = self.deferred_printers.pop(typ_key) |
|
534 | old = self.deferred_printers.pop(typ_key) | |
526 | else: |
|
535 | else: | |
527 | if typ in self.type_printers: |
|
536 | if typ in self.type_printers: | |
528 | old = self.type_printers.pop(typ) |
|
537 | old = self.type_printers.pop(typ) | |
529 | else: |
|
538 | else: | |
530 | old = self.deferred_printers.pop(_mod_name_key(typ), default) |
|
539 | old = self.deferred_printers.pop(_mod_name_key(typ), default) | |
531 | if old is _raise_key_error: |
|
540 | if old is _raise_key_error: | |
532 | raise KeyError("No registered value for {0!r}".format(typ)) |
|
541 | raise KeyError("No registered value for {0!r}".format(typ)) | |
533 | return old |
|
542 | return old | |
534 |
|
543 | |||
535 | def _in_deferred_types(self, cls): |
|
544 | def _in_deferred_types(self, cls): | |
536 | """ |
|
545 | """ | |
537 | Check if the given class is specified in the deferred type registry. |
|
546 | Check if the given class is specified in the deferred type registry. | |
538 |
|
547 | |||
539 | Successful matches will be moved to the regular type registry for future use. |
|
548 | Successful matches will be moved to the regular type registry for future use. | |
540 | """ |
|
549 | """ | |
541 | mod = getattr(cls, '__module__', None) |
|
550 | mod = getattr(cls, '__module__', None) | |
542 | name = getattr(cls, '__name__', None) |
|
551 | name = getattr(cls, '__name__', None) | |
543 | key = (mod, name) |
|
552 | key = (mod, name) | |
544 | if key in self.deferred_printers: |
|
553 | if key in self.deferred_printers: | |
545 | # Move the printer over to the regular registry. |
|
554 | # Move the printer over to the regular registry. | |
546 | printer = self.deferred_printers.pop(key) |
|
555 | printer = self.deferred_printers.pop(key) | |
547 | self.type_printers[cls] = printer |
|
556 | self.type_printers[cls] = printer | |
548 | return True |
|
557 | return True | |
549 | return False |
|
558 | return False | |
550 |
|
559 | |||
551 |
|
560 | |||
552 | class PlainTextFormatter(BaseFormatter): |
|
561 | class PlainTextFormatter(BaseFormatter): | |
553 | """The default pretty-printer. |
|
562 | """The default pretty-printer. | |
554 |
|
563 | |||
555 | This uses :mod:`IPython.lib.pretty` to compute the format data of |
|
564 | This uses :mod:`IPython.lib.pretty` to compute the format data of | |
556 | the object. If the object cannot be pretty printed, :func:`repr` is used. |
|
565 | the object. If the object cannot be pretty printed, :func:`repr` is used. | |
557 | See the documentation of :mod:`IPython.lib.pretty` for details on |
|
566 | See the documentation of :mod:`IPython.lib.pretty` for details on | |
558 | how to write pretty printers. Here is a simple example:: |
|
567 | how to write pretty printers. Here is a simple example:: | |
559 |
|
568 | |||
560 | def dtype_pprinter(obj, p, cycle): |
|
569 | def dtype_pprinter(obj, p, cycle): | |
561 | if cycle: |
|
570 | if cycle: | |
562 | return p.text('dtype(...)') |
|
571 | return p.text('dtype(...)') | |
563 | if hasattr(obj, 'fields'): |
|
572 | if hasattr(obj, 'fields'): | |
564 | if obj.fields is None: |
|
573 | if obj.fields is None: | |
565 | p.text(repr(obj)) |
|
574 | p.text(repr(obj)) | |
566 | else: |
|
575 | else: | |
567 | p.begin_group(7, 'dtype([') |
|
576 | p.begin_group(7, 'dtype([') | |
568 | for i, field in enumerate(obj.descr): |
|
577 | for i, field in enumerate(obj.descr): | |
569 | if i > 0: |
|
578 | if i > 0: | |
570 | p.text(',') |
|
579 | p.text(',') | |
571 | p.breakable() |
|
580 | p.breakable() | |
572 | p.pretty(field) |
|
581 | p.pretty(field) | |
573 | p.end_group(7, '])') |
|
582 | p.end_group(7, '])') | |
574 | """ |
|
583 | """ | |
575 |
|
584 | |||
576 | # The format type of data returned. |
|
585 | # The format type of data returned. | |
577 | format_type = Unicode('text/plain') |
|
586 | format_type = Unicode('text/plain') | |
578 |
|
587 | |||
579 | # This subclass ignores this attribute as it always need to return |
|
588 | # This subclass ignores this attribute as it always need to return | |
580 | # something. |
|
589 | # something. | |
581 | enabled = Bool(True, config=False) |
|
590 | enabled = Bool(True, config=False) | |
582 |
|
591 | |||
583 | # Look for a _repr_pretty_ methods to use for pretty printing. |
|
592 | # Look for a _repr_pretty_ methods to use for pretty printing. | |
584 | print_method = ObjectName('_repr_pretty_') |
|
593 | print_method = ObjectName('_repr_pretty_') | |
585 |
|
594 | |||
586 | # Whether to pretty-print or not. |
|
595 | # Whether to pretty-print or not. | |
587 | pprint = Bool(True, config=True) |
|
596 | pprint = Bool(True, config=True) | |
588 |
|
597 | |||
589 | # Whether to be verbose or not. |
|
598 | # Whether to be verbose or not. | |
590 | verbose = Bool(False, config=True) |
|
599 | verbose = Bool(False, config=True) | |
591 |
|
600 | |||
592 | # The maximum width. |
|
601 | # The maximum width. | |
593 | max_width = Integer(79, config=True) |
|
602 | max_width = Integer(79, config=True) | |
594 |
|
603 | |||
595 | # The newline character. |
|
604 | # The newline character. | |
596 | newline = Unicode('\n', config=True) |
|
605 | newline = Unicode('\n', config=True) | |
597 |
|
606 | |||
598 | # format-string for pprinting floats |
|
607 | # format-string for pprinting floats | |
599 | float_format = Unicode('%r') |
|
608 | float_format = Unicode('%r') | |
600 | # setter for float precision, either int or direct format-string |
|
609 | # setter for float precision, either int or direct format-string | |
601 | float_precision = CUnicode('', config=True) |
|
610 | float_precision = CUnicode('', config=True) | |
602 |
|
611 | |||
603 | def _float_precision_changed(self, name, old, new): |
|
612 | def _float_precision_changed(self, name, old, new): | |
604 | """float_precision changed, set float_format accordingly. |
|
613 | """float_precision changed, set float_format accordingly. | |
605 |
|
614 | |||
606 | float_precision can be set by int or str. |
|
615 | float_precision can be set by int or str. | |
607 | This will set float_format, after interpreting input. |
|
616 | This will set float_format, after interpreting input. | |
608 | If numpy has been imported, numpy print precision will also be set. |
|
617 | If numpy has been imported, numpy print precision will also be set. | |
609 |
|
618 | |||
610 | integer `n` sets format to '%.nf', otherwise, format set directly. |
|
619 | integer `n` sets format to '%.nf', otherwise, format set directly. | |
611 |
|
620 | |||
612 | An empty string returns to defaults (repr for float, 8 for numpy). |
|
621 | An empty string returns to defaults (repr for float, 8 for numpy). | |
613 |
|
622 | |||
614 | This parameter can be set via the '%precision' magic. |
|
623 | This parameter can be set via the '%precision' magic. | |
615 | """ |
|
624 | """ | |
616 |
|
625 | |||
617 | if '%' in new: |
|
626 | if '%' in new: | |
618 | # got explicit format string |
|
627 | # got explicit format string | |
619 | fmt = new |
|
628 | fmt = new | |
620 | try: |
|
629 | try: | |
621 | fmt%3.14159 |
|
630 | fmt%3.14159 | |
622 | except Exception: |
|
631 | except Exception: | |
623 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
632 | raise ValueError("Precision must be int or format string, not %r"%new) | |
624 | elif new: |
|
633 | elif new: | |
625 | # otherwise, should be an int |
|
634 | # otherwise, should be an int | |
626 | try: |
|
635 | try: | |
627 | i = int(new) |
|
636 | i = int(new) | |
628 | assert i >= 0 |
|
637 | assert i >= 0 | |
629 | except ValueError: |
|
638 | except ValueError: | |
630 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
639 | raise ValueError("Precision must be int or format string, not %r"%new) | |
631 | except AssertionError: |
|
640 | except AssertionError: | |
632 | raise ValueError("int precision must be non-negative, not %r"%i) |
|
641 | raise ValueError("int precision must be non-negative, not %r"%i) | |
633 |
|
642 | |||
634 | fmt = '%%.%if'%i |
|
643 | fmt = '%%.%if'%i | |
635 | if 'numpy' in sys.modules: |
|
644 | if 'numpy' in sys.modules: | |
636 | # set numpy precision if it has been imported |
|
645 | # set numpy precision if it has been imported | |
637 | import numpy |
|
646 | import numpy | |
638 | numpy.set_printoptions(precision=i) |
|
647 | numpy.set_printoptions(precision=i) | |
639 | else: |
|
648 | else: | |
640 | # default back to repr |
|
649 | # default back to repr | |
641 | fmt = '%r' |
|
650 | fmt = '%r' | |
642 | if 'numpy' in sys.modules: |
|
651 | if 'numpy' in sys.modules: | |
643 | import numpy |
|
652 | import numpy | |
644 | # numpy default is 8 |
|
653 | # numpy default is 8 | |
645 | numpy.set_printoptions(precision=8) |
|
654 | numpy.set_printoptions(precision=8) | |
646 | self.float_format = fmt |
|
655 | self.float_format = fmt | |
647 |
|
656 | |||
648 | # Use the default pretty printers from IPython.lib.pretty. |
|
657 | # Use the default pretty printers from IPython.lib.pretty. | |
649 | def _singleton_printers_default(self): |
|
658 | def _singleton_printers_default(self): | |
650 | return pretty._singleton_pprinters.copy() |
|
659 | return pretty._singleton_pprinters.copy() | |
651 |
|
660 | |||
652 | def _type_printers_default(self): |
|
661 | def _type_printers_default(self): | |
653 | d = pretty._type_pprinters.copy() |
|
662 | d = pretty._type_pprinters.copy() | |
654 | d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) |
|
663 | d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) | |
655 | return d |
|
664 | return d | |
656 |
|
665 | |||
657 | def _deferred_printers_default(self): |
|
666 | def _deferred_printers_default(self): | |
658 | return pretty._deferred_type_pprinters.copy() |
|
667 | return pretty._deferred_type_pprinters.copy() | |
659 |
|
668 | |||
660 | #### FormatterABC interface #### |
|
669 | #### FormatterABC interface #### | |
661 |
|
670 | |||
662 | @warn_format_error |
|
671 | @warn_format_error | |
663 | def __call__(self, obj): |
|
672 | def __call__(self, obj): | |
664 | """Compute the pretty representation of the object.""" |
|
673 | """Compute the pretty representation of the object.""" | |
665 | if not self.pprint: |
|
674 | if not self.pprint: | |
666 | return pretty._safe_repr(obj) |
|
675 | return pretty._safe_repr(obj) | |
667 | else: |
|
676 | else: | |
668 | # This uses use StringIO, as cStringIO doesn't handle unicode. |
|
677 | # This uses use StringIO, as cStringIO doesn't handle unicode. | |
669 | stream = StringIO() |
|
678 | stream = StringIO() | |
670 | # self.newline.encode() is a quick fix for issue gh-597. We need to |
|
679 | # self.newline.encode() is a quick fix for issue gh-597. We need to | |
671 | # ensure that stream does not get a mix of unicode and bytestrings, |
|
680 | # ensure that stream does not get a mix of unicode and bytestrings, | |
672 | # or it will cause trouble. |
|
681 | # or it will cause trouble. | |
673 | printer = pretty.RepresentationPrinter(stream, self.verbose, |
|
682 | printer = pretty.RepresentationPrinter(stream, self.verbose, | |
674 | self.max_width, unicode_to_str(self.newline), |
|
683 | self.max_width, unicode_to_str(self.newline), | |
675 | singleton_pprinters=self.singleton_printers, |
|
684 | singleton_pprinters=self.singleton_printers, | |
676 | type_pprinters=self.type_printers, |
|
685 | type_pprinters=self.type_printers, | |
677 | deferred_pprinters=self.deferred_printers) |
|
686 | deferred_pprinters=self.deferred_printers) | |
678 | printer.pretty(obj) |
|
687 | printer.pretty(obj) | |
679 | printer.flush() |
|
688 | printer.flush() | |
680 | return stream.getvalue() |
|
689 | return stream.getvalue() | |
681 |
|
690 | |||
682 |
|
691 | |||
683 | class HTMLFormatter(BaseFormatter): |
|
692 | class HTMLFormatter(BaseFormatter): | |
684 | """An HTML formatter. |
|
693 | """An HTML formatter. | |
685 |
|
694 | |||
686 | To define the callables that compute the HTML representation of your |
|
695 | To define the callables that compute the HTML representation of your | |
687 | objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` |
|
696 | objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` | |
688 | or :meth:`for_type_by_name` methods to register functions that handle |
|
697 | or :meth:`for_type_by_name` methods to register functions that handle | |
689 | this. |
|
698 | this. | |
690 |
|
699 | |||
691 | The return value of this formatter should be a valid HTML snippet that |
|
700 | The return value of this formatter should be a valid HTML snippet that | |
692 | could be injected into an existing DOM. It should *not* include the |
|
701 | could be injected into an existing DOM. It should *not* include the | |
693 | ```<html>`` or ```<body>`` tags. |
|
702 | ```<html>`` or ```<body>`` tags. | |
694 | """ |
|
703 | """ | |
695 | format_type = Unicode('text/html') |
|
704 | format_type = Unicode('text/html') | |
696 |
|
705 | |||
697 | print_method = ObjectName('_repr_html_') |
|
706 | print_method = ObjectName('_repr_html_') | |
698 |
|
707 | |||
699 |
|
708 | |||
700 | class SVGFormatter(BaseFormatter): |
|
709 | class SVGFormatter(BaseFormatter): | |
701 | """An SVG formatter. |
|
710 | """An SVG formatter. | |
702 |
|
711 | |||
703 | To define the callables that compute the SVG representation of your |
|
712 | To define the callables that compute the SVG representation of your | |
704 | objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` |
|
713 | objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` | |
705 | or :meth:`for_type_by_name` methods to register functions that handle |
|
714 | or :meth:`for_type_by_name` methods to register functions that handle | |
706 | this. |
|
715 | this. | |
707 |
|
716 | |||
708 | The return value of this formatter should be valid SVG enclosed in |
|
717 | The return value of this formatter should be valid SVG enclosed in | |
709 | ```<svg>``` tags, that could be injected into an existing DOM. It should |
|
718 | ```<svg>``` tags, that could be injected into an existing DOM. It should | |
710 | *not* include the ```<html>`` or ```<body>`` tags. |
|
719 | *not* include the ```<html>`` or ```<body>`` tags. | |
711 | """ |
|
720 | """ | |
712 | format_type = Unicode('image/svg+xml') |
|
721 | format_type = Unicode('image/svg+xml') | |
713 |
|
722 | |||
714 | print_method = ObjectName('_repr_svg_') |
|
723 | print_method = ObjectName('_repr_svg_') | |
715 |
|
724 | |||
716 |
|
725 | |||
717 | class PNGFormatter(BaseFormatter): |
|
726 | class PNGFormatter(BaseFormatter): | |
718 | """A PNG formatter. |
|
727 | """A PNG formatter. | |
719 |
|
728 | |||
720 | To define the callables that compute the PNG representation of your |
|
729 | To define the callables that compute the PNG representation of your | |
721 | objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` |
|
730 | objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` | |
722 | or :meth:`for_type_by_name` methods to register functions that handle |
|
731 | or :meth:`for_type_by_name` methods to register functions that handle | |
723 | this. |
|
732 | this. | |
724 |
|
733 | |||
725 | The return value of this formatter should be raw PNG data, *not* |
|
734 | The return value of this formatter should be raw PNG data, *not* | |
726 | base64 encoded. |
|
735 | base64 encoded. | |
727 | """ |
|
736 | """ | |
728 | format_type = Unicode('image/png') |
|
737 | format_type = Unicode('image/png') | |
729 |
|
738 | |||
730 | print_method = ObjectName('_repr_png_') |
|
739 | print_method = ObjectName('_repr_png_') | |
731 |
|
740 | |||
732 | _return_type = (bytes, unicode_type) |
|
741 | _return_type = (bytes, unicode_type) | |
733 |
|
742 | |||
734 |
|
743 | |||
735 | class JPEGFormatter(BaseFormatter): |
|
744 | class JPEGFormatter(BaseFormatter): | |
736 | """A JPEG formatter. |
|
745 | """A JPEG formatter. | |
737 |
|
746 | |||
738 | To define the callables that compute the JPEG representation of your |
|
747 | To define the callables that compute the JPEG representation of your | |
739 | objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type` |
|
748 | objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type` | |
740 | or :meth:`for_type_by_name` methods to register functions that handle |
|
749 | or :meth:`for_type_by_name` methods to register functions that handle | |
741 | this. |
|
750 | this. | |
742 |
|
751 | |||
743 | The return value of this formatter should be raw JPEG data, *not* |
|
752 | The return value of this formatter should be raw JPEG data, *not* | |
744 | base64 encoded. |
|
753 | base64 encoded. | |
745 | """ |
|
754 | """ | |
746 | format_type = Unicode('image/jpeg') |
|
755 | format_type = Unicode('image/jpeg') | |
747 |
|
756 | |||
748 | print_method = ObjectName('_repr_jpeg_') |
|
757 | print_method = ObjectName('_repr_jpeg_') | |
749 |
|
758 | |||
750 | _return_type = (bytes, unicode_type) |
|
759 | _return_type = (bytes, unicode_type) | |
751 |
|
760 | |||
752 |
|
761 | |||
753 | class LatexFormatter(BaseFormatter): |
|
762 | class LatexFormatter(BaseFormatter): | |
754 | """A LaTeX formatter. |
|
763 | """A LaTeX formatter. | |
755 |
|
764 | |||
756 | To define the callables that compute the LaTeX representation of your |
|
765 | To define the callables that compute the LaTeX representation of your | |
757 | objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` |
|
766 | objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` | |
758 | or :meth:`for_type_by_name` methods to register functions that handle |
|
767 | or :meth:`for_type_by_name` methods to register functions that handle | |
759 | this. |
|
768 | this. | |
760 |
|
769 | |||
761 | The return value of this formatter should be a valid LaTeX equation, |
|
770 | The return value of this formatter should be a valid LaTeX equation, | |
762 | enclosed in either ```$```, ```$$``` or another LaTeX equation |
|
771 | enclosed in either ```$```, ```$$``` or another LaTeX equation | |
763 | environment. |
|
772 | environment. | |
764 | """ |
|
773 | """ | |
765 | format_type = Unicode('text/latex') |
|
774 | format_type = Unicode('text/latex') | |
766 |
|
775 | |||
767 | print_method = ObjectName('_repr_latex_') |
|
776 | print_method = ObjectName('_repr_latex_') | |
768 |
|
777 | |||
769 |
|
778 | |||
770 | class JSONFormatter(BaseFormatter): |
|
779 | class JSONFormatter(BaseFormatter): | |
771 | """A JSON string formatter. |
|
780 | """A JSON string formatter. | |
772 |
|
781 | |||
773 | To define the callables that compute the JSON string representation of |
|
782 | To define the callables that compute the JSON string representation of | |
774 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` |
|
783 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` | |
775 | or :meth:`for_type_by_name` methods to register functions that handle |
|
784 | or :meth:`for_type_by_name` methods to register functions that handle | |
776 | this. |
|
785 | this. | |
777 |
|
786 | |||
778 | The return value of this formatter should be a valid JSON string. |
|
787 | The return value of this formatter should be a valid JSON string. | |
779 | """ |
|
788 | """ | |
780 | format_type = Unicode('application/json') |
|
789 | format_type = Unicode('application/json') | |
781 |
|
790 | |||
782 | print_method = ObjectName('_repr_json_') |
|
791 | print_method = ObjectName('_repr_json_') | |
783 |
|
792 | |||
784 |
|
793 | |||
785 | class JavascriptFormatter(BaseFormatter): |
|
794 | class JavascriptFormatter(BaseFormatter): | |
786 | """A Javascript formatter. |
|
795 | """A Javascript formatter. | |
787 |
|
796 | |||
788 | To define the callables that compute the Javascript representation of |
|
797 | To define the callables that compute the Javascript representation of | |
789 | your objects, define a :meth:`_repr_javascript_` method or use the |
|
798 | your objects, define a :meth:`_repr_javascript_` method or use the | |
790 | :meth:`for_type` or :meth:`for_type_by_name` methods to register functions |
|
799 | :meth:`for_type` or :meth:`for_type_by_name` methods to register functions | |
791 | that handle this. |
|
800 | that handle this. | |
792 |
|
801 | |||
793 | The return value of this formatter should be valid Javascript code and |
|
802 | The return value of this formatter should be valid Javascript code and | |
794 | should *not* be enclosed in ```<script>``` tags. |
|
803 | should *not* be enclosed in ```<script>``` tags. | |
795 | """ |
|
804 | """ | |
796 | format_type = Unicode('application/javascript') |
|
805 | format_type = Unicode('application/javascript') | |
797 |
|
806 | |||
798 | print_method = ObjectName('_repr_javascript_') |
|
807 | print_method = ObjectName('_repr_javascript_') | |
799 |
|
808 | |||
800 |
|
809 | |||
801 | class PDFFormatter(BaseFormatter): |
|
810 | class PDFFormatter(BaseFormatter): | |
802 | """A PDF formatter. |
|
811 | """A PDF formatter. | |
803 |
|
812 | |||
804 | To defined the callables that compute to PDF representation of your |
|
813 | To defined the callables that compute to PDF representation of your | |
805 | objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type` |
|
814 | objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type` | |
806 | or :meth:`for_type_by_name` methods to register functions that handle |
|
815 | or :meth:`for_type_by_name` methods to register functions that handle | |
807 | this. |
|
816 | this. | |
808 |
|
817 | |||
809 | The return value of this formatter should be raw PDF data, *not* |
|
818 | The return value of this formatter should be raw PDF data, *not* | |
810 | base64 encoded. |
|
819 | base64 encoded. | |
811 | """ |
|
820 | """ | |
812 | format_type = Unicode('application/pdf') |
|
821 | format_type = Unicode('application/pdf') | |
813 |
|
822 | |||
814 | print_method = ObjectName('_repr_pdf_') |
|
823 | print_method = ObjectName('_repr_pdf_') | |
815 |
|
824 | |||
816 |
|
825 | |||
817 | FormatterABC.register(BaseFormatter) |
|
826 | FormatterABC.register(BaseFormatter) | |
818 | FormatterABC.register(PlainTextFormatter) |
|
827 | FormatterABC.register(PlainTextFormatter) | |
819 | FormatterABC.register(HTMLFormatter) |
|
828 | FormatterABC.register(HTMLFormatter) | |
820 | FormatterABC.register(SVGFormatter) |
|
829 | FormatterABC.register(SVGFormatter) | |
821 | FormatterABC.register(PNGFormatter) |
|
830 | FormatterABC.register(PNGFormatter) | |
822 | FormatterABC.register(PDFFormatter) |
|
831 | FormatterABC.register(PDFFormatter) | |
823 | FormatterABC.register(JPEGFormatter) |
|
832 | FormatterABC.register(JPEGFormatter) | |
824 | FormatterABC.register(LatexFormatter) |
|
833 | FormatterABC.register(LatexFormatter) | |
825 | FormatterABC.register(JSONFormatter) |
|
834 | FormatterABC.register(JSONFormatter) | |
826 | FormatterABC.register(JavascriptFormatter) |
|
835 | FormatterABC.register(JavascriptFormatter) | |
827 |
|
836 | |||
828 |
|
837 | |||
829 | def format_display_data(obj, include=None, exclude=None): |
|
838 | def format_display_data(obj, include=None, exclude=None): | |
830 | """Return a format data dict for an object. |
|
839 | """Return a format data dict for an object. | |
831 |
|
840 | |||
832 | By default all format types will be computed. |
|
841 | By default all format types will be computed. | |
833 |
|
842 | |||
834 | The following MIME types are currently implemented: |
|
843 | The following MIME types are currently implemented: | |
835 |
|
844 | |||
836 | * text/plain |
|
845 | * text/plain | |
837 | * text/html |
|
846 | * text/html | |
838 | * text/latex |
|
847 | * text/latex | |
839 | * application/json |
|
848 | * application/json | |
840 | * application/javascript |
|
849 | * application/javascript | |
841 | * application/pdf |
|
850 | * application/pdf | |
842 | * image/png |
|
851 | * image/png | |
843 | * image/jpeg |
|
852 | * image/jpeg | |
844 | * image/svg+xml |
|
853 | * image/svg+xml | |
845 |
|
854 | |||
846 | Parameters |
|
855 | Parameters | |
847 | ---------- |
|
856 | ---------- | |
848 | obj : object |
|
857 | obj : object | |
849 | The Python object whose format data will be computed. |
|
858 | The Python object whose format data will be computed. | |
850 |
|
859 | |||
851 | Returns |
|
860 | Returns | |
852 | ------- |
|
861 | ------- | |
853 | format_dict : dict |
|
862 | format_dict : dict | |
854 | A dictionary of key/value pairs, one or each format that was |
|
863 | A dictionary of key/value pairs, one or each format that was | |
855 | generated for the object. The keys are the format types, which |
|
864 | generated for the object. The keys are the format types, which | |
856 | will usually be MIME type strings and the values and JSON'able |
|
865 | will usually be MIME type strings and the values and JSON'able | |
857 | data structure containing the raw data for the representation in |
|
866 | data structure containing the raw data for the representation in | |
858 | that format. |
|
867 | that format. | |
859 | include : list or tuple, optional |
|
868 | include : list or tuple, optional | |
860 | A list of format type strings (MIME types) to include in the |
|
869 | A list of format type strings (MIME types) to include in the | |
861 | format data dict. If this is set *only* the format types included |
|
870 | format data dict. If this is set *only* the format types included | |
862 | in this list will be computed. |
|
871 | in this list will be computed. | |
863 | exclude : list or tuple, optional |
|
872 | exclude : list or tuple, optional | |
864 | A list of format type string (MIME types) to exclue in the format |
|
873 | A list of format type string (MIME types) to exclue in the format | |
865 | data dict. If this is set all format types will be computed, |
|
874 | data dict. If this is set all format types will be computed, | |
866 | except for those included in this argument. |
|
875 | except for those included in this argument. | |
867 | """ |
|
876 | """ | |
868 | from IPython.core.interactiveshell import InteractiveShell |
|
877 | from IPython.core.interactiveshell import InteractiveShell | |
869 |
|
878 | |||
870 | InteractiveShell.instance().display_formatter.format( |
|
879 | InteractiveShell.instance().display_formatter.format( | |
871 | obj, |
|
880 | obj, | |
872 | include, |
|
881 | include, | |
873 | exclude |
|
882 | exclude | |
874 | ) |
|
883 | ) | |
875 |
|
884 |
General Comments 0
You need to be logged in to leave comments.
Login now