Show More
@@ -1,1296 +1,1311 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 | # Copyright (c) IPython Development Team. |
|
4 | # Copyright (c) IPython Development Team. | |
5 | # Distributed under the terms of the Modified BSD License. |
|
5 | # Distributed under the terms of the Modified BSD License. | |
6 |
|
6 | |||
7 |
|
7 | |||
8 | try: |
|
8 | try: | |
9 | from base64 import encodebytes as base64_encode |
|
9 | from base64 import encodebytes as base64_encode | |
10 | except ImportError: |
|
10 | except ImportError: | |
11 | from base64 import encodestring as base64_encode |
|
11 | from base64 import encodestring as base64_encode | |
12 |
|
12 | |||
13 | from binascii import b2a_hex |
|
13 | from binascii import b2a_hex | |
14 | import json |
|
14 | import json | |
15 | import mimetypes |
|
15 | import mimetypes | |
16 | import os |
|
16 | import os | |
17 | import struct |
|
17 | import struct | |
18 | import sys |
|
18 | import sys | |
19 | import warnings |
|
19 | import warnings | |
20 |
|
20 | |||
21 | from IPython.utils.py3compat import cast_unicode |
|
21 | from IPython.utils.py3compat import cast_unicode | |
22 | from IPython.testing.skipdoctest import skip_doctest |
|
22 | from IPython.testing.skipdoctest import skip_doctest | |
23 |
|
23 | |||
24 | __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown', |
|
24 | __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown', | |
25 | 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json', |
|
25 | 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json', | |
26 | 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject', |
|
26 | 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject', | |
27 | 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'JSON', 'GeoJSON', 'Javascript', |
|
27 | 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'JSON', 'GeoJSON', 'Javascript', | |
28 | 'Image', 'clear_output', 'set_matplotlib_formats', 'set_matplotlib_close', |
|
28 | 'Image', 'clear_output', 'set_matplotlib_formats', 'set_matplotlib_close', | |
29 | 'publish_display_data', 'update_display', 'DisplayHandle', 'Video'] |
|
29 | 'publish_display_data', 'update_display', 'DisplayHandle', 'Video'] | |
30 |
|
30 | |||
31 | #----------------------------------------------------------------------------- |
|
31 | #----------------------------------------------------------------------------- | |
32 | # utility functions |
|
32 | # utility functions | |
33 | #----------------------------------------------------------------------------- |
|
33 | #----------------------------------------------------------------------------- | |
34 |
|
34 | |||
35 | def _safe_exists(path): |
|
35 | def _safe_exists(path): | |
36 | """Check path, but don't let exceptions raise""" |
|
36 | """Check path, but don't let exceptions raise""" | |
37 | try: |
|
37 | try: | |
38 | return os.path.exists(path) |
|
38 | return os.path.exists(path) | |
39 | except Exception: |
|
39 | except Exception: | |
40 | return False |
|
40 | return False | |
41 |
|
41 | |||
42 | def _merge(d1, d2): |
|
42 | def _merge(d1, d2): | |
43 | """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. | |
44 |
|
44 | |||
45 | Updates d1 in-place |
|
45 | Updates d1 in-place | |
46 | """ |
|
46 | """ | |
47 |
|
47 | |||
48 | if not isinstance(d2, dict) or not isinstance(d1, dict): |
|
48 | if not isinstance(d2, dict) or not isinstance(d1, dict): | |
49 | return d2 |
|
49 | return d2 | |
50 | for key, value in d2.items(): |
|
50 | for key, value in d2.items(): | |
51 | d1[key] = _merge(d1.get(key), value) |
|
51 | d1[key] = _merge(d1.get(key), value) | |
52 | return d1 |
|
52 | return d1 | |
53 |
|
53 | |||
54 | def _display_mimetype(mimetype, objs, raw=False, metadata=None): |
|
54 | def _display_mimetype(mimetype, objs, raw=False, metadata=None): | |
55 | """internal implementation of all display_foo methods |
|
55 | """internal implementation of all display_foo methods | |
56 |
|
56 | |||
57 | Parameters |
|
57 | Parameters | |
58 | ---------- |
|
58 | ---------- | |
59 | mimetype : str |
|
59 | mimetype : str | |
60 | The mimetype to be published (e.g. 'image/png') |
|
60 | The mimetype to be published (e.g. 'image/png') | |
61 | objs : tuple of objects |
|
61 | objs : tuple of objects | |
62 | 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 | |
63 | display. |
|
63 | display. | |
64 | raw : bool |
|
64 | raw : bool | |
65 | 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 | |
66 | formatted before display? [default: False] |
|
66 | formatted before display? [default: False] | |
67 | metadata : dict (optional) |
|
67 | metadata : dict (optional) | |
68 | Metadata to be associated with the specific mimetype output. |
|
68 | Metadata to be associated with the specific mimetype output. | |
69 | """ |
|
69 | """ | |
70 | if metadata: |
|
70 | if metadata: | |
71 | metadata = {mimetype: metadata} |
|
71 | metadata = {mimetype: metadata} | |
72 | if raw: |
|
72 | if raw: | |
73 | # turn list of pngdata into list of { 'image/png': pngdata } |
|
73 | # turn list of pngdata into list of { 'image/png': pngdata } | |
74 | objs = [ {mimetype: obj} for obj in objs ] |
|
74 | objs = [ {mimetype: obj} for obj in objs ] | |
75 | display(*objs, raw=raw, metadata=metadata, include=[mimetype]) |
|
75 | display(*objs, raw=raw, metadata=metadata, include=[mimetype]) | |
76 |
|
76 | |||
77 | #----------------------------------------------------------------------------- |
|
77 | #----------------------------------------------------------------------------- | |
78 | # Main functions |
|
78 | # Main functions | |
79 | #----------------------------------------------------------------------------- |
|
79 | #----------------------------------------------------------------------------- | |
80 |
|
80 | |||
81 | # use * to indicate transient is keyword-only |
|
81 | # use * to indicate transient is keyword-only | |
82 | def publish_display_data(data, metadata=None, source=None, *, transient=None, **kwargs): |
|
82 | def publish_display_data(data, metadata=None, source=None, *, transient=None, **kwargs): | |
83 | """Publish data and metadata to all frontends. |
|
83 | """Publish data and metadata to all frontends. | |
84 |
|
84 | |||
85 | See the ``display_data`` message in the messaging documentation for |
|
85 | See the ``display_data`` message in the messaging documentation for | |
86 | more details about this message type. |
|
86 | more details about this message type. | |
87 |
|
87 | |||
88 | The following MIME types are currently implemented: |
|
88 | The following MIME types are currently implemented: | |
89 |
|
89 | |||
90 | * text/plain |
|
90 | * text/plain | |
91 | * text/html |
|
91 | * text/html | |
92 | * text/markdown |
|
92 | * text/markdown | |
93 | * text/latex |
|
93 | * text/latex | |
94 | * application/json |
|
94 | * application/json | |
95 | * application/javascript |
|
95 | * application/javascript | |
96 | * image/png |
|
96 | * image/png | |
97 | * image/jpeg |
|
97 | * image/jpeg | |
98 | * image/svg+xml |
|
98 | * image/svg+xml | |
99 |
|
99 | |||
100 | Parameters |
|
100 | Parameters | |
101 | ---------- |
|
101 | ---------- | |
102 | data : dict |
|
102 | data : dict | |
103 | A dictionary having keys that are valid MIME types (like |
|
103 | A dictionary having keys that are valid MIME types (like | |
104 | 'text/plain' or 'image/svg+xml') and values that are the data for |
|
104 | 'text/plain' or 'image/svg+xml') and values that are the data for | |
105 | that MIME type. The data itself must be a JSON'able data |
|
105 | that MIME type. The data itself must be a JSON'able data | |
106 | structure. Minimally all data should have the 'text/plain' data, |
|
106 | structure. Minimally all data should have the 'text/plain' data, | |
107 | which can be displayed by all frontends. If more than the plain |
|
107 | which can be displayed by all frontends. If more than the plain | |
108 | text is given, it is up to the frontend to decide which |
|
108 | text is given, it is up to the frontend to decide which | |
109 | representation to use. |
|
109 | representation to use. | |
110 | metadata : dict |
|
110 | metadata : dict | |
111 | A dictionary for metadata related to the data. This can contain |
|
111 | A dictionary for metadata related to the data. This can contain | |
112 | arbitrary key, value pairs that frontends can use to interpret |
|
112 | arbitrary key, value pairs that frontends can use to interpret | |
113 | the data. mime-type keys matching those in data can be used |
|
113 | the data. mime-type keys matching those in data can be used | |
114 | to specify metadata about particular representations. |
|
114 | to specify metadata about particular representations. | |
115 | source : str, deprecated |
|
115 | source : str, deprecated | |
116 | Unused. |
|
116 | Unused. | |
117 | transient : dict, keyword-only |
|
117 | transient : dict, keyword-only | |
118 | A dictionary of transient data, such as display_id. |
|
118 | A dictionary of transient data, such as display_id. | |
119 | """ |
|
119 | """ | |
120 | from IPython.core.interactiveshell import InteractiveShell |
|
120 | from IPython.core.interactiveshell import InteractiveShell | |
121 |
|
121 | |||
122 | display_pub = InteractiveShell.instance().display_pub |
|
122 | display_pub = InteractiveShell.instance().display_pub | |
123 |
|
123 | |||
124 | # only pass transient if supplied, |
|
124 | # only pass transient if supplied, | |
125 | # to avoid errors with older ipykernel. |
|
125 | # to avoid errors with older ipykernel. | |
126 | # TODO: We could check for ipykernel version and provide a detailed upgrade message. |
|
126 | # TODO: We could check for ipykernel version and provide a detailed upgrade message. | |
127 | if transient: |
|
127 | if transient: | |
128 | kwargs['transient'] = transient |
|
128 | kwargs['transient'] = transient | |
129 |
|
129 | |||
130 | display_pub.publish( |
|
130 | display_pub.publish( | |
131 | data=data, |
|
131 | data=data, | |
132 | metadata=metadata, |
|
132 | metadata=metadata, | |
133 | **kwargs |
|
133 | **kwargs | |
134 | ) |
|
134 | ) | |
135 |
|
135 | |||
136 |
|
136 | |||
137 | def _new_id(): |
|
137 | def _new_id(): | |
138 | """Generate a new random text id with urandom""" |
|
138 | """Generate a new random text id with urandom""" | |
139 | return b2a_hex(os.urandom(16)).decode('ascii') |
|
139 | return b2a_hex(os.urandom(16)).decode('ascii') | |
140 |
|
140 | |||
141 |
|
141 | |||
142 | def display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs): |
|
142 | def display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs): | |
143 | """Display a Python object in all frontends. |
|
143 | """Display a Python object in all frontends. | |
144 |
|
144 | |||
145 | By default all representations will be computed and sent to the frontends. |
|
145 | By default all representations will be computed and sent to the frontends. | |
146 | Frontends can decide which representation is used and how. |
|
146 | Frontends can decide which representation is used and how. | |
147 |
|
147 | |||
148 | In terminal IPython this will be similar to using `print`, for use in richer |
|
148 | In terminal IPython this will be similar to using :func:`print`, for use in richer | |
149 | frontends see Jupyter notebook examples with rich display logic. |
|
149 | frontends see Jupyter notebook examples with rich display logic. | |
150 |
|
150 | |||
151 | Parameters |
|
151 | Parameters | |
152 | ---------- |
|
152 | ---------- | |
153 | objs : tuple of objects |
|
153 | objs : tuple of objects | |
154 | The Python objects to display. |
|
154 | The Python objects to display. | |
155 | raw : bool, optional |
|
155 | raw : bool, optional | |
156 | Are the objects to be displayed already mimetype-keyed dicts of raw display data, |
|
156 | Are the objects to be displayed already mimetype-keyed dicts of raw display data, | |
157 | or Python objects that need to be formatted before display? [default: False] |
|
157 | or Python objects that need to be formatted before display? [default: False] | |
158 |
include : list |
|
158 | include : list, tuple or set, optional | |
159 | A list of format type strings (MIME types) to include in the |
|
159 | A list of format type strings (MIME types) to include in the | |
160 | format data dict. If this is set *only* the format types included |
|
160 | format data dict. If this is set *only* the format types included | |
161 | in this list will be computed. |
|
161 | in this list will be computed. | |
162 |
exclude : list |
|
162 | exclude : list, tuple or set, optional | |
163 | A list of format type strings (MIME types) to exclude in the format |
|
163 | A list of format type strings (MIME types) to exclude in the format | |
164 | data dict. If this is set all format types will be computed, |
|
164 | data dict. If this is set all format types will be computed, | |
165 | except for those included in this argument. |
|
165 | except for those included in this argument. | |
166 | metadata : dict, optional |
|
166 | metadata : dict, optional | |
167 | A dictionary of metadata to associate with the output. |
|
167 | A dictionary of metadata to associate with the output. | |
168 | mime-type keys in this dictionary will be associated with the individual |
|
168 | mime-type keys in this dictionary will be associated with the individual | |
169 | representation formats, if they exist. |
|
169 | representation formats, if they exist. | |
170 | transient : dict, optional |
|
170 | transient : dict, optional | |
171 | A dictionary of transient data to associate with the output. |
|
171 | A dictionary of transient data to associate with the output. | |
172 | Data in this dict should not be persisted to files (e.g. notebooks). |
|
172 | Data in this dict should not be persisted to files (e.g. notebooks). | |
173 | display_id : str, optional |
|
173 | display_id : str, bool optional | |
174 | Set an id for the display. |
|
174 | Set an id for the display. | |
175 | This id can be used for updating this display area later via update_display. |
|
175 | This id can be used for updating this display area later via update_display. | |
176 | If given as True, generate a new display_id |
|
176 | If given as `True`, generate a new `display_id` | |
177 | kwargs: additional keyword-args, optional |
|
177 | kwargs: additional keyword-args, optional | |
178 | Additional keyword-arguments are passed through to the display publisher. |
|
178 | Additional keyword-arguments are passed through to the display publisher. | |
179 |
|
179 | |||
180 | Returns |
|
180 | Returns | |
181 | ------- |
|
181 | ------- | |
182 |
|
182 | |||
183 | handle: DisplayHandle |
|
183 | handle: DisplayHandle | |
184 |
Returns a handle on updatable displays |
|
184 | Returns a handle on updatable displays for use with :func:`update_display`, | |
185 | Returns None if no display_id is given (default). |
|
185 | if `display_id` is given. Returns :any:`None` if no `display_id` is given | |
|
186 | (default). | |||
186 |
|
187 | |||
187 | Examples |
|
188 | Examples | |
188 | -------- |
|
189 | -------- | |
189 |
|
190 | |||
190 | >>> class Json(object): |
|
191 | >>> class Json(object): | |
191 | ... def __init__(self, json): |
|
192 | ... def __init__(self, json): | |
192 | ... self.json = json |
|
193 | ... self.json = json | |
193 | ... def _repr_pretty_(self, pp, cycle): |
|
194 | ... def _repr_pretty_(self, pp, cycle): | |
194 | ... import json |
|
195 | ... import json | |
195 | ... pp.text(json.dumps(self.json, indent=2)) |
|
196 | ... pp.text(json.dumps(self.json, indent=2)) | |
196 | ... def __repr__(self): |
|
197 | ... def __repr__(self): | |
197 | ... return str(self.json) |
|
198 | ... return str(self.json) | |
198 | ... |
|
199 | ... | |
199 |
|
200 | |||
200 | >>> d = Json({1:2, 3: {4:5}}) |
|
201 | >>> d = Json({1:2, 3: {4:5}}) | |
201 |
|
202 | |||
202 | >>> print(d) |
|
203 | >>> print(d) | |
203 | {1: 2, 3: {4: 5}} |
|
204 | {1: 2, 3: {4: 5}} | |
204 |
|
205 | |||
205 | >>> display(d) |
|
206 | >>> display(d) | |
206 | { |
|
207 | { | |
207 | "1": 2, |
|
208 | "1": 2, | |
208 | "3": { |
|
209 | "3": { | |
209 | "4": 5 |
|
210 | "4": 5 | |
210 | } |
|
211 | } | |
211 | } |
|
212 | } | |
212 |
|
213 | |||
213 | >>> def int_formatter(integer, pp, cycle): |
|
214 | >>> def int_formatter(integer, pp, cycle): | |
214 | ... pp.text('I'*integer) |
|
215 | ... pp.text('I'*integer) | |
215 |
|
216 | |||
216 | >>> plain = get_ipython().display_formatter.formatters['text/plain'] |
|
217 | >>> plain = get_ipython().display_formatter.formatters['text/plain'] | |
217 | >>> plain.for_type(int, int_formatter) |
|
218 | >>> plain.for_type(int, int_formatter) | |
218 | <function _repr_pprint at 0x...> |
|
219 | <function _repr_pprint at 0x...> | |
219 | >>> display(7-5) |
|
220 | >>> display(7-5) | |
220 | II |
|
221 | II | |
221 |
|
222 | |||
222 | >>> del plain.type_printers[int] |
|
223 | >>> del plain.type_printers[int] | |
223 | >>> display(7-5) |
|
224 | >>> display(7-5) | |
224 | 2 |
|
225 | 2 | |
225 |
|
226 | |||
226 | See Also |
|
227 | See Also | |
227 | -------- |
|
228 | -------- | |
228 |
|
229 | |||
229 | `update_display` |
|
230 | :func:`update_display` | |
230 |
|
231 | |||
231 | Notes |
|
232 | Notes | |
232 | ----- |
|
233 | ----- | |
233 |
|
234 | |||
234 | In Python, objects can declare their textual representation using the |
|
235 | In Python, objects can declare their textual representation using the | |
235 | `__repr__` method. IPython expands on this idea and allows objects to declare |
|
236 | `__repr__` method. IPython expands on this idea and allows objects to declare | |
236 | other, rich representations including: |
|
237 | other, rich representations including: | |
237 |
|
238 | |||
238 | - HTML |
|
239 | - HTML | |
239 | - JSON |
|
240 | - JSON | |
240 | - PNG |
|
241 | - PNG | |
241 | - JPEG |
|
242 | - JPEG | |
242 | - SVG |
|
243 | - SVG | |
243 | - LaTeX |
|
244 | - LaTeX | |
244 |
|
245 | |||
245 | A single object can declare some or all of these representations; all are |
|
246 | A single object can declare some or all of these representations; all are | |
246 | handled by IPython's display system. |
|
247 | handled by IPython's display system. | |
247 |
|
248 | |||
248 | The main idea of the first approach is that you have to implement special |
|
249 | The main idea of the first approach is that you have to implement special | |
249 | display methods when you define your class, one for each representation you |
|
250 | display methods when you define your class, one for each representation you | |
250 | want to use. Here is a list of the names of the special methods and the |
|
251 | want to use. Here is a list of the names of the special methods and the | |
251 | values they must return: |
|
252 | values they must return: | |
252 |
|
253 | |||
253 | - `_repr_html_`: return raw HTML as a string |
|
254 | - `_repr_html_`: return raw HTML as a string | |
254 | - `_repr_json_`: return a JSONable dict |
|
255 | - `_repr_json_`: return a JSONable dict | |
255 | - `_repr_jpeg_`: return raw JPEG data |
|
256 | - `_repr_jpeg_`: return raw JPEG data | |
256 | - `_repr_png_`: return raw PNG data |
|
257 | - `_repr_png_`: return raw PNG data | |
257 | - `_repr_svg_`: return raw SVG data as a string |
|
258 | - `_repr_svg_`: return raw SVG data as a string | |
258 | - `_repr_latex_`: return LaTeX commands in a string surrounded by "$". |
|
259 | - `_repr_latex_`: return LaTeX commands in a string surrounded by "$". | |
259 | - `_repr_mimebundle_`: return a full mimebundle containing the mapping |
|
260 | - `_repr_mimebundle_`: return a full mimebundle containing the mapping | |
260 | from all mimetypes to data |
|
261 | from all mimetypes to data | |
261 |
|
262 | |||
262 | When you are directly writing your own classes, you can adapt them for |
|
263 | When you are directly writing your own classes, you can adapt them for | |
263 | display in IPython by following the above approach. But in practice, you |
|
264 | display in IPython by following the above approach. But in practice, you | |
264 | often need to work with existing classes that you can't easily modify. |
|
265 | often need to work with existing classes that you can't easily modify. | |
265 |
|
266 | |||
266 | You can refer to the documentation on IPython display formatters in order to |
|
267 | You can refer to the documentation on IPython display formatters in order to | |
267 | register custom formatters for already existing types. |
|
268 | register custom formatters for already existing types. | |
268 |
|
269 | |||
269 | Since IPython 5.4 and 6.1 display is automatically made available to the |
|
270 | .. versionadded:: 5.4 display available without import | |
270 | user without import. If you are using display in a document that might be |
|
271 | .. versionadded:: 6.1 display available without import | |
271 | used in a pure python context or with older version of IPython, use the |
|
272 | ||
|
273 | Since IPython 5.4 and 6.1 :func:`display` is automatically made available to | |||
|
274 | the user without import. If you are using display in a document that might | |||
|
275 | be used in a pure python context or with older version of IPython, use the | |||
272 | following import at the top of your file:: |
|
276 | following import at the top of your file:: | |
273 |
|
277 | |||
274 | from IPython.display import display |
|
278 | from IPython.display import display | |
275 |
|
279 | |||
276 | """ |
|
280 | """ | |
277 | raw = kwargs.pop('raw', False) |
|
281 | raw = kwargs.pop('raw', False) | |
278 | if transient is None: |
|
282 | if transient is None: | |
279 | transient = {} |
|
283 | transient = {} | |
280 | if display_id: |
|
284 | if display_id: | |
281 | if display_id is True: |
|
285 | if display_id is True: | |
282 | display_id = _new_id() |
|
286 | display_id = _new_id() | |
283 | transient['display_id'] = display_id |
|
287 | transient['display_id'] = display_id | |
284 | if kwargs.get('update') and 'display_id' not in transient: |
|
288 | if kwargs.get('update') and 'display_id' not in transient: | |
285 | raise TypeError('display_id required for update_display') |
|
289 | raise TypeError('display_id required for update_display') | |
286 | if transient: |
|
290 | if transient: | |
287 | kwargs['transient'] = transient |
|
291 | kwargs['transient'] = transient | |
288 |
|
292 | |||
289 | from IPython.core.interactiveshell import InteractiveShell |
|
293 | from IPython.core.interactiveshell import InteractiveShell | |
290 |
|
294 | |||
291 | if not raw: |
|
295 | if not raw: | |
292 | format = InteractiveShell.instance().display_formatter.format |
|
296 | format = InteractiveShell.instance().display_formatter.format | |
293 |
|
297 | |||
294 | for obj in objs: |
|
298 | for obj in objs: | |
295 | if raw: |
|
299 | if raw: | |
296 | publish_display_data(data=obj, metadata=metadata, **kwargs) |
|
300 | publish_display_data(data=obj, metadata=metadata, **kwargs) | |
297 | else: |
|
301 | else: | |
298 | format_dict, md_dict = format(obj, include=include, exclude=exclude) |
|
302 | format_dict, md_dict = format(obj, include=include, exclude=exclude) | |
299 | if not format_dict: |
|
303 | if not format_dict: | |
300 | # nothing to display (e.g. _ipython_display_ took over) |
|
304 | # nothing to display (e.g. _ipython_display_ took over) | |
301 | continue |
|
305 | continue | |
302 | if metadata: |
|
306 | if metadata: | |
303 | # kwarg-specified metadata gets precedence |
|
307 | # kwarg-specified metadata gets precedence | |
304 | _merge(md_dict, metadata) |
|
308 | _merge(md_dict, metadata) | |
305 | publish_display_data(data=format_dict, metadata=md_dict, **kwargs) |
|
309 | publish_display_data(data=format_dict, metadata=md_dict, **kwargs) | |
306 | if display_id: |
|
310 | if display_id: | |
307 | return DisplayHandle(display_id) |
|
311 | return DisplayHandle(display_id) | |
308 |
|
312 | |||
309 |
|
313 | |||
310 | # use * for keyword-only display_id arg |
|
314 | # use * for keyword-only display_id arg | |
311 | def update_display(obj, *, display_id, **kwargs): |
|
315 | def update_display(obj, *, display_id, **kwargs): | |
312 | """Update an existing display by id |
|
316 | """Update an existing display by id | |
313 |
|
317 | |||
314 | Parameters |
|
318 | Parameters | |
315 | ---------- |
|
319 | ---------- | |
316 |
|
320 | |||
317 | obj: |
|
321 | obj: | |
318 | The object with which to update the display |
|
322 | The object with which to update the display | |
319 | display_id: keyword-only |
|
323 | display_id: keyword-only | |
320 | The id of the display to update |
|
324 | The id of the display to update | |
|
325 | ||||
|
326 | See Also | |||
|
327 | -------- | |||
|
328 | ||||
|
329 | :func:`display` | |||
321 | """ |
|
330 | """ | |
322 | kwargs['update'] = True |
|
331 | kwargs['update'] = True | |
323 | display(obj, display_id=display_id, **kwargs) |
|
332 | display(obj, display_id=display_id, **kwargs) | |
324 |
|
333 | |||
325 |
|
334 | |||
326 | class DisplayHandle(object): |
|
335 | class DisplayHandle(object): | |
327 | """A handle on an updatable display |
|
336 | """A handle on an updatable display | |
328 |
|
337 | |||
329 | Call .update(obj) to display a new object. |
|
338 | Call `.update(obj)` to display a new object. | |
330 |
|
339 | |||
331 | Call .display(obj) to add a new instance of this display, |
|
340 | Call `.display(obj`) to add a new instance of this display, | |
332 | and update existing instances. |
|
341 | and update existing instances. | |
|
342 | ||||
|
343 | See Also | |||
|
344 | -------- | |||
|
345 | ||||
|
346 | :func:`display`, :func:`update_display` | |||
|
347 | ||||
333 | """ |
|
348 | """ | |
334 |
|
349 | |||
335 | def __init__(self, display_id=None): |
|
350 | def __init__(self, display_id=None): | |
336 | if display_id is None: |
|
351 | if display_id is None: | |
337 | display_id = _new_id() |
|
352 | display_id = _new_id() | |
338 | self.display_id = display_id |
|
353 | self.display_id = display_id | |
339 |
|
354 | |||
340 | def __repr__(self): |
|
355 | def __repr__(self): | |
341 | return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id) |
|
356 | return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id) | |
342 |
|
357 | |||
343 | def display(self, obj, **kwargs): |
|
358 | def display(self, obj, **kwargs): | |
344 | """Make a new display with my id, updating existing instances. |
|
359 | """Make a new display with my id, updating existing instances. | |
345 |
|
360 | |||
346 | Parameters |
|
361 | Parameters | |
347 | ---------- |
|
362 | ---------- | |
348 |
|
363 | |||
349 | obj: |
|
364 | obj: | |
350 | object to display |
|
365 | object to display | |
351 | **kwargs: |
|
366 | **kwargs: | |
352 | additional keyword arguments passed to display |
|
367 | additional keyword arguments passed to display | |
353 | """ |
|
368 | """ | |
354 | display(obj, display_id=self.display_id, **kwargs) |
|
369 | display(obj, display_id=self.display_id, **kwargs) | |
355 |
|
370 | |||
356 | def update(self, obj, **kwargs): |
|
371 | def update(self, obj, **kwargs): | |
357 | """Update existing displays with my id |
|
372 | """Update existing displays with my id | |
358 |
|
373 | |||
359 | Parameters |
|
374 | Parameters | |
360 | ---------- |
|
375 | ---------- | |
361 |
|
376 | |||
362 | obj: |
|
377 | obj: | |
363 | object to display |
|
378 | object to display | |
364 | **kwargs: |
|
379 | **kwargs: | |
365 | additional keyword arguments passed to update_display |
|
380 | additional keyword arguments passed to update_display | |
366 | """ |
|
381 | """ | |
367 | update_display(obj, display_id=self.display_id, **kwargs) |
|
382 | update_display(obj, display_id=self.display_id, **kwargs) | |
368 |
|
383 | |||
369 |
|
384 | |||
370 | def display_pretty(*objs, **kwargs): |
|
385 | def display_pretty(*objs, **kwargs): | |
371 | """Display the pretty (default) representation of an object. |
|
386 | """Display the pretty (default) representation of an object. | |
372 |
|
387 | |||
373 | Parameters |
|
388 | Parameters | |
374 | ---------- |
|
389 | ---------- | |
375 | objs : tuple of objects |
|
390 | objs : tuple of objects | |
376 | The Python objects to display, or if raw=True raw text data to |
|
391 | The Python objects to display, or if raw=True raw text data to | |
377 | display. |
|
392 | display. | |
378 | raw : bool |
|
393 | raw : bool | |
379 | Are the data objects raw data or Python objects that need to be |
|
394 | Are the data objects raw data or Python objects that need to be | |
380 | formatted before display? [default: False] |
|
395 | formatted before display? [default: False] | |
381 | metadata : dict (optional) |
|
396 | metadata : dict (optional) | |
382 | Metadata to be associated with the specific mimetype output. |
|
397 | Metadata to be associated with the specific mimetype output. | |
383 | """ |
|
398 | """ | |
384 | _display_mimetype('text/plain', objs, **kwargs) |
|
399 | _display_mimetype('text/plain', objs, **kwargs) | |
385 |
|
400 | |||
386 |
|
401 | |||
387 | def display_html(*objs, **kwargs): |
|
402 | def display_html(*objs, **kwargs): | |
388 | """Display the HTML representation of an object. |
|
403 | """Display the HTML representation of an object. | |
389 |
|
404 | |||
390 | Note: If raw=False and the object does not have a HTML |
|
405 | Note: If raw=False and the object does not have a HTML | |
391 | representation, no HTML will be shown. |
|
406 | representation, no HTML will be shown. | |
392 |
|
407 | |||
393 | Parameters |
|
408 | Parameters | |
394 | ---------- |
|
409 | ---------- | |
395 | objs : tuple of objects |
|
410 | objs : tuple of objects | |
396 | The Python objects to display, or if raw=True raw HTML data to |
|
411 | The Python objects to display, or if raw=True raw HTML data to | |
397 | display. |
|
412 | display. | |
398 | raw : bool |
|
413 | raw : bool | |
399 | Are the data objects raw data or Python objects that need to be |
|
414 | Are the data objects raw data or Python objects that need to be | |
400 | formatted before display? [default: False] |
|
415 | formatted before display? [default: False] | |
401 | metadata : dict (optional) |
|
416 | metadata : dict (optional) | |
402 | Metadata to be associated with the specific mimetype output. |
|
417 | Metadata to be associated with the specific mimetype output. | |
403 | """ |
|
418 | """ | |
404 | _display_mimetype('text/html', objs, **kwargs) |
|
419 | _display_mimetype('text/html', objs, **kwargs) | |
405 |
|
420 | |||
406 |
|
421 | |||
407 | def display_markdown(*objs, **kwargs): |
|
422 | def display_markdown(*objs, **kwargs): | |
408 | """Displays the Markdown representation of an object. |
|
423 | """Displays the Markdown representation of an object. | |
409 |
|
424 | |||
410 | Parameters |
|
425 | Parameters | |
411 | ---------- |
|
426 | ---------- | |
412 | objs : tuple of objects |
|
427 | objs : tuple of objects | |
413 | The Python objects to display, or if raw=True raw markdown data to |
|
428 | The Python objects to display, or if raw=True raw markdown data to | |
414 | display. |
|
429 | display. | |
415 | raw : bool |
|
430 | raw : bool | |
416 | Are the data objects raw data or Python objects that need to be |
|
431 | Are the data objects raw data or Python objects that need to be | |
417 | formatted before display? [default: False] |
|
432 | formatted before display? [default: False] | |
418 | metadata : dict (optional) |
|
433 | metadata : dict (optional) | |
419 | Metadata to be associated with the specific mimetype output. |
|
434 | Metadata to be associated with the specific mimetype output. | |
420 | """ |
|
435 | """ | |
421 |
|
436 | |||
422 | _display_mimetype('text/markdown', objs, **kwargs) |
|
437 | _display_mimetype('text/markdown', objs, **kwargs) | |
423 |
|
438 | |||
424 |
|
439 | |||
425 | def display_svg(*objs, **kwargs): |
|
440 | def display_svg(*objs, **kwargs): | |
426 | """Display the SVG representation of an object. |
|
441 | """Display the SVG representation of an object. | |
427 |
|
442 | |||
428 | Parameters |
|
443 | Parameters | |
429 | ---------- |
|
444 | ---------- | |
430 | objs : tuple of objects |
|
445 | objs : tuple of objects | |
431 | The Python objects to display, or if raw=True raw svg data to |
|
446 | The Python objects to display, or if raw=True raw svg data to | |
432 | display. |
|
447 | display. | |
433 | raw : bool |
|
448 | raw : bool | |
434 | Are the data objects raw data or Python objects that need to be |
|
449 | Are the data objects raw data or Python objects that need to be | |
435 | formatted before display? [default: False] |
|
450 | formatted before display? [default: False] | |
436 | metadata : dict (optional) |
|
451 | metadata : dict (optional) | |
437 | Metadata to be associated with the specific mimetype output. |
|
452 | Metadata to be associated with the specific mimetype output. | |
438 | """ |
|
453 | """ | |
439 | _display_mimetype('image/svg+xml', objs, **kwargs) |
|
454 | _display_mimetype('image/svg+xml', objs, **kwargs) | |
440 |
|
455 | |||
441 |
|
456 | |||
442 | def display_png(*objs, **kwargs): |
|
457 | def display_png(*objs, **kwargs): | |
443 | """Display the PNG representation of an object. |
|
458 | """Display the PNG representation of an object. | |
444 |
|
459 | |||
445 | Parameters |
|
460 | Parameters | |
446 | ---------- |
|
461 | ---------- | |
447 | objs : tuple of objects |
|
462 | objs : tuple of objects | |
448 | The Python objects to display, or if raw=True raw png data to |
|
463 | The Python objects to display, or if raw=True raw png data to | |
449 | display. |
|
464 | display. | |
450 | raw : bool |
|
465 | raw : bool | |
451 | Are the data objects raw data or Python objects that need to be |
|
466 | Are the data objects raw data or Python objects that need to be | |
452 | formatted before display? [default: False] |
|
467 | formatted before display? [default: False] | |
453 | metadata : dict (optional) |
|
468 | metadata : dict (optional) | |
454 | Metadata to be associated with the specific mimetype output. |
|
469 | Metadata to be associated with the specific mimetype output. | |
455 | """ |
|
470 | """ | |
456 | _display_mimetype('image/png', objs, **kwargs) |
|
471 | _display_mimetype('image/png', objs, **kwargs) | |
457 |
|
472 | |||
458 |
|
473 | |||
459 | def display_jpeg(*objs, **kwargs): |
|
474 | def display_jpeg(*objs, **kwargs): | |
460 | """Display the JPEG representation of an object. |
|
475 | """Display the JPEG representation of an object. | |
461 |
|
476 | |||
462 | Parameters |
|
477 | Parameters | |
463 | ---------- |
|
478 | ---------- | |
464 | objs : tuple of objects |
|
479 | objs : tuple of objects | |
465 | The Python objects to display, or if raw=True raw JPEG data to |
|
480 | The Python objects to display, or if raw=True raw JPEG data to | |
466 | display. |
|
481 | display. | |
467 | raw : bool |
|
482 | raw : bool | |
468 | Are the data objects raw data or Python objects that need to be |
|
483 | Are the data objects raw data or Python objects that need to be | |
469 | formatted before display? [default: False] |
|
484 | formatted before display? [default: False] | |
470 | metadata : dict (optional) |
|
485 | metadata : dict (optional) | |
471 | Metadata to be associated with the specific mimetype output. |
|
486 | Metadata to be associated with the specific mimetype output. | |
472 | """ |
|
487 | """ | |
473 | _display_mimetype('image/jpeg', objs, **kwargs) |
|
488 | _display_mimetype('image/jpeg', objs, **kwargs) | |
474 |
|
489 | |||
475 |
|
490 | |||
476 | def display_latex(*objs, **kwargs): |
|
491 | def display_latex(*objs, **kwargs): | |
477 | """Display the LaTeX representation of an object. |
|
492 | """Display the LaTeX representation of an object. | |
478 |
|
493 | |||
479 | Parameters |
|
494 | Parameters | |
480 | ---------- |
|
495 | ---------- | |
481 | objs : tuple of objects |
|
496 | objs : tuple of objects | |
482 | The Python objects to display, or if raw=True raw latex data to |
|
497 | The Python objects to display, or if raw=True raw latex data to | |
483 | display. |
|
498 | display. | |
484 | raw : bool |
|
499 | raw : bool | |
485 | Are the data objects raw data or Python objects that need to be |
|
500 | Are the data objects raw data or Python objects that need to be | |
486 | formatted before display? [default: False] |
|
501 | formatted before display? [default: False] | |
487 | metadata : dict (optional) |
|
502 | metadata : dict (optional) | |
488 | Metadata to be associated with the specific mimetype output. |
|
503 | Metadata to be associated with the specific mimetype output. | |
489 | """ |
|
504 | """ | |
490 | _display_mimetype('text/latex', objs, **kwargs) |
|
505 | _display_mimetype('text/latex', objs, **kwargs) | |
491 |
|
506 | |||
492 |
|
507 | |||
493 | def display_json(*objs, **kwargs): |
|
508 | def display_json(*objs, **kwargs): | |
494 | """Display the JSON representation of an object. |
|
509 | """Display the JSON representation of an object. | |
495 |
|
510 | |||
496 | Note that not many frontends support displaying JSON. |
|
511 | Note that not many frontends support displaying JSON. | |
497 |
|
512 | |||
498 | Parameters |
|
513 | Parameters | |
499 | ---------- |
|
514 | ---------- | |
500 | objs : tuple of objects |
|
515 | objs : tuple of objects | |
501 | The Python objects to display, or if raw=True raw json data to |
|
516 | The Python objects to display, or if raw=True raw json data to | |
502 | display. |
|
517 | display. | |
503 | raw : bool |
|
518 | raw : bool | |
504 | Are the data objects raw data or Python objects that need to be |
|
519 | Are the data objects raw data or Python objects that need to be | |
505 | formatted before display? [default: False] |
|
520 | formatted before display? [default: False] | |
506 | metadata : dict (optional) |
|
521 | metadata : dict (optional) | |
507 | Metadata to be associated with the specific mimetype output. |
|
522 | Metadata to be associated with the specific mimetype output. | |
508 | """ |
|
523 | """ | |
509 | _display_mimetype('application/json', objs, **kwargs) |
|
524 | _display_mimetype('application/json', objs, **kwargs) | |
510 |
|
525 | |||
511 |
|
526 | |||
512 | def display_javascript(*objs, **kwargs): |
|
527 | def display_javascript(*objs, **kwargs): | |
513 | """Display the Javascript representation of an object. |
|
528 | """Display the Javascript representation of an object. | |
514 |
|
529 | |||
515 | Parameters |
|
530 | Parameters | |
516 | ---------- |
|
531 | ---------- | |
517 | objs : tuple of objects |
|
532 | objs : tuple of objects | |
518 | The Python objects to display, or if raw=True raw javascript data to |
|
533 | The Python objects to display, or if raw=True raw javascript data to | |
519 | display. |
|
534 | display. | |
520 | raw : bool |
|
535 | raw : bool | |
521 | Are the data objects raw data or Python objects that need to be |
|
536 | Are the data objects raw data or Python objects that need to be | |
522 | formatted before display? [default: False] |
|
537 | formatted before display? [default: False] | |
523 | metadata : dict (optional) |
|
538 | metadata : dict (optional) | |
524 | Metadata to be associated with the specific mimetype output. |
|
539 | Metadata to be associated with the specific mimetype output. | |
525 | """ |
|
540 | """ | |
526 | _display_mimetype('application/javascript', objs, **kwargs) |
|
541 | _display_mimetype('application/javascript', objs, **kwargs) | |
527 |
|
542 | |||
528 |
|
543 | |||
529 | def display_pdf(*objs, **kwargs): |
|
544 | def display_pdf(*objs, **kwargs): | |
530 | """Display the PDF representation of an object. |
|
545 | """Display the PDF representation of an object. | |
531 |
|
546 | |||
532 | Parameters |
|
547 | Parameters | |
533 | ---------- |
|
548 | ---------- | |
534 | objs : tuple of objects |
|
549 | objs : tuple of objects | |
535 | The Python objects to display, or if raw=True raw javascript data to |
|
550 | The Python objects to display, or if raw=True raw javascript data to | |
536 | display. |
|
551 | display. | |
537 | raw : bool |
|
552 | raw : bool | |
538 | Are the data objects raw data or Python objects that need to be |
|
553 | Are the data objects raw data or Python objects that need to be | |
539 | formatted before display? [default: False] |
|
554 | formatted before display? [default: False] | |
540 | metadata : dict (optional) |
|
555 | metadata : dict (optional) | |
541 | Metadata to be associated with the specific mimetype output. |
|
556 | Metadata to be associated with the specific mimetype output. | |
542 | """ |
|
557 | """ | |
543 | _display_mimetype('application/pdf', objs, **kwargs) |
|
558 | _display_mimetype('application/pdf', objs, **kwargs) | |
544 |
|
559 | |||
545 |
|
560 | |||
546 | #----------------------------------------------------------------------------- |
|
561 | #----------------------------------------------------------------------------- | |
547 | # Smart classes |
|
562 | # Smart classes | |
548 | #----------------------------------------------------------------------------- |
|
563 | #----------------------------------------------------------------------------- | |
549 |
|
564 | |||
550 |
|
565 | |||
551 | class DisplayObject(object): |
|
566 | class DisplayObject(object): | |
552 | """An object that wraps data to be displayed.""" |
|
567 | """An object that wraps data to be displayed.""" | |
553 |
|
568 | |||
554 | _read_flags = 'r' |
|
569 | _read_flags = 'r' | |
555 | _show_mem_addr = False |
|
570 | _show_mem_addr = False | |
556 |
|
571 | |||
557 | def __init__(self, data=None, url=None, filename=None): |
|
572 | def __init__(self, data=None, url=None, filename=None): | |
558 | """Create a display object given raw data. |
|
573 | """Create a display object given raw data. | |
559 |
|
574 | |||
560 | When this object is returned by an expression or passed to the |
|
575 | When this object is returned by an expression or passed to the | |
561 | display function, it will result in the data being displayed |
|
576 | display function, it will result in the data being displayed | |
562 | in the frontend. The MIME type of the data should match the |
|
577 | in the frontend. The MIME type of the data should match the | |
563 | subclasses used, so the Png subclass should be used for 'image/png' |
|
578 | subclasses used, so the Png subclass should be used for 'image/png' | |
564 | data. If the data is a URL, the data will first be downloaded |
|
579 | data. If the data is a URL, the data will first be downloaded | |
565 | and then displayed. If |
|
580 | and then displayed. If | |
566 |
|
581 | |||
567 | Parameters |
|
582 | Parameters | |
568 | ---------- |
|
583 | ---------- | |
569 | data : unicode, str or bytes |
|
584 | data : unicode, str or bytes | |
570 | The raw data or a URL or file to load the data from |
|
585 | The raw data or a URL or file to load the data from | |
571 | url : unicode |
|
586 | url : unicode | |
572 | A URL to download the data from. |
|
587 | A URL to download the data from. | |
573 | filename : unicode |
|
588 | filename : unicode | |
574 | Path to a local file to load the data from. |
|
589 | Path to a local file to load the data from. | |
575 | """ |
|
590 | """ | |
576 | if data is not None and isinstance(data, str): |
|
591 | if data is not None and isinstance(data, str): | |
577 | if data.startswith('http') and url is None: |
|
592 | if data.startswith('http') and url is None: | |
578 | url = data |
|
593 | url = data | |
579 | filename = None |
|
594 | filename = None | |
580 | data = None |
|
595 | data = None | |
581 | elif _safe_exists(data) and filename is None: |
|
596 | elif _safe_exists(data) and filename is None: | |
582 | url = None |
|
597 | url = None | |
583 | filename = data |
|
598 | filename = data | |
584 | data = None |
|
599 | data = None | |
585 |
|
600 | |||
586 | self.data = data |
|
601 | self.data = data | |
587 | self.url = url |
|
602 | self.url = url | |
588 | self.filename = filename |
|
603 | self.filename = filename | |
589 |
|
604 | |||
590 | self.reload() |
|
605 | self.reload() | |
591 | self._check_data() |
|
606 | self._check_data() | |
592 |
|
607 | |||
593 | def __repr__(self): |
|
608 | def __repr__(self): | |
594 | if not self._show_mem_addr: |
|
609 | if not self._show_mem_addr: | |
595 | cls = self.__class__ |
|
610 | cls = self.__class__ | |
596 | r = "<%s.%s object>" % (cls.__module__, cls.__name__) |
|
611 | r = "<%s.%s object>" % (cls.__module__, cls.__name__) | |
597 | else: |
|
612 | else: | |
598 | r = super(DisplayObject, self).__repr__() |
|
613 | r = super(DisplayObject, self).__repr__() | |
599 | return r |
|
614 | return r | |
600 |
|
615 | |||
601 | def _check_data(self): |
|
616 | def _check_data(self): | |
602 | """Override in subclasses if there's something to check.""" |
|
617 | """Override in subclasses if there's something to check.""" | |
603 | pass |
|
618 | pass | |
604 |
|
619 | |||
605 | def reload(self): |
|
620 | def reload(self): | |
606 | """Reload the raw data from file or URL.""" |
|
621 | """Reload the raw data from file or URL.""" | |
607 | if self.filename is not None: |
|
622 | if self.filename is not None: | |
608 | with open(self.filename, self._read_flags) as f: |
|
623 | with open(self.filename, self._read_flags) as f: | |
609 | self.data = f.read() |
|
624 | self.data = f.read() | |
610 | elif self.url is not None: |
|
625 | elif self.url is not None: | |
611 | try: |
|
626 | try: | |
612 | # Deferred import |
|
627 | # Deferred import | |
613 | from urllib.request import urlopen |
|
628 | from urllib.request import urlopen | |
614 | response = urlopen(self.url) |
|
629 | response = urlopen(self.url) | |
615 | self.data = response.read() |
|
630 | self.data = response.read() | |
616 | # extract encoding from header, if there is one: |
|
631 | # extract encoding from header, if there is one: | |
617 | encoding = None |
|
632 | encoding = None | |
618 | for sub in response.headers['content-type'].split(';'): |
|
633 | for sub in response.headers['content-type'].split(';'): | |
619 | sub = sub.strip() |
|
634 | sub = sub.strip() | |
620 | if sub.startswith('charset'): |
|
635 | if sub.startswith('charset'): | |
621 | encoding = sub.split('=')[-1].strip() |
|
636 | encoding = sub.split('=')[-1].strip() | |
622 | break |
|
637 | break | |
623 | # decode data, if an encoding was specified |
|
638 | # decode data, if an encoding was specified | |
624 | if encoding: |
|
639 | if encoding: | |
625 | self.data = self.data.decode(encoding, 'replace') |
|
640 | self.data = self.data.decode(encoding, 'replace') | |
626 | except: |
|
641 | except: | |
627 | self.data = None |
|
642 | self.data = None | |
628 |
|
643 | |||
629 | class TextDisplayObject(DisplayObject): |
|
644 | class TextDisplayObject(DisplayObject): | |
630 | """Validate that display data is text""" |
|
645 | """Validate that display data is text""" | |
631 | def _check_data(self): |
|
646 | def _check_data(self): | |
632 | if self.data is not None and not isinstance(self.data, str): |
|
647 | if self.data is not None and not isinstance(self.data, str): | |
633 | raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data)) |
|
648 | raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data)) | |
634 |
|
649 | |||
635 | class Pretty(TextDisplayObject): |
|
650 | class Pretty(TextDisplayObject): | |
636 |
|
651 | |||
637 | def _repr_pretty_(self): |
|
652 | def _repr_pretty_(self): | |
638 | return self.data |
|
653 | return self.data | |
639 |
|
654 | |||
640 |
|
655 | |||
641 | class HTML(TextDisplayObject): |
|
656 | class HTML(TextDisplayObject): | |
642 |
|
657 | |||
643 | def _repr_html_(self): |
|
658 | def _repr_html_(self): | |
644 | return self.data |
|
659 | return self.data | |
645 |
|
660 | |||
646 | def __html__(self): |
|
661 | def __html__(self): | |
647 | """ |
|
662 | """ | |
648 | This method exists to inform other HTML-using modules (e.g. Markupsafe, |
|
663 | This method exists to inform other HTML-using modules (e.g. Markupsafe, | |
649 | htmltag, etc) that this object is HTML and does not need things like |
|
664 | htmltag, etc) that this object is HTML and does not need things like | |
650 | special characters (<>&) escaped. |
|
665 | special characters (<>&) escaped. | |
651 | """ |
|
666 | """ | |
652 | return self._repr_html_() |
|
667 | return self._repr_html_() | |
653 |
|
668 | |||
654 |
|
669 | |||
655 | class Markdown(TextDisplayObject): |
|
670 | class Markdown(TextDisplayObject): | |
656 |
|
671 | |||
657 | def _repr_markdown_(self): |
|
672 | def _repr_markdown_(self): | |
658 | return self.data |
|
673 | return self.data | |
659 |
|
674 | |||
660 |
|
675 | |||
661 | class Math(TextDisplayObject): |
|
676 | class Math(TextDisplayObject): | |
662 |
|
677 | |||
663 | def _repr_latex_(self): |
|
678 | def _repr_latex_(self): | |
664 | s = self.data.strip('$') |
|
679 | s = self.data.strip('$') | |
665 | return "$$%s$$" % s |
|
680 | return "$$%s$$" % s | |
666 |
|
681 | |||
667 |
|
682 | |||
668 | class Latex(TextDisplayObject): |
|
683 | class Latex(TextDisplayObject): | |
669 |
|
684 | |||
670 | def _repr_latex_(self): |
|
685 | def _repr_latex_(self): | |
671 | return self.data |
|
686 | return self.data | |
672 |
|
687 | |||
673 |
|
688 | |||
674 | class SVG(DisplayObject): |
|
689 | class SVG(DisplayObject): | |
675 |
|
690 | |||
676 | _read_flags = 'rb' |
|
691 | _read_flags = 'rb' | |
677 | # wrap data in a property, which extracts the <svg> tag, discarding |
|
692 | # wrap data in a property, which extracts the <svg> tag, discarding | |
678 | # document headers |
|
693 | # document headers | |
679 | _data = None |
|
694 | _data = None | |
680 |
|
695 | |||
681 | @property |
|
696 | @property | |
682 | def data(self): |
|
697 | def data(self): | |
683 | return self._data |
|
698 | return self._data | |
684 |
|
699 | |||
685 | @data.setter |
|
700 | @data.setter | |
686 | def data(self, svg): |
|
701 | def data(self, svg): | |
687 | if svg is None: |
|
702 | if svg is None: | |
688 | self._data = None |
|
703 | self._data = None | |
689 | return |
|
704 | return | |
690 | # parse into dom object |
|
705 | # parse into dom object | |
691 | from xml.dom import minidom |
|
706 | from xml.dom import minidom | |
692 | x = minidom.parseString(svg) |
|
707 | x = minidom.parseString(svg) | |
693 | # get svg tag (should be 1) |
|
708 | # get svg tag (should be 1) | |
694 | found_svg = x.getElementsByTagName('svg') |
|
709 | found_svg = x.getElementsByTagName('svg') | |
695 | if found_svg: |
|
710 | if found_svg: | |
696 | svg = found_svg[0].toxml() |
|
711 | svg = found_svg[0].toxml() | |
697 | else: |
|
712 | else: | |
698 | # fallback on the input, trust the user |
|
713 | # fallback on the input, trust the user | |
699 | # but this is probably an error. |
|
714 | # but this is probably an error. | |
700 | pass |
|
715 | pass | |
701 | svg = cast_unicode(svg) |
|
716 | svg = cast_unicode(svg) | |
702 | self._data = svg |
|
717 | self._data = svg | |
703 |
|
718 | |||
704 | def _repr_svg_(self): |
|
719 | def _repr_svg_(self): | |
705 | return self.data |
|
720 | return self.data | |
706 |
|
721 | |||
707 |
|
722 | |||
708 | class JSON(DisplayObject): |
|
723 | class JSON(DisplayObject): | |
709 | """JSON expects a JSON-able dict or list |
|
724 | """JSON expects a JSON-able dict or list | |
710 |
|
725 | |||
711 | not an already-serialized JSON string. |
|
726 | not an already-serialized JSON string. | |
712 |
|
727 | |||
713 | Scalar types (None, number, string) are not allowed, only dict or list containers. |
|
728 | Scalar types (None, number, string) are not allowed, only dict or list containers. | |
714 | """ |
|
729 | """ | |
715 | # wrap data in a property, which warns about passing already-serialized JSON |
|
730 | # wrap data in a property, which warns about passing already-serialized JSON | |
716 | _data = None |
|
731 | _data = None | |
717 | def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None, **kwargs): |
|
732 | def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None, **kwargs): | |
718 | """Create a JSON display object given raw data. |
|
733 | """Create a JSON display object given raw data. | |
719 |
|
734 | |||
720 | Parameters |
|
735 | Parameters | |
721 | ---------- |
|
736 | ---------- | |
722 | data : dict or list |
|
737 | data : dict or list | |
723 | JSON data to display. Not an already-serialized JSON string. |
|
738 | JSON data to display. Not an already-serialized JSON string. | |
724 | Scalar types (None, number, string) are not allowed, only dict |
|
739 | Scalar types (None, number, string) are not allowed, only dict | |
725 | or list containers. |
|
740 | or list containers. | |
726 | url : unicode |
|
741 | url : unicode | |
727 | A URL to download the data from. |
|
742 | A URL to download the data from. | |
728 | filename : unicode |
|
743 | filename : unicode | |
729 | Path to a local file to load the data from. |
|
744 | Path to a local file to load the data from. | |
730 | expanded : boolean |
|
745 | expanded : boolean | |
731 | Metadata to control whether a JSON display component is expanded. |
|
746 | Metadata to control whether a JSON display component is expanded. | |
732 | metadata: dict |
|
747 | metadata: dict | |
733 | Specify extra metadata to attach to the json display object. |
|
748 | Specify extra metadata to attach to the json display object. | |
734 | """ |
|
749 | """ | |
735 | self.metadata = {'expanded': expanded} |
|
750 | self.metadata = {'expanded': expanded} | |
736 | if metadata: |
|
751 | if metadata: | |
737 | self.metadata.update(metadata) |
|
752 | self.metadata.update(metadata) | |
738 | if kwargs: |
|
753 | if kwargs: | |
739 | self.metadata.update(kwargs) |
|
754 | self.metadata.update(kwargs) | |
740 | super(JSON, self).__init__(data=data, url=url, filename=filename) |
|
755 | super(JSON, self).__init__(data=data, url=url, filename=filename) | |
741 |
|
756 | |||
742 | def _check_data(self): |
|
757 | def _check_data(self): | |
743 | if self.data is not None and not isinstance(self.data, (dict, list)): |
|
758 | if self.data is not None and not isinstance(self.data, (dict, list)): | |
744 | raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data)) |
|
759 | raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data)) | |
745 |
|
760 | |||
746 | @property |
|
761 | @property | |
747 | def data(self): |
|
762 | def data(self): | |
748 | return self._data |
|
763 | return self._data | |
749 |
|
764 | |||
750 | @data.setter |
|
765 | @data.setter | |
751 | def data(self, data): |
|
766 | def data(self, data): | |
752 | if isinstance(data, str): |
|
767 | if isinstance(data, str): | |
753 | if getattr(self, 'filename', None) is None: |
|
768 | if getattr(self, 'filename', None) is None: | |
754 | warnings.warn("JSON expects JSONable dict or list, not JSON strings") |
|
769 | warnings.warn("JSON expects JSONable dict or list, not JSON strings") | |
755 | data = json.loads(data) |
|
770 | data = json.loads(data) | |
756 | self._data = data |
|
771 | self._data = data | |
757 |
|
772 | |||
758 | def _data_and_metadata(self): |
|
773 | def _data_and_metadata(self): | |
759 | return self.data, self.metadata |
|
774 | return self.data, self.metadata | |
760 |
|
775 | |||
761 | def _repr_json_(self): |
|
776 | def _repr_json_(self): | |
762 | return self._data_and_metadata() |
|
777 | return self._data_and_metadata() | |
763 |
|
778 | |||
764 | _css_t = """$("head").append($("<link/>").attr({ |
|
779 | _css_t = """$("head").append($("<link/>").attr({ | |
765 | rel: "stylesheet", |
|
780 | rel: "stylesheet", | |
766 | type: "text/css", |
|
781 | type: "text/css", | |
767 | href: "%s" |
|
782 | href: "%s" | |
768 | })); |
|
783 | })); | |
769 | """ |
|
784 | """ | |
770 |
|
785 | |||
771 | _lib_t1 = """$.getScript("%s", function () { |
|
786 | _lib_t1 = """$.getScript("%s", function () { | |
772 | """ |
|
787 | """ | |
773 | _lib_t2 = """}); |
|
788 | _lib_t2 = """}); | |
774 | """ |
|
789 | """ | |
775 |
|
790 | |||
776 | class GeoJSON(JSON): |
|
791 | class GeoJSON(JSON): | |
777 | """GeoJSON expects JSON-able dict |
|
792 | """GeoJSON expects JSON-able dict | |
778 |
|
793 | |||
779 | not an already-serialized JSON string. |
|
794 | not an already-serialized JSON string. | |
780 |
|
795 | |||
781 | Scalar types (None, number, string) are not allowed, only dict containers. |
|
796 | Scalar types (None, number, string) are not allowed, only dict containers. | |
782 | """ |
|
797 | """ | |
783 |
|
798 | |||
784 | def __init__(self, *args, **kwargs): |
|
799 | def __init__(self, *args, **kwargs): | |
785 | """Create a GeoJSON display object given raw data. |
|
800 | """Create a GeoJSON display object given raw data. | |
786 |
|
801 | |||
787 | Parameters |
|
802 | Parameters | |
788 | ---------- |
|
803 | ---------- | |
789 | data : dict or list |
|
804 | data : dict or list | |
790 | VegaLite data. Not an already-serialized JSON string. |
|
805 | VegaLite data. Not an already-serialized JSON string. | |
791 | Scalar types (None, number, string) are not allowed, only dict |
|
806 | Scalar types (None, number, string) are not allowed, only dict | |
792 | or list containers. |
|
807 | or list containers. | |
793 | url_template : string |
|
808 | url_template : string | |
794 | Leaflet TileLayer URL template: http://leafletjs.com/reference.html#url-template |
|
809 | Leaflet TileLayer URL template: http://leafletjs.com/reference.html#url-template | |
795 | layer_options : dict |
|
810 | layer_options : dict | |
796 | Leaflet TileLayer options: http://leafletjs.com/reference.html#tilelayer-options |
|
811 | Leaflet TileLayer options: http://leafletjs.com/reference.html#tilelayer-options | |
797 | url : unicode |
|
812 | url : unicode | |
798 | A URL to download the data from. |
|
813 | A URL to download the data from. | |
799 | filename : unicode |
|
814 | filename : unicode | |
800 | Path to a local file to load the data from. |
|
815 | Path to a local file to load the data from. | |
801 | metadata: dict |
|
816 | metadata: dict | |
802 | Specify extra metadata to attach to the json display object. |
|
817 | Specify extra metadata to attach to the json display object. | |
803 |
|
818 | |||
804 | Examples |
|
819 | Examples | |
805 | -------- |
|
820 | -------- | |
806 |
|
821 | |||
807 | The following will display an interactive map of Mars with a point of |
|
822 | The following will display an interactive map of Mars with a point of | |
808 | interest on frontend that do support GeoJSON display. |
|
823 | interest on frontend that do support GeoJSON display. | |
809 |
|
824 | |||
810 | >>> from IPython.display import GeoJSON |
|
825 | >>> from IPython.display import GeoJSON | |
811 |
|
826 | |||
812 | >>> GeoJSON(data={ |
|
827 | >>> GeoJSON(data={ | |
813 | ... "type": "Feature", |
|
828 | ... "type": "Feature", | |
814 | ... "geometry": { |
|
829 | ... "geometry": { | |
815 | ... "type": "Point", |
|
830 | ... "type": "Point", | |
816 | ... "coordinates": [-81.327, 296.038] |
|
831 | ... "coordinates": [-81.327, 296.038] | |
817 | ... } |
|
832 | ... } | |
818 | ... }, |
|
833 | ... }, | |
819 | ... url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png", |
|
834 | ... url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png", | |
820 | ... layer_options={ |
|
835 | ... layer_options={ | |
821 | ... "basemap_id": "celestia_mars-shaded-16k_global", |
|
836 | ... "basemap_id": "celestia_mars-shaded-16k_global", | |
822 | ... "attribution" : "Celestia/praesepe", |
|
837 | ... "attribution" : "Celestia/praesepe", | |
823 | ... "minZoom" : 0, |
|
838 | ... "minZoom" : 0, | |
824 | ... "maxZoom" : 18, |
|
839 | ... "maxZoom" : 18, | |
825 | ... }) |
|
840 | ... }) | |
826 | <IPython.core.display.GeoJSON object> |
|
841 | <IPython.core.display.GeoJSON object> | |
827 |
|
842 | |||
828 | In the terminal IPython, you will only see the text representation of |
|
843 | In the terminal IPython, you will only see the text representation of | |
829 | the GeoJSON object. |
|
844 | the GeoJSON object. | |
830 |
|
845 | |||
831 | """ |
|
846 | """ | |
832 |
|
847 | |||
833 | super(GeoJSON, self).__init__(*args, **kwargs) |
|
848 | super(GeoJSON, self).__init__(*args, **kwargs) | |
834 |
|
849 | |||
835 |
|
850 | |||
836 | def _ipython_display_(self): |
|
851 | def _ipython_display_(self): | |
837 | bundle = { |
|
852 | bundle = { | |
838 | 'application/geo+json': self.data, |
|
853 | 'application/geo+json': self.data, | |
839 | 'text/plain': '<IPython.display.GeoJSON object>' |
|
854 | 'text/plain': '<IPython.display.GeoJSON object>' | |
840 | } |
|
855 | } | |
841 | metadata = { |
|
856 | metadata = { | |
842 | 'application/geo+json': self.metadata |
|
857 | 'application/geo+json': self.metadata | |
843 | } |
|
858 | } | |
844 | display(bundle, metadata=metadata, raw=True) |
|
859 | display(bundle, metadata=metadata, raw=True) | |
845 |
|
860 | |||
846 | class Javascript(TextDisplayObject): |
|
861 | class Javascript(TextDisplayObject): | |
847 |
|
862 | |||
848 | def __init__(self, data=None, url=None, filename=None, lib=None, css=None): |
|
863 | def __init__(self, data=None, url=None, filename=None, lib=None, css=None): | |
849 | """Create a Javascript display object given raw data. |
|
864 | """Create a Javascript display object given raw data. | |
850 |
|
865 | |||
851 | When this object is returned by an expression or passed to the |
|
866 | When this object is returned by an expression or passed to the | |
852 | display function, it will result in the data being displayed |
|
867 | display function, it will result in the data being displayed | |
853 | in the frontend. If the data is a URL, the data will first be |
|
868 | in the frontend. If the data is a URL, the data will first be | |
854 | downloaded and then displayed. |
|
869 | downloaded and then displayed. | |
855 |
|
870 | |||
856 | In the Notebook, the containing element will be available as `element`, |
|
871 | In the Notebook, the containing element will be available as `element`, | |
857 | and jQuery will be available. Content appended to `element` will be |
|
872 | and jQuery will be available. Content appended to `element` will be | |
858 | visible in the output area. |
|
873 | visible in the output area. | |
859 |
|
874 | |||
860 | Parameters |
|
875 | Parameters | |
861 | ---------- |
|
876 | ---------- | |
862 | data : unicode, str or bytes |
|
877 | data : unicode, str or bytes | |
863 | The Javascript source code or a URL to download it from. |
|
878 | The Javascript source code or a URL to download it from. | |
864 | url : unicode |
|
879 | url : unicode | |
865 | A URL to download the data from. |
|
880 | A URL to download the data from. | |
866 | filename : unicode |
|
881 | filename : unicode | |
867 | Path to a local file to load the data from. |
|
882 | Path to a local file to load the data from. | |
868 | lib : list or str |
|
883 | lib : list or str | |
869 | A sequence of Javascript library URLs to load asynchronously before |
|
884 | A sequence of Javascript library URLs to load asynchronously before | |
870 | running the source code. The full URLs of the libraries should |
|
885 | running the source code. The full URLs of the libraries should | |
871 | be given. A single Javascript library URL can also be given as a |
|
886 | be given. A single Javascript library URL can also be given as a | |
872 | string. |
|
887 | string. | |
873 | css: : list or str |
|
888 | css: : list or str | |
874 | A sequence of css files to load before running the source code. |
|
889 | A sequence of css files to load before running the source code. | |
875 | The full URLs of the css files should be given. A single css URL |
|
890 | The full URLs of the css files should be given. A single css URL | |
876 | can also be given as a string. |
|
891 | can also be given as a string. | |
877 | """ |
|
892 | """ | |
878 | if isinstance(lib, str): |
|
893 | if isinstance(lib, str): | |
879 | lib = [lib] |
|
894 | lib = [lib] | |
880 | elif lib is None: |
|
895 | elif lib is None: | |
881 | lib = [] |
|
896 | lib = [] | |
882 | if isinstance(css, str): |
|
897 | if isinstance(css, str): | |
883 | css = [css] |
|
898 | css = [css] | |
884 | elif css is None: |
|
899 | elif css is None: | |
885 | css = [] |
|
900 | css = [] | |
886 | if not isinstance(lib, (list,tuple)): |
|
901 | if not isinstance(lib, (list,tuple)): | |
887 | raise TypeError('expected sequence, got: %r' % lib) |
|
902 | raise TypeError('expected sequence, got: %r' % lib) | |
888 | if not isinstance(css, (list,tuple)): |
|
903 | if not isinstance(css, (list,tuple)): | |
889 | raise TypeError('expected sequence, got: %r' % css) |
|
904 | raise TypeError('expected sequence, got: %r' % css) | |
890 | self.lib = lib |
|
905 | self.lib = lib | |
891 | self.css = css |
|
906 | self.css = css | |
892 | super(Javascript, self).__init__(data=data, url=url, filename=filename) |
|
907 | super(Javascript, self).__init__(data=data, url=url, filename=filename) | |
893 |
|
908 | |||
894 | def _repr_javascript_(self): |
|
909 | def _repr_javascript_(self): | |
895 | r = '' |
|
910 | r = '' | |
896 | for c in self.css: |
|
911 | for c in self.css: | |
897 | r += _css_t % c |
|
912 | r += _css_t % c | |
898 | for l in self.lib: |
|
913 | for l in self.lib: | |
899 | r += _lib_t1 % l |
|
914 | r += _lib_t1 % l | |
900 | r += self.data |
|
915 | r += self.data | |
901 | r += _lib_t2*len(self.lib) |
|
916 | r += _lib_t2*len(self.lib) | |
902 | return r |
|
917 | return r | |
903 |
|
918 | |||
904 | # constants for identifying png/jpeg data |
|
919 | # constants for identifying png/jpeg data | |
905 | _PNG = b'\x89PNG\r\n\x1a\n' |
|
920 | _PNG = b'\x89PNG\r\n\x1a\n' | |
906 | _JPEG = b'\xff\xd8' |
|
921 | _JPEG = b'\xff\xd8' | |
907 |
|
922 | |||
908 | def _pngxy(data): |
|
923 | def _pngxy(data): | |
909 | """read the (width, height) from a PNG header""" |
|
924 | """read the (width, height) from a PNG header""" | |
910 | ihdr = data.index(b'IHDR') |
|
925 | ihdr = data.index(b'IHDR') | |
911 | # next 8 bytes are width/height |
|
926 | # next 8 bytes are width/height | |
912 | w4h4 = data[ihdr+4:ihdr+12] |
|
927 | w4h4 = data[ihdr+4:ihdr+12] | |
913 | return struct.unpack('>ii', w4h4) |
|
928 | return struct.unpack('>ii', w4h4) | |
914 |
|
929 | |||
915 | def _jpegxy(data): |
|
930 | def _jpegxy(data): | |
916 | """read the (width, height) from a JPEG header""" |
|
931 | """read the (width, height) from a JPEG header""" | |
917 | # adapted from http://www.64lines.com/jpeg-width-height |
|
932 | # adapted from http://www.64lines.com/jpeg-width-height | |
918 |
|
933 | |||
919 | idx = 4 |
|
934 | idx = 4 | |
920 | while True: |
|
935 | while True: | |
921 | block_size = struct.unpack('>H', data[idx:idx+2])[0] |
|
936 | block_size = struct.unpack('>H', data[idx:idx+2])[0] | |
922 | idx = idx + block_size |
|
937 | idx = idx + block_size | |
923 | if data[idx:idx+2] == b'\xFF\xC0': |
|
938 | if data[idx:idx+2] == b'\xFF\xC0': | |
924 | # found Start of Frame |
|
939 | # found Start of Frame | |
925 | iSOF = idx |
|
940 | iSOF = idx | |
926 | break |
|
941 | break | |
927 | else: |
|
942 | else: | |
928 | # read another block |
|
943 | # read another block | |
929 | idx += 2 |
|
944 | idx += 2 | |
930 |
|
945 | |||
931 | h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9]) |
|
946 | h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9]) | |
932 | return w, h |
|
947 | return w, h | |
933 |
|
948 | |||
934 | class Image(DisplayObject): |
|
949 | class Image(DisplayObject): | |
935 |
|
950 | |||
936 | _read_flags = 'rb' |
|
951 | _read_flags = 'rb' | |
937 | _FMT_JPEG = u'jpeg' |
|
952 | _FMT_JPEG = u'jpeg' | |
938 | _FMT_PNG = u'png' |
|
953 | _FMT_PNG = u'png' | |
939 | _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG] |
|
954 | _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG] | |
940 |
|
955 | |||
941 | def __init__(self, data=None, url=None, filename=None, format=None, |
|
956 | def __init__(self, data=None, url=None, filename=None, format=None, | |
942 | embed=None, width=None, height=None, retina=False, |
|
957 | embed=None, width=None, height=None, retina=False, | |
943 | unconfined=False, metadata=None): |
|
958 | unconfined=False, metadata=None): | |
944 | """Create a PNG/JPEG image object given raw data. |
|
959 | """Create a PNG/JPEG image object given raw data. | |
945 |
|
960 | |||
946 | When this object is returned by an input cell or passed to the |
|
961 | When this object is returned by an input cell or passed to the | |
947 | display function, it will result in the image being displayed |
|
962 | display function, it will result in the image being displayed | |
948 | in the frontend. |
|
963 | in the frontend. | |
949 |
|
964 | |||
950 | Parameters |
|
965 | Parameters | |
951 | ---------- |
|
966 | ---------- | |
952 | data : unicode, str or bytes |
|
967 | data : unicode, str or bytes | |
953 | The raw image data or a URL or filename to load the data from. |
|
968 | The raw image data or a URL or filename to load the data from. | |
954 | This always results in embedded image data. |
|
969 | This always results in embedded image data. | |
955 | url : unicode |
|
970 | url : unicode | |
956 | A URL to download the data from. If you specify `url=`, |
|
971 | A URL to download the data from. If you specify `url=`, | |
957 | the image data will not be embedded unless you also specify `embed=True`. |
|
972 | the image data will not be embedded unless you also specify `embed=True`. | |
958 | filename : unicode |
|
973 | filename : unicode | |
959 | Path to a local file to load the data from. |
|
974 | Path to a local file to load the data from. | |
960 | Images from a file are always embedded. |
|
975 | Images from a file are always embedded. | |
961 | format : unicode |
|
976 | format : unicode | |
962 | The format of the image data (png/jpeg/jpg). If a filename or URL is given |
|
977 | The format of the image data (png/jpeg/jpg). If a filename or URL is given | |
963 | for format will be inferred from the filename extension. |
|
978 | for format will be inferred from the filename extension. | |
964 | embed : bool |
|
979 | embed : bool | |
965 | Should the image data be embedded using a data URI (True) or be |
|
980 | Should the image data be embedded using a data URI (True) or be | |
966 | loaded using an <img> tag. Set this to True if you want the image |
|
981 | loaded using an <img> tag. Set this to True if you want the image | |
967 | to be viewable later with no internet connection in the notebook. |
|
982 | to be viewable later with no internet connection in the notebook. | |
968 |
|
983 | |||
969 | Default is `True`, unless the keyword argument `url` is set, then |
|
984 | Default is `True`, unless the keyword argument `url` is set, then | |
970 | default value is `False`. |
|
985 | default value is `False`. | |
971 |
|
986 | |||
972 | Note that QtConsole is not able to display images if `embed` is set to `False` |
|
987 | Note that QtConsole is not able to display images if `embed` is set to `False` | |
973 | width : int |
|
988 | width : int | |
974 | Width in pixels to which to constrain the image in html |
|
989 | Width in pixels to which to constrain the image in html | |
975 | height : int |
|
990 | height : int | |
976 | Height in pixels to which to constrain the image in html |
|
991 | Height in pixels to which to constrain the image in html | |
977 | retina : bool |
|
992 | retina : bool | |
978 | Automatically set the width and height to half of the measured |
|
993 | Automatically set the width and height to half of the measured | |
979 | width and height. |
|
994 | width and height. | |
980 | This only works for embedded images because it reads the width/height |
|
995 | This only works for embedded images because it reads the width/height | |
981 | from image data. |
|
996 | from image data. | |
982 | For non-embedded images, you can just set the desired display width |
|
997 | For non-embedded images, you can just set the desired display width | |
983 | and height directly. |
|
998 | and height directly. | |
984 | unconfined: bool |
|
999 | unconfined: bool | |
985 | Set unconfined=True to disable max-width confinement of the image. |
|
1000 | Set unconfined=True to disable max-width confinement of the image. | |
986 | metadata: dict |
|
1001 | metadata: dict | |
987 | Specify extra metadata to attach to the image. |
|
1002 | Specify extra metadata to attach to the image. | |
988 |
|
1003 | |||
989 | Examples |
|
1004 | Examples | |
990 | -------- |
|
1005 | -------- | |
991 | # embedded image data, works in qtconsole and notebook |
|
1006 | # embedded image data, works in qtconsole and notebook | |
992 | # when passed positionally, the first arg can be any of raw image data, |
|
1007 | # when passed positionally, the first arg can be any of raw image data, | |
993 | # a URL, or a filename from which to load image data. |
|
1008 | # a URL, or a filename from which to load image data. | |
994 | # The result is always embedding image data for inline images. |
|
1009 | # The result is always embedding image data for inline images. | |
995 | Image('http://www.google.fr/images/srpr/logo3w.png') |
|
1010 | Image('http://www.google.fr/images/srpr/logo3w.png') | |
996 | Image('/path/to/image.jpg') |
|
1011 | Image('/path/to/image.jpg') | |
997 | Image(b'RAW_PNG_DATA...') |
|
1012 | Image(b'RAW_PNG_DATA...') | |
998 |
|
1013 | |||
999 | # Specifying Image(url=...) does not embed the image data, |
|
1014 | # Specifying Image(url=...) does not embed the image data, | |
1000 | # it only generates `<img>` tag with a link to the source. |
|
1015 | # it only generates `<img>` tag with a link to the source. | |
1001 | # This will not work in the qtconsole or offline. |
|
1016 | # This will not work in the qtconsole or offline. | |
1002 | Image(url='http://www.google.fr/images/srpr/logo3w.png') |
|
1017 | Image(url='http://www.google.fr/images/srpr/logo3w.png') | |
1003 |
|
1018 | |||
1004 | """ |
|
1019 | """ | |
1005 | if filename is not None: |
|
1020 | if filename is not None: | |
1006 | ext = self._find_ext(filename) |
|
1021 | ext = self._find_ext(filename) | |
1007 | elif url is not None: |
|
1022 | elif url is not None: | |
1008 | ext = self._find_ext(url) |
|
1023 | ext = self._find_ext(url) | |
1009 | elif data is None: |
|
1024 | elif data is None: | |
1010 | raise ValueError("No image data found. Expecting filename, url, or data.") |
|
1025 | raise ValueError("No image data found. Expecting filename, url, or data.") | |
1011 | elif isinstance(data, str) and ( |
|
1026 | elif isinstance(data, str) and ( | |
1012 | data.startswith('http') or _safe_exists(data) |
|
1027 | data.startswith('http') or _safe_exists(data) | |
1013 | ): |
|
1028 | ): | |
1014 | ext = self._find_ext(data) |
|
1029 | ext = self._find_ext(data) | |
1015 | else: |
|
1030 | else: | |
1016 | ext = None |
|
1031 | ext = None | |
1017 |
|
1032 | |||
1018 | if format is None: |
|
1033 | if format is None: | |
1019 | if ext is not None: |
|
1034 | if ext is not None: | |
1020 | if ext == u'jpg' or ext == u'jpeg': |
|
1035 | if ext == u'jpg' or ext == u'jpeg': | |
1021 | format = self._FMT_JPEG |
|
1036 | format = self._FMT_JPEG | |
1022 | if ext == u'png': |
|
1037 | if ext == u'png': | |
1023 | format = self._FMT_PNG |
|
1038 | format = self._FMT_PNG | |
1024 | else: |
|
1039 | else: | |
1025 | format = ext.lower() |
|
1040 | format = ext.lower() | |
1026 | elif isinstance(data, bytes): |
|
1041 | elif isinstance(data, bytes): | |
1027 | # infer image type from image data header, |
|
1042 | # infer image type from image data header, | |
1028 | # only if format has not been specified. |
|
1043 | # only if format has not been specified. | |
1029 | if data[:2] == _JPEG: |
|
1044 | if data[:2] == _JPEG: | |
1030 | format = self._FMT_JPEG |
|
1045 | format = self._FMT_JPEG | |
1031 |
|
1046 | |||
1032 | # failed to detect format, default png |
|
1047 | # failed to detect format, default png | |
1033 | if format is None: |
|
1048 | if format is None: | |
1034 | format = 'png' |
|
1049 | format = 'png' | |
1035 |
|
1050 | |||
1036 | if format.lower() == 'jpg': |
|
1051 | if format.lower() == 'jpg': | |
1037 | # jpg->jpeg |
|
1052 | # jpg->jpeg | |
1038 | format = self._FMT_JPEG |
|
1053 | format = self._FMT_JPEG | |
1039 |
|
1054 | |||
1040 | self.format = format.lower() |
|
1055 | self.format = format.lower() | |
1041 | self.embed = embed if embed is not None else (url is None) |
|
1056 | self.embed = embed if embed is not None else (url is None) | |
1042 |
|
1057 | |||
1043 | if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS: |
|
1058 | if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS: | |
1044 | raise ValueError("Cannot embed the '%s' image format" % (self.format)) |
|
1059 | raise ValueError("Cannot embed the '%s' image format" % (self.format)) | |
1045 | self.width = width |
|
1060 | self.width = width | |
1046 | self.height = height |
|
1061 | self.height = height | |
1047 | self.retina = retina |
|
1062 | self.retina = retina | |
1048 | self.unconfined = unconfined |
|
1063 | self.unconfined = unconfined | |
1049 | self.metadata = metadata |
|
1064 | self.metadata = metadata | |
1050 | super(Image, self).__init__(data=data, url=url, filename=filename) |
|
1065 | super(Image, self).__init__(data=data, url=url, filename=filename) | |
1051 |
|
1066 | |||
1052 | if retina: |
|
1067 | if retina: | |
1053 | self._retina_shape() |
|
1068 | self._retina_shape() | |
1054 |
|
1069 | |||
1055 | def _retina_shape(self): |
|
1070 | def _retina_shape(self): | |
1056 | """load pixel-doubled width and height from image data""" |
|
1071 | """load pixel-doubled width and height from image data""" | |
1057 | if not self.embed: |
|
1072 | if not self.embed: | |
1058 | return |
|
1073 | return | |
1059 | if self.format == 'png': |
|
1074 | if self.format == 'png': | |
1060 | w, h = _pngxy(self.data) |
|
1075 | w, h = _pngxy(self.data) | |
1061 | elif self.format == 'jpeg': |
|
1076 | elif self.format == 'jpeg': | |
1062 | w, h = _jpegxy(self.data) |
|
1077 | w, h = _jpegxy(self.data) | |
1063 | else: |
|
1078 | else: | |
1064 | # retina only supports png |
|
1079 | # retina only supports png | |
1065 | return |
|
1080 | return | |
1066 | self.width = w // 2 |
|
1081 | self.width = w // 2 | |
1067 | self.height = h // 2 |
|
1082 | self.height = h // 2 | |
1068 |
|
1083 | |||
1069 | def reload(self): |
|
1084 | def reload(self): | |
1070 | """Reload the raw data from file or URL.""" |
|
1085 | """Reload the raw data from file or URL.""" | |
1071 | if self.embed: |
|
1086 | if self.embed: | |
1072 | super(Image,self).reload() |
|
1087 | super(Image,self).reload() | |
1073 | if self.retina: |
|
1088 | if self.retina: | |
1074 | self._retina_shape() |
|
1089 | self._retina_shape() | |
1075 |
|
1090 | |||
1076 | def _repr_html_(self): |
|
1091 | def _repr_html_(self): | |
1077 | if not self.embed: |
|
1092 | if not self.embed: | |
1078 | width = height = klass = '' |
|
1093 | width = height = klass = '' | |
1079 | if self.width: |
|
1094 | if self.width: | |
1080 | width = ' width="%d"' % self.width |
|
1095 | width = ' width="%d"' % self.width | |
1081 | if self.height: |
|
1096 | if self.height: | |
1082 | height = ' height="%d"' % self.height |
|
1097 | height = ' height="%d"' % self.height | |
1083 | if self.unconfined: |
|
1098 | if self.unconfined: | |
1084 | klass = ' class="unconfined"' |
|
1099 | klass = ' class="unconfined"' | |
1085 | return u'<img src="{url}"{width}{height}{klass}/>'.format( |
|
1100 | return u'<img src="{url}"{width}{height}{klass}/>'.format( | |
1086 | url=self.url, |
|
1101 | url=self.url, | |
1087 | width=width, |
|
1102 | width=width, | |
1088 | height=height, |
|
1103 | height=height, | |
1089 | klass=klass, |
|
1104 | klass=klass, | |
1090 | ) |
|
1105 | ) | |
1091 |
|
1106 | |||
1092 | def _data_and_metadata(self): |
|
1107 | def _data_and_metadata(self): | |
1093 | """shortcut for returning metadata with shape information, if defined""" |
|
1108 | """shortcut for returning metadata with shape information, if defined""" | |
1094 | md = {} |
|
1109 | md = {} | |
1095 | if self.width: |
|
1110 | if self.width: | |
1096 | md['width'] = self.width |
|
1111 | md['width'] = self.width | |
1097 | if self.height: |
|
1112 | if self.height: | |
1098 | md['height'] = self.height |
|
1113 | md['height'] = self.height | |
1099 | if self.unconfined: |
|
1114 | if self.unconfined: | |
1100 | md['unconfined'] = self.unconfined |
|
1115 | md['unconfined'] = self.unconfined | |
1101 | if self.metadata: |
|
1116 | if self.metadata: | |
1102 | md.update(self.metadata) |
|
1117 | md.update(self.metadata) | |
1103 | if md: |
|
1118 | if md: | |
1104 | return self.data, md |
|
1119 | return self.data, md | |
1105 | else: |
|
1120 | else: | |
1106 | return self.data |
|
1121 | return self.data | |
1107 |
|
1122 | |||
1108 | def _repr_png_(self): |
|
1123 | def _repr_png_(self): | |
1109 | if self.embed and self.format == u'png': |
|
1124 | if self.embed and self.format == u'png': | |
1110 | return self._data_and_metadata() |
|
1125 | return self._data_and_metadata() | |
1111 |
|
1126 | |||
1112 | def _repr_jpeg_(self): |
|
1127 | def _repr_jpeg_(self): | |
1113 | if self.embed and (self.format == u'jpeg' or self.format == u'jpg'): |
|
1128 | if self.embed and (self.format == u'jpeg' or self.format == u'jpg'): | |
1114 | return self._data_and_metadata() |
|
1129 | return self._data_and_metadata() | |
1115 |
|
1130 | |||
1116 | def _find_ext(self, s): |
|
1131 | def _find_ext(self, s): | |
1117 | return s.split('.')[-1].lower() |
|
1132 | return s.split('.')[-1].lower() | |
1118 |
|
1133 | |||
1119 | class Video(DisplayObject): |
|
1134 | class Video(DisplayObject): | |
1120 |
|
1135 | |||
1121 | def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None): |
|
1136 | def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None): | |
1122 | """Create a video object given raw data or an URL. |
|
1137 | """Create a video object given raw data or an URL. | |
1123 |
|
1138 | |||
1124 | When this object is returned by an input cell or passed to the |
|
1139 | When this object is returned by an input cell or passed to the | |
1125 | display function, it will result in the video being displayed |
|
1140 | display function, it will result in the video being displayed | |
1126 | in the frontend. |
|
1141 | in the frontend. | |
1127 |
|
1142 | |||
1128 | Parameters |
|
1143 | Parameters | |
1129 | ---------- |
|
1144 | ---------- | |
1130 | data : unicode, str or bytes |
|
1145 | data : unicode, str or bytes | |
1131 | The raw video data or a URL or filename to load the data from. |
|
1146 | The raw video data or a URL or filename to load the data from. | |
1132 | Raw data will require passing `embed=True`. |
|
1147 | Raw data will require passing `embed=True`. | |
1133 | url : unicode |
|
1148 | url : unicode | |
1134 | A URL for the video. If you specify `url=`, |
|
1149 | A URL for the video. If you specify `url=`, | |
1135 | the image data will not be embedded. |
|
1150 | the image data will not be embedded. | |
1136 | filename : unicode |
|
1151 | filename : unicode | |
1137 | Path to a local file containing the video. |
|
1152 | Path to a local file containing the video. | |
1138 | Will be interpreted as a local URL unless `embed=True`. |
|
1153 | Will be interpreted as a local URL unless `embed=True`. | |
1139 | embed : bool |
|
1154 | embed : bool | |
1140 | Should the video be embedded using a data URI (True) or be |
|
1155 | Should the video be embedded using a data URI (True) or be | |
1141 | loaded using a <video> tag (False). |
|
1156 | loaded using a <video> tag (False). | |
1142 |
|
1157 | |||
1143 | Since videos are large, embedding them should be avoided, if possible. |
|
1158 | Since videos are large, embedding them should be avoided, if possible. | |
1144 | You must confirm embedding as your intention by passing `embed=True`. |
|
1159 | You must confirm embedding as your intention by passing `embed=True`. | |
1145 |
|
1160 | |||
1146 | Local files can be displayed with URLs without embedding the content, via:: |
|
1161 | Local files can be displayed with URLs without embedding the content, via:: | |
1147 |
|
1162 | |||
1148 | Video('./video.mp4') |
|
1163 | Video('./video.mp4') | |
1149 |
|
1164 | |||
1150 | mimetype: unicode |
|
1165 | mimetype: unicode | |
1151 | Specify the mimetype for embedded videos. |
|
1166 | Specify the mimetype for embedded videos. | |
1152 | Default will be guessed from file extension, if available. |
|
1167 | Default will be guessed from file extension, if available. | |
1153 |
|
1168 | |||
1154 | Examples |
|
1169 | Examples | |
1155 | -------- |
|
1170 | -------- | |
1156 |
|
1171 | |||
1157 | Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4') |
|
1172 | Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4') | |
1158 | Video('path/to/video.mp4') |
|
1173 | Video('path/to/video.mp4') | |
1159 | Video('path/to/video.mp4', embed=True) |
|
1174 | Video('path/to/video.mp4', embed=True) | |
1160 | Video(b'raw-videodata', embed=True) |
|
1175 | Video(b'raw-videodata', embed=True) | |
1161 | """ |
|
1176 | """ | |
1162 | if url is None and isinstance(data, str) and data.startswith(('http:', 'https:')): |
|
1177 | if url is None and isinstance(data, str) and data.startswith(('http:', 'https:')): | |
1163 | url = data |
|
1178 | url = data | |
1164 | data = None |
|
1179 | data = None | |
1165 | elif os.path.exists(data): |
|
1180 | elif os.path.exists(data): | |
1166 | filename = data |
|
1181 | filename = data | |
1167 | data = None |
|
1182 | data = None | |
1168 |
|
1183 | |||
1169 | if data and not embed: |
|
1184 | if data and not embed: | |
1170 | msg = ''.join([ |
|
1185 | msg = ''.join([ | |
1171 | "To embed videos, you must pass embed=True ", |
|
1186 | "To embed videos, you must pass embed=True ", | |
1172 | "(this may make your notebook files huge)\n", |
|
1187 | "(this may make your notebook files huge)\n", | |
1173 | "Consider passing Video(url='...')", |
|
1188 | "Consider passing Video(url='...')", | |
1174 | ]) |
|
1189 | ]) | |
1175 | raise ValueError(msg) |
|
1190 | raise ValueError(msg) | |
1176 |
|
1191 | |||
1177 | self.mimetype = mimetype |
|
1192 | self.mimetype = mimetype | |
1178 | self.embed = embed |
|
1193 | self.embed = embed | |
1179 | super(Video, self).__init__(data=data, url=url, filename=filename) |
|
1194 | super(Video, self).__init__(data=data, url=url, filename=filename) | |
1180 |
|
1195 | |||
1181 | def _repr_html_(self): |
|
1196 | def _repr_html_(self): | |
1182 | # External URLs and potentially local files are not embedded into the |
|
1197 | # External URLs and potentially local files are not embedded into the | |
1183 | # notebook output. |
|
1198 | # notebook output. | |
1184 | if not self.embed: |
|
1199 | if not self.embed: | |
1185 | url = self.url if self.url is not None else self.filename |
|
1200 | url = self.url if self.url is not None else self.filename | |
1186 | output = """<video src="{0}" controls> |
|
1201 | output = """<video src="{0}" controls> | |
1187 | Your browser does not support the <code>video</code> element. |
|
1202 | Your browser does not support the <code>video</code> element. | |
1188 | </video>""".format(url) |
|
1203 | </video>""".format(url) | |
1189 | return output |
|
1204 | return output | |
1190 |
|
1205 | |||
1191 | # Embedded videos are base64-encoded. |
|
1206 | # Embedded videos are base64-encoded. | |
1192 | mimetype = self.mimetype |
|
1207 | mimetype = self.mimetype | |
1193 | if self.filename is not None: |
|
1208 | if self.filename is not None: | |
1194 | if not mimetype: |
|
1209 | if not mimetype: | |
1195 | mimetype, _ = mimetypes.guess_type(self.filename) |
|
1210 | mimetype, _ = mimetypes.guess_type(self.filename) | |
1196 |
|
1211 | |||
1197 | with open(self.filename, 'rb') as f: |
|
1212 | with open(self.filename, 'rb') as f: | |
1198 | video = f.read() |
|
1213 | video = f.read() | |
1199 | else: |
|
1214 | else: | |
1200 | video = self.data |
|
1215 | video = self.data | |
1201 | if isinstance(video, str): |
|
1216 | if isinstance(video, str): | |
1202 | # unicode input is already b64-encoded |
|
1217 | # unicode input is already b64-encoded | |
1203 | b64_video = video |
|
1218 | b64_video = video | |
1204 | else: |
|
1219 | else: | |
1205 | b64_video = base64_encode(video).decode('ascii').rstrip() |
|
1220 | b64_video = base64_encode(video).decode('ascii').rstrip() | |
1206 |
|
1221 | |||
1207 | output = """<video controls> |
|
1222 | output = """<video controls> | |
1208 | <source src="data:{0};base64,{1}" type="{0}"> |
|
1223 | <source src="data:{0};base64,{1}" type="{0}"> | |
1209 | Your browser does not support the video tag. |
|
1224 | Your browser does not support the video tag. | |
1210 | </video>""".format(mimetype, b64_video) |
|
1225 | </video>""".format(mimetype, b64_video) | |
1211 | return output |
|
1226 | return output | |
1212 |
|
1227 | |||
1213 | def reload(self): |
|
1228 | def reload(self): | |
1214 | # TODO |
|
1229 | # TODO | |
1215 | pass |
|
1230 | pass | |
1216 |
|
1231 | |||
1217 | def _repr_png_(self): |
|
1232 | def _repr_png_(self): | |
1218 | # TODO |
|
1233 | # TODO | |
1219 | pass |
|
1234 | pass | |
1220 | def _repr_jpeg_(self): |
|
1235 | def _repr_jpeg_(self): | |
1221 | # TODO |
|
1236 | # TODO | |
1222 | pass |
|
1237 | pass | |
1223 |
|
1238 | |||
1224 | def clear_output(wait=False): |
|
1239 | def clear_output(wait=False): | |
1225 | """Clear the output of the current cell receiving output. |
|
1240 | """Clear the output of the current cell receiving output. | |
1226 |
|
1241 | |||
1227 | Parameters |
|
1242 | Parameters | |
1228 | ---------- |
|
1243 | ---------- | |
1229 | wait : bool [default: false] |
|
1244 | wait : bool [default: false] | |
1230 | Wait to clear the output until new output is available to replace it.""" |
|
1245 | Wait to clear the output until new output is available to replace it.""" | |
1231 | from IPython.core.interactiveshell import InteractiveShell |
|
1246 | from IPython.core.interactiveshell import InteractiveShell | |
1232 | if InteractiveShell.initialized(): |
|
1247 | if InteractiveShell.initialized(): | |
1233 | InteractiveShell.instance().display_pub.clear_output(wait) |
|
1248 | InteractiveShell.instance().display_pub.clear_output(wait) | |
1234 | else: |
|
1249 | else: | |
1235 | print('\033[2K\r', end='') |
|
1250 | print('\033[2K\r', end='') | |
1236 | sys.stdout.flush() |
|
1251 | sys.stdout.flush() | |
1237 | print('\033[2K\r', end='') |
|
1252 | print('\033[2K\r', end='') | |
1238 | sys.stderr.flush() |
|
1253 | sys.stderr.flush() | |
1239 |
|
1254 | |||
1240 |
|
1255 | |||
1241 | @skip_doctest |
|
1256 | @skip_doctest | |
1242 | def set_matplotlib_formats(*formats, **kwargs): |
|
1257 | def set_matplotlib_formats(*formats, **kwargs): | |
1243 | """Select figure formats for the inline backend. Optionally pass quality for JPEG. |
|
1258 | """Select figure formats for the inline backend. Optionally pass quality for JPEG. | |
1244 |
|
1259 | |||
1245 | For example, this enables PNG and JPEG output with a JPEG quality of 90%:: |
|
1260 | For example, this enables PNG and JPEG output with a JPEG quality of 90%:: | |
1246 |
|
1261 | |||
1247 | In [1]: set_matplotlib_formats('png', 'jpeg', quality=90) |
|
1262 | In [1]: set_matplotlib_formats('png', 'jpeg', quality=90) | |
1248 |
|
1263 | |||
1249 | To set this in your config files use the following:: |
|
1264 | To set this in your config files use the following:: | |
1250 |
|
1265 | |||
1251 | c.InlineBackend.figure_formats = {'png', 'jpeg'} |
|
1266 | c.InlineBackend.figure_formats = {'png', 'jpeg'} | |
1252 | c.InlineBackend.print_figure_kwargs.update({'quality' : 90}) |
|
1267 | c.InlineBackend.print_figure_kwargs.update({'quality' : 90}) | |
1253 |
|
1268 | |||
1254 | Parameters |
|
1269 | Parameters | |
1255 | ---------- |
|
1270 | ---------- | |
1256 | *formats : strs |
|
1271 | *formats : strs | |
1257 | One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. |
|
1272 | One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. | |
1258 | **kwargs : |
|
1273 | **kwargs : | |
1259 | Keyword args will be relayed to ``figure.canvas.print_figure``. |
|
1274 | Keyword args will be relayed to ``figure.canvas.print_figure``. | |
1260 | """ |
|
1275 | """ | |
1261 | from IPython.core.interactiveshell import InteractiveShell |
|
1276 | from IPython.core.interactiveshell import InteractiveShell | |
1262 | from IPython.core.pylabtools import select_figure_formats |
|
1277 | from IPython.core.pylabtools import select_figure_formats | |
1263 | # build kwargs, starting with InlineBackend config |
|
1278 | # build kwargs, starting with InlineBackend config | |
1264 | kw = {} |
|
1279 | kw = {} | |
1265 | from ipykernel.pylab.config import InlineBackend |
|
1280 | from ipykernel.pylab.config import InlineBackend | |
1266 | cfg = InlineBackend.instance() |
|
1281 | cfg = InlineBackend.instance() | |
1267 | kw.update(cfg.print_figure_kwargs) |
|
1282 | kw.update(cfg.print_figure_kwargs) | |
1268 | kw.update(**kwargs) |
|
1283 | kw.update(**kwargs) | |
1269 | shell = InteractiveShell.instance() |
|
1284 | shell = InteractiveShell.instance() | |
1270 | select_figure_formats(shell, formats, **kw) |
|
1285 | select_figure_formats(shell, formats, **kw) | |
1271 |
|
1286 | |||
1272 | @skip_doctest |
|
1287 | @skip_doctest | |
1273 | def set_matplotlib_close(close=True): |
|
1288 | def set_matplotlib_close(close=True): | |
1274 | """Set whether the inline backend closes all figures automatically or not. |
|
1289 | """Set whether the inline backend closes all figures automatically or not. | |
1275 |
|
1290 | |||
1276 | By default, the inline backend used in the IPython Notebook will close all |
|
1291 | By default, the inline backend used in the IPython Notebook will close all | |
1277 | matplotlib figures automatically after each cell is run. This means that |
|
1292 | matplotlib figures automatically after each cell is run. This means that | |
1278 | plots in different cells won't interfere. Sometimes, you may want to make |
|
1293 | plots in different cells won't interfere. Sometimes, you may want to make | |
1279 | a plot in one cell and then refine it in later cells. This can be accomplished |
|
1294 | a plot in one cell and then refine it in later cells. This can be accomplished | |
1280 | by:: |
|
1295 | by:: | |
1281 |
|
1296 | |||
1282 | In [1]: set_matplotlib_close(False) |
|
1297 | In [1]: set_matplotlib_close(False) | |
1283 |
|
1298 | |||
1284 | To set this in your config files use the following:: |
|
1299 | To set this in your config files use the following:: | |
1285 |
|
1300 | |||
1286 | c.InlineBackend.close_figures = False |
|
1301 | c.InlineBackend.close_figures = False | |
1287 |
|
1302 | |||
1288 | Parameters |
|
1303 | Parameters | |
1289 | ---------- |
|
1304 | ---------- | |
1290 | close : bool |
|
1305 | close : bool | |
1291 | Should all matplotlib figures be automatically closed after each cell is |
|
1306 | Should all matplotlib figures be automatically closed after each cell is | |
1292 | run? |
|
1307 | run? | |
1293 | """ |
|
1308 | """ | |
1294 | from ipykernel.pylab.config import InlineBackend |
|
1309 | from ipykernel.pylab.config import InlineBackend | |
1295 | cfg = InlineBackend.instance() |
|
1310 | cfg = InlineBackend.instance() | |
1296 | cfg.close_figures = close |
|
1311 | cfg.close_figures = close |
@@ -1,42 +1,67 b'' | |||||
1 | .. _plotting: |
|
1 | .. _plotting: | |
2 |
|
2 | |||
|
3 | Rich Outputs | |||
|
4 | ------------ | |||
|
5 | ||||
|
6 | One of the main feature of IPython when used as a kernel is its ability to | |||
|
7 | show rich output. This means that object that can be representing as image, | |||
|
8 | sounds, animation, (etc...) can be shown this way if the frontend support it. | |||
|
9 | ||||
|
10 | In order for this to be possible, you need to use the ``display()`` function, | |||
|
11 | that should be available by default on IPython 5.4+ and 6.1+, or that you can | |||
|
12 | import with ``from IPython.display import display``. Then use ``display(<your | |||
|
13 | object>)`` instead of ``print()``, and if possible your object will be displayed | |||
|
14 | with a richer representation. In the terminal of course, there wont be much | |||
|
15 | difference as object are most of the time represented by text, but in notebook | |||
|
16 | and similar interface you will get richer outputs. | |||
|
17 | ||||
|
18 | ||||
3 | Plotting |
|
19 | Plotting | |
4 | -------- |
|
20 | -------- | |
|
21 | ||||
|
22 | .. note:: | |||
|
23 | ||||
|
24 | Starting with IPython 5.0 and matplotlib 2.0 you can avoid the use of | |||
|
25 | IPython's specific magic and use | |||
|
26 | ``matplotlib.pyplot.ion()``/``matplotlib.pyplot.ioff()`` which have the | |||
|
27 | advantages of working outside of IPython as well. | |||
|
28 | ||||
|
29 | ||||
5 | One major feature of the IPython kernel is the ability to display plots that |
|
30 | One major feature of the IPython kernel is the ability to display plots that | |
6 | are the output of running code cells. The IPython kernel is designed to work |
|
31 | are the output of running code cells. The IPython kernel is designed to work | |
7 | seamlessly with the matplotlib_ plotting library to provide this functionality. |
|
32 | seamlessly with the matplotlib_ plotting library to provide this functionality. | |
8 |
|
33 | |||
9 | To set this up, before any plotting or import of matplotlib is performed you |
|
34 | To set this up, before any plotting or import of matplotlib is performed you | |
10 | must execute the ``%matplotlib`` :ref:`magic command <magics_explained>`. This |
|
35 | must execute the ``%matplotlib`` :ref:`magic command <magics_explained>`. This | |
11 | performs the necessary behind-the-scenes setup for IPython to work correctly |
|
36 | performs the necessary behind-the-scenes setup for IPython to work correctly | |
12 | hand in hand with ``matplotlib``; it does *not*, however, actually execute any |
|
37 | hand in hand with ``matplotlib``; it does *not*, however, actually execute any | |
13 | Python ``import`` commands, that is, no names are added to the namespace. |
|
38 | Python ``import`` commands, that is, no names are added to the namespace. | |
14 |
|
39 | |||
15 | If the ``%matplotlib`` magic is called without an argument, the |
|
40 | If the ``%matplotlib`` magic is called without an argument, the | |
16 | output of a plotting command is displayed using the default ``matplotlib`` |
|
41 | output of a plotting command is displayed using the default ``matplotlib`` | |
17 | backend in a separate window. Alternatively, the backend can be explicitly |
|
42 | backend in a separate window. Alternatively, the backend can be explicitly | |
18 | requested using, for example:: |
|
43 | requested using, for example:: | |
19 |
|
44 | |||
20 | %matplotlib gtk |
|
45 | %matplotlib gtk | |
21 |
|
46 | |||
22 | A particularly interesting backend, provided by IPython, is the ``inline`` |
|
47 | A particularly interesting backend, provided by IPython, is the ``inline`` | |
23 | backend. This is available only for the Jupyter Notebook and the |
|
48 | backend. This is available only for the Jupyter Notebook and the | |
24 | Jupyter QtConsole. It can be invoked as follows:: |
|
49 | Jupyter QtConsole. It can be invoked as follows:: | |
25 |
|
50 | |||
26 | %matplotlib inline |
|
51 | %matplotlib inline | |
27 |
|
52 | |||
28 | With this backend, the output of plotting commands is displayed *inline* within |
|
53 | With this backend, the output of plotting commands is displayed *inline* within | |
29 | frontends like the Jupyter notebook, directly below the code cell that produced |
|
54 | frontends like the Jupyter notebook, directly below the code cell that produced | |
30 | it. The resulting plots will then also be stored in the notebook document. |
|
55 | it. The resulting plots will then also be stored in the notebook document. | |
31 |
|
56 | |||
32 | .. seealso:: |
|
57 | .. seealso:: | |
33 |
|
58 | |||
34 | `Plotting with Matplotlib`_ example notebook |
|
59 | `Plotting with Matplotlib`_ example notebook | |
35 |
|
60 | |||
36 |
|
61 | |||
37 | The matplotlib_ library also ships with ``%matplotlib notebook`` command that |
|
62 | The matplotlib_ library also ships with ``%matplotlib notebook`` command that | |
38 | allows interactive figures if your environment allows it. |
|
63 | allows interactive figures if your environment allows it. | |
39 |
|
64 | |||
40 | See the matplotlib_ documentation for more information. |
|
65 | See the matplotlib_ documentation for more information. | |
41 |
|
66 | |||
42 | .. include:: ../links.txt |
|
67 | .. include:: ../links.txt |
@@ -1,346 +1,359 b'' | |||||
1 | ============ |
|
1 | ============ | |
2 | 5.x Series |
|
2 | 5.x Series | |
3 | ============ |
|
3 | ============ | |
4 |
|
4 | |||
5 | .. _whatsnew540: |
|
5 | .. _whatsnew540: | |
6 |
|
6 | |||
7 | IPython 5.4 |
|
7 | IPython 5.4 | |
8 | =========== |
|
8 | =========== | |
9 |
|
9 | |||
10 | IPython 5.4-LTS is the first release of IPython after the release of the 6.x |
|
10 | IPython 5.4-LTS is the first release of IPython after the release of the 6.x | |
11 | series which is Python 3 only. It backports most of the new exposed API |
|
11 | series which is Python 3 only. It backports most of the new exposed API | |
12 | additions made in IPython 6.0 and 6.1 and avoid having to write conditional |
|
12 | additions made in IPython 6.0 and 6.1 and avoid having to write conditional | |
13 | logics depending of the version of IPython. |
|
13 | logics depending of the version of IPython. | |
14 |
|
14 | |||
15 | Please upgrade to pip 9 or greater before upgrading IPython. |
|
15 | Please upgrade to pip 9 or greater before upgrading IPython. | |
16 | Failing to do so on Python 2 may lead to a broken IPython install. |
|
16 | Failing to do so on Python 2 may lead to a broken IPython install. | |
17 |
|
17 | |||
18 | Configurable TerminalInteractiveShell |
|
18 | Configurable TerminalInteractiveShell | |
19 | ------------------------------------- |
|
19 | ------------------------------------- | |
20 |
|
20 | |||
21 | Backported from the 6.x branch as an exceptional new feature. See |
|
21 | Backported from the 6.x branch as an exceptional new feature. See | |
22 | :ghpull:`10373` and :ghissue:`10364` |
|
22 | :ghpull:`10373` and :ghissue:`10364` | |
23 |
|
23 | |||
24 | IPython gained a new ``c.TerminalIPythonApp.interactive_shell_class`` option |
|
24 | IPython gained a new ``c.TerminalIPythonApp.interactive_shell_class`` option | |
25 | that allow to customize the class used to start the terminal frontend. This |
|
25 | that allow to customize the class used to start the terminal frontend. This | |
26 | should allow user to use custom interfaces, like reviving the former readline |
|
26 | should allow user to use custom interfaces, like reviving the former readline | |
27 | interface which is now a separate package not maintained by the core team. |
|
27 | interface which is now a separate package not maintained by the core team. | |
28 |
|
28 | |||
29 |
|
29 | |||
30 | Define ``_repr_mimebundle_`` |
|
30 | Define ``_repr_mimebundle_`` | |
31 | ---------------------------- |
|
31 | ---------------------------- | |
32 |
|
32 | |||
33 | Object can now define `_repr_mimebundle_` in place of multiple `_repr_*_` |
|
33 | Object can now define `_repr_mimebundle_` in place of multiple `_repr_*_` | |
34 | methods and return a full mimebundle. This greatly simplify many implementation |
|
34 | methods and return a full mimebundle. This greatly simplify many implementation | |
35 | and allow to publish custom mimetypes (like geojson, plotly, dataframes....). |
|
35 | and allow to publish custom mimetypes (like geojson, plotly, dataframes....). | |
36 | See the ``Cutom Display Logic`` example notebook for more informations. |
|
36 | See the ``Cutom Display Logic`` example notebook for more informations. | |
37 |
|
37 | |||
38 | Execution Heuristics |
|
38 | Execution Heuristics | |
39 | -------------------- |
|
39 | -------------------- | |
40 |
|
40 | |||
41 | The heuristic for execution in the command line interface is now more biased |
|
41 | The heuristic for execution in the command line interface is now more biased | |
42 | toward executing for single statement. While in IPython 4.x and before a single |
|
42 | toward executing for single statement. While in IPython 4.x and before a single | |
43 | line would be executed when enter is pressed, IPython 5.x would insert a new |
|
43 | line would be executed when enter is pressed, IPython 5.x would insert a new | |
44 | line. For single line statement this is not true anymore and if a single line is |
|
44 | line. For single line statement this is not true anymore and if a single line is | |
45 | valid Python, IPython will execute it regardless of the cursor position. Use |
|
45 | valid Python, IPython will execute it regardless of the cursor position. Use | |
46 | :kbd:`Ctrl-O` to insert a new line. :ghpull:`10489` |
|
46 | :kbd:`Ctrl-O` to insert a new line. :ghpull:`10489` | |
47 |
|
47 | |||
48 |
|
48 | |||
49 | Implement Display IDs |
|
49 | Implement Display IDs | |
50 | --------------------- |
|
50 | --------------------- | |
51 |
|
51 | |||
52 | Implement display id and ability to update a given display. This should greatly |
|
52 | Implement display id and ability to update a given display. This should greatly | |
53 | simplify a lot of code by removing the need for widgets and allow other frontend |
|
53 | simplify a lot of code by removing the need for widgets and allow other frontend | |
54 | to implement things like progress-bars. See :ghpull:`10048` |
|
54 | to implement things like progress-bars. See :ghpull:`10048` | |
55 |
|
55 | |||
|
56 | Display function | |||
|
57 | ---------------- | |||
|
58 | ||||
|
59 | The :func:`display() <IPython.display.display>` function is now available by | |||
|
60 | default in an IPython session, meaning users can call it on any object to see | |||
|
61 | their rich representation. This should allow for better interactivity both at | |||
|
62 | the REPL and in notebook environment. | |||
|
63 | ||||
|
64 | Scripts and library that rely on display and may be run outside of IPython still | |||
|
65 | need to import the display function using ``from IPython.display import | |||
|
66 | display``. See :ghpull:`10596` | |||
|
67 | ||||
|
68 | ||||
56 | Miscs |
|
69 | Miscs | |
57 | ----- |
|
70 | ----- | |
58 |
|
71 | |||
59 | * ``_mp_main_`` is not reloaded which fixes issues with multiprocessing. |
|
72 | * ``_mp_main_`` is not reloaded which fixes issues with multiprocessing. | |
60 | :ghpull:`10523` |
|
73 | :ghpull:`10523` | |
61 | * Use user colorscheme in Pdb as well :ghpull:`10479` |
|
74 | * Use user colorscheme in Pdb as well :ghpull:`10479` | |
62 | * Faster shutdown. :ghpull:`10408` |
|
75 | * Faster shutdown. :ghpull:`10408` | |
63 | * Fix a crash in reverse search. :ghpull:`10371` |
|
76 | * Fix a crash in reverse search. :ghpull:`10371` | |
64 | * added ``Completer.backslash_combining_completions`` boolean option to |
|
77 | * added ``Completer.backslash_combining_completions`` boolean option to | |
65 | deactivate backslash-tab completion that may conflict with windows path. |
|
78 | deactivate backslash-tab completion that may conflict with windows path. | |
66 |
|
79 | |||
67 | IPython 5.3 |
|
80 | IPython 5.3 | |
68 | =========== |
|
81 | =========== | |
69 |
|
82 | |||
70 | Released on February 24th, 2017. Remarkable changes and fixes: |
|
83 | Released on February 24th, 2017. Remarkable changes and fixes: | |
71 |
|
84 | |||
72 | * Fix a bug in ``set_next_input`` leading to a crash of terminal IPython. |
|
85 | * Fix a bug in ``set_next_input`` leading to a crash of terminal IPython. | |
73 | :ghpull:`10231`, :ghissue:`10296`, :ghissue:`10229` |
|
86 | :ghpull:`10231`, :ghissue:`10296`, :ghissue:`10229` | |
74 | * Always wait for editor inputhook for terminal IPython :ghpull:`10239`, |
|
87 | * Always wait for editor inputhook for terminal IPython :ghpull:`10239`, | |
75 | :ghpull:`10240` |
|
88 | :ghpull:`10240` | |
76 | * Disable ``_ipython_display_`` in terminal :ghpull:`10249`, :ghpull:`10274` |
|
89 | * Disable ``_ipython_display_`` in terminal :ghpull:`10249`, :ghpull:`10274` | |
77 | * Update terminal colors to be more visible by default on windows |
|
90 | * Update terminal colors to be more visible by default on windows | |
78 | :ghpull:`10260`, :ghpull:`10238`, :ghissue:`10281` |
|
91 | :ghpull:`10260`, :ghpull:`10238`, :ghissue:`10281` | |
79 | * Add Ctrl-Z shortcut (suspend) in terminal debugger :ghpull:`10254`, |
|
92 | * Add Ctrl-Z shortcut (suspend) in terminal debugger :ghpull:`10254`, | |
80 | :ghissue:`10273` |
|
93 | :ghissue:`10273` | |
81 | * Indent on new line by looking at the text before the cursor :ghpull:`10264`, |
|
94 | * Indent on new line by looking at the text before the cursor :ghpull:`10264`, | |
82 | :ghpull:`10275`, :ghissue:`9283` |
|
95 | :ghpull:`10275`, :ghissue:`9283` | |
83 | * Update QtEventloop integration to fix some matplotlib integration issues |
|
96 | * Update QtEventloop integration to fix some matplotlib integration issues | |
84 | :ghpull:`10201`, :ghpull:`10311`, :ghissue:`10201` |
|
97 | :ghpull:`10201`, :ghpull:`10311`, :ghissue:`10201` | |
85 | * Respect completions display style in terminal debugger :ghpull:`10305`, |
|
98 | * Respect completions display style in terminal debugger :ghpull:`10305`, | |
86 | :ghpull:`10313` |
|
99 | :ghpull:`10313` | |
87 | * Add a config option ``TerminalInteractiveShell.extra_open_editor_shortcuts`` |
|
100 | * Add a config option ``TerminalInteractiveShell.extra_open_editor_shortcuts`` | |
88 | to enable extra shortcuts to open the input in an editor. These are :kbd:`v` |
|
101 | to enable extra shortcuts to open the input in an editor. These are :kbd:`v` | |
89 | in vi mode, and :kbd:`C-X C-E` in emacs mode (:ghpull:`10330`). |
|
102 | in vi mode, and :kbd:`C-X C-E` in emacs mode (:ghpull:`10330`). | |
90 | The :kbd:`F2` shortcut is always enabled. |
|
103 | The :kbd:`F2` shortcut is always enabled. | |
91 |
|
104 | |||
92 | IPython 5.2.2 |
|
105 | IPython 5.2.2 | |
93 | ============= |
|
106 | ============= | |
94 |
|
107 | |||
95 | * Fix error when starting with ``IPCompleter.limit_to__all__`` configured. |
|
108 | * Fix error when starting with ``IPCompleter.limit_to__all__`` configured. | |
96 |
|
109 | |||
97 | IPython 5.2.1 |
|
110 | IPython 5.2.1 | |
98 | ============= |
|
111 | ============= | |
99 |
|
112 | |||
100 | * Fix tab completion in the debugger. :ghpull:`10223` |
|
113 | * Fix tab completion in the debugger. :ghpull:`10223` | |
101 |
|
114 | |||
102 | IPython 5.2 |
|
115 | IPython 5.2 | |
103 | =========== |
|
116 | =========== | |
104 |
|
117 | |||
105 | Released on January 29th, 2017. Remarkable changes and fixes: |
|
118 | Released on January 29th, 2017. Remarkable changes and fixes: | |
106 |
|
119 | |||
107 | * restore IPython's debugger to raise on quit. :ghpull:`10009` |
|
120 | * restore IPython's debugger to raise on quit. :ghpull:`10009` | |
108 | * The configuration value ``c.TerminalInteractiveShell.highlighting_style`` can |
|
121 | * The configuration value ``c.TerminalInteractiveShell.highlighting_style`` can | |
109 | now directly take a class argument for custom color style. :ghpull:`9848` |
|
122 | now directly take a class argument for custom color style. :ghpull:`9848` | |
110 | * Correctly handle matplotlib figures dpi :ghpull:`9868` |
|
123 | * Correctly handle matplotlib figures dpi :ghpull:`9868` | |
111 | * Deprecate ``-e`` flag for the ``%notebook`` magic that had no effects. |
|
124 | * Deprecate ``-e`` flag for the ``%notebook`` magic that had no effects. | |
112 | :ghpull:`9872` |
|
125 | :ghpull:`9872` | |
113 | * You can now press F2 while typing at a terminal prompt to edit the contents |
|
126 | * You can now press F2 while typing at a terminal prompt to edit the contents | |
114 | in your favourite terminal editor. Set the :envvar:`EDITOR` environment |
|
127 | in your favourite terminal editor. Set the :envvar:`EDITOR` environment | |
115 | variable to pick which editor is used. :ghpull:`9929` |
|
128 | variable to pick which editor is used. :ghpull:`9929` | |
116 | * sdists will now only be ``.tar.gz`` as per upstream PyPI requirements. |
|
129 | * sdists will now only be ``.tar.gz`` as per upstream PyPI requirements. | |
117 | :ghpull:`9925` |
|
130 | :ghpull:`9925` | |
118 | * :any:`IPython.core.debugger` have gained a ``set_trace()`` method for |
|
131 | * :any:`IPython.core.debugger` have gained a ``set_trace()`` method for | |
119 | convenience. :ghpull:`9947` |
|
132 | convenience. :ghpull:`9947` | |
120 | * The 'smart command mode' added to the debugger in 5.0 was removed, as more |
|
133 | * The 'smart command mode' added to the debugger in 5.0 was removed, as more | |
121 | people preferred the previous behaviour. Therefore, debugger commands such as |
|
134 | people preferred the previous behaviour. Therefore, debugger commands such as | |
122 | ``c`` will act as debugger commands even when ``c`` is defined as a variable. |
|
135 | ``c`` will act as debugger commands even when ``c`` is defined as a variable. | |
123 | :ghpull:`10050` |
|
136 | :ghpull:`10050` | |
124 | * Fixes OS X event loop issues at startup, :ghpull:`10150` |
|
137 | * Fixes OS X event loop issues at startup, :ghpull:`10150` | |
125 | * Deprecate the ``%autoindent`` magic. :ghpull:`10176` |
|
138 | * Deprecate the ``%autoindent`` magic. :ghpull:`10176` | |
126 | * Emit a :any:`DeprecationWarning` when setting the deprecated |
|
139 | * Emit a :any:`DeprecationWarning` when setting the deprecated | |
127 | ``limit_to_all`` option of the completer. :ghpull:`10198` |
|
140 | ``limit_to_all`` option of the completer. :ghpull:`10198` | |
128 | * The :cellmagic:`capture` magic can now capture the result of a cell (from an |
|
141 | * The :cellmagic:`capture` magic can now capture the result of a cell (from an | |
129 | expression on the last line), as well as printed and displayed output. |
|
142 | expression on the last line), as well as printed and displayed output. | |
130 | :ghpull:`9851`. |
|
143 | :ghpull:`9851`. | |
131 |
|
144 | |||
132 |
|
145 | |||
133 | Changes of behavior to :any:`InteractiveShellEmbed`. |
|
146 | Changes of behavior to :any:`InteractiveShellEmbed`. | |
134 |
|
147 | |||
135 | :any:`InteractiveShellEmbed` interactive behavior have changed a bit in between |
|
148 | :any:`InteractiveShellEmbed` interactive behavior have changed a bit in between | |
136 | 5.1 and 5.2. By default ``%kill_embedded`` magic will prevent further invocation |
|
149 | 5.1 and 5.2. By default ``%kill_embedded`` magic will prevent further invocation | |
137 | of the current ``call location`` instead of preventing further invocation of |
|
150 | of the current ``call location`` instead of preventing further invocation of | |
138 | the current instance creation location. For most use case this will not change |
|
151 | the current instance creation location. For most use case this will not change | |
139 | much for you, though previous behavior was confusing and less consistent with |
|
152 | much for you, though previous behavior was confusing and less consistent with | |
140 | previous IPython versions. |
|
153 | previous IPython versions. | |
141 |
|
154 | |||
142 | You can now deactivate instances by using ``%kill_embedded --instance`` flag, |
|
155 | You can now deactivate instances by using ``%kill_embedded --instance`` flag, | |
143 | (or ``-i`` in short). The ``%kill_embedded`` magic also gained a |
|
156 | (or ``-i`` in short). The ``%kill_embedded`` magic also gained a | |
144 | ``--yes``/``-y`` option which skip confirmation step, and ``-x``/``--exit`` |
|
157 | ``--yes``/``-y`` option which skip confirmation step, and ``-x``/``--exit`` | |
145 | which also exit the current embedded call without asking for confirmation. |
|
158 | which also exit the current embedded call without asking for confirmation. | |
146 |
|
159 | |||
147 | See :ghpull:`10207`. |
|
160 | See :ghpull:`10207`. | |
148 |
|
161 | |||
149 |
|
162 | |||
150 |
|
163 | |||
151 | IPython 5.1 |
|
164 | IPython 5.1 | |
152 | =========== |
|
165 | =========== | |
153 |
|
166 | |||
154 | * Broken ``%timeit`` on Python2 due to the use of ``__qualname__``. :ghpull:`9804` |
|
167 | * Broken ``%timeit`` on Python2 due to the use of ``__qualname__``. :ghpull:`9804` | |
155 | * Restore ``%gui qt`` to create and return a ``QApplication`` if necessary. :ghpull:`9789` |
|
168 | * Restore ``%gui qt`` to create and return a ``QApplication`` if necessary. :ghpull:`9789` | |
156 | * Don't set terminal title by default. :ghpull:`9801` |
|
169 | * Don't set terminal title by default. :ghpull:`9801` | |
157 | * Preserve indentation when inserting newlines with ``Ctrl-O``. :ghpull:`9770` |
|
170 | * Preserve indentation when inserting newlines with ``Ctrl-O``. :ghpull:`9770` | |
158 | * Restore completion in debugger. :ghpull:`9785` |
|
171 | * Restore completion in debugger. :ghpull:`9785` | |
159 | * Deprecate ``IPython.core.debugger.Tracer()`` in favor of simpler, newer, APIs. :ghpull:`9731` |
|
172 | * Deprecate ``IPython.core.debugger.Tracer()`` in favor of simpler, newer, APIs. :ghpull:`9731` | |
160 | * Restore ``NoOpContext`` context manager removed by mistake, and add `DeprecationWarning`. :ghpull:`9765` |
|
173 | * Restore ``NoOpContext`` context manager removed by mistake, and add `DeprecationWarning`. :ghpull:`9765` | |
161 | * Add option allowing ``Prompt_toolkit`` to use 24bits colors. :ghpull:`9736` |
|
174 | * Add option allowing ``Prompt_toolkit`` to use 24bits colors. :ghpull:`9736` | |
162 | * Fix for closing interactive matplotlib windows on OS X. :ghpull:`9854` |
|
175 | * Fix for closing interactive matplotlib windows on OS X. :ghpull:`9854` | |
163 | * An embedded interactive shell instance can be used more than once. :ghpull:`9843` |
|
176 | * An embedded interactive shell instance can be used more than once. :ghpull:`9843` | |
164 | * More robust check for whether IPython is in a terminal. :ghpull:`9833` |
|
177 | * More robust check for whether IPython is in a terminal. :ghpull:`9833` | |
165 | * Better pretty-printing of dicts on PyPy. :ghpull:`9827` |
|
178 | * Better pretty-printing of dicts on PyPy. :ghpull:`9827` | |
166 | * Some coloured output now looks better on dark background command prompts in Windows. |
|
179 | * Some coloured output now looks better on dark background command prompts in Windows. | |
167 | :ghpull:`9838` |
|
180 | :ghpull:`9838` | |
168 | * Improved tab completion of paths on Windows . :ghpull:`9826` |
|
181 | * Improved tab completion of paths on Windows . :ghpull:`9826` | |
169 | * Fix tkinter event loop integration on Python 2 with ``future`` installed. :ghpull:`9824` |
|
182 | * Fix tkinter event loop integration on Python 2 with ``future`` installed. :ghpull:`9824` | |
170 | * Restore ``Ctrl-\`` as a shortcut to quit IPython. |
|
183 | * Restore ``Ctrl-\`` as a shortcut to quit IPython. | |
171 | * Make ``get_ipython()`` accessible when modules are imported by startup files. :ghpull:`9818` |
|
184 | * Make ``get_ipython()`` accessible when modules are imported by startup files. :ghpull:`9818` | |
172 | * Add support for running directories containing a ``__main__.py`` file with the |
|
185 | * Add support for running directories containing a ``__main__.py`` file with the | |
173 | ``ipython`` command. :ghpull:`9813` |
|
186 | ``ipython`` command. :ghpull:`9813` | |
174 |
|
187 | |||
175 |
|
188 | |||
176 | True Color feature |
|
189 | True Color feature | |
177 | ------------------ |
|
190 | ------------------ | |
178 |
|
191 | |||
179 | ``prompt_toolkit`` uses pygments styles for syntax highlighting. By default, the |
|
192 | ``prompt_toolkit`` uses pygments styles for syntax highlighting. By default, the | |
180 | colors specified in the style are approximated using a standard 256-color |
|
193 | colors specified in the style are approximated using a standard 256-color | |
181 | palette. ``prompt_toolkit`` also supports 24bit, a.k.a. "true", a.k.a. 16-million |
|
194 | palette. ``prompt_toolkit`` also supports 24bit, a.k.a. "true", a.k.a. 16-million | |
182 | color escape sequences which enable compatible terminals to display the exact |
|
195 | color escape sequences which enable compatible terminals to display the exact | |
183 | colors specified instead of an approximation. This true_color option exposes |
|
196 | colors specified instead of an approximation. This true_color option exposes | |
184 | that capability in prompt_toolkit to the IPython shell. |
|
197 | that capability in prompt_toolkit to the IPython shell. | |
185 |
|
198 | |||
186 | Here is a good source for the current state of true color support in various |
|
199 | Here is a good source for the current state of true color support in various | |
187 | terminal emulators and software projects: https://gist.github.com/XVilka/8346728 |
|
200 | terminal emulators and software projects: https://gist.github.com/XVilka/8346728 | |
188 |
|
201 | |||
189 |
|
202 | |||
190 |
|
203 | |||
191 | IPython 5.0 |
|
204 | IPython 5.0 | |
192 | =========== |
|
205 | =========== | |
193 |
|
206 | |||
194 | Released July 7, 2016 |
|
207 | Released July 7, 2016 | |
195 |
|
208 | |||
196 | New terminal interface |
|
209 | New terminal interface | |
197 | ---------------------- |
|
210 | ---------------------- | |
198 |
|
211 | |||
199 | IPython 5 features a major upgrade to the terminal interface, bringing live |
|
212 | IPython 5 features a major upgrade to the terminal interface, bringing live | |
200 | syntax highlighting as you type, proper multiline editing and multiline paste, |
|
213 | syntax highlighting as you type, proper multiline editing and multiline paste, | |
201 | and tab completions that don't clutter up your history. |
|
214 | and tab completions that don't clutter up your history. | |
202 |
|
215 | |||
203 | .. image:: ../_images/ptshell_features.png |
|
216 | .. image:: ../_images/ptshell_features.png | |
204 | :alt: New terminal interface features |
|
217 | :alt: New terminal interface features | |
205 | :align: center |
|
218 | :align: center | |
206 | :target: ../_images/ptshell_features.png |
|
219 | :target: ../_images/ptshell_features.png | |
207 |
|
220 | |||
208 | These features are provided by the Python library `prompt_toolkit |
|
221 | These features are provided by the Python library `prompt_toolkit | |
209 | <http://python-prompt-toolkit.readthedocs.io/en/stable/>`__, which replaces |
|
222 | <http://python-prompt-toolkit.readthedocs.io/en/stable/>`__, which replaces | |
210 | ``readline`` throughout our terminal interface. |
|
223 | ``readline`` throughout our terminal interface. | |
211 |
|
224 | |||
212 | Relying on this pure-Python, cross platform module also makes it simpler to |
|
225 | Relying on this pure-Python, cross platform module also makes it simpler to | |
213 | install IPython. We have removed dependencies on ``pyreadline`` for Windows and |
|
226 | install IPython. We have removed dependencies on ``pyreadline`` for Windows and | |
214 | ``gnureadline`` for Mac. |
|
227 | ``gnureadline`` for Mac. | |
215 |
|
228 | |||
216 | Backwards incompatible changes |
|
229 | Backwards incompatible changes | |
217 | ------------------------------ |
|
230 | ------------------------------ | |
218 |
|
231 | |||
219 | - The ``%install_ext`` magic function, deprecated since 4.0, has now been deleted. |
|
232 | - The ``%install_ext`` magic function, deprecated since 4.0, has now been deleted. | |
220 | You can distribute and install extensions as packages on PyPI. |
|
233 | You can distribute and install extensions as packages on PyPI. | |
221 | - Callbacks registered while an event is being handled will now only be called |
|
234 | - Callbacks registered while an event is being handled will now only be called | |
222 | for subsequent events; previously they could be called for the current event. |
|
235 | for subsequent events; previously they could be called for the current event. | |
223 | Similarly, callbacks removed while handling an event *will* always get that |
|
236 | Similarly, callbacks removed while handling an event *will* always get that | |
224 | event. See :ghissue:`9447` and :ghpull:`9453`. |
|
237 | event. See :ghissue:`9447` and :ghpull:`9453`. | |
225 | - Integration with pydb has been removed since pydb development has been stopped |
|
238 | - Integration with pydb has been removed since pydb development has been stopped | |
226 | since 2012, and pydb is not installable from PyPI. |
|
239 | since 2012, and pydb is not installable from PyPI. | |
227 | - The ``autoedit_syntax`` option has apparently been broken for many years. |
|
240 | - The ``autoedit_syntax`` option has apparently been broken for many years. | |
228 | It has been removed. |
|
241 | It has been removed. | |
229 |
|
242 | |||
230 | New terminal interface |
|
243 | New terminal interface | |
231 | ~~~~~~~~~~~~~~~~~~~~~~ |
|
244 | ~~~~~~~~~~~~~~~~~~~~~~ | |
232 |
|
245 | |||
233 | The overhaul of the terminal interface will probably cause a range of minor |
|
246 | The overhaul of the terminal interface will probably cause a range of minor | |
234 | issues for existing users. |
|
247 | issues for existing users. | |
235 | This is inevitable for such a significant change, and we've done our best to |
|
248 | This is inevitable for such a significant change, and we've done our best to | |
236 | minimise these issues. |
|
249 | minimise these issues. | |
237 | Some changes that we're aware of, with suggestions on how to handle them: |
|
250 | Some changes that we're aware of, with suggestions on how to handle them: | |
238 |
|
251 | |||
239 | IPython no longer uses readline configuration (``~/.inputrc``). We hope that |
|
252 | IPython no longer uses readline configuration (``~/.inputrc``). We hope that | |
240 | the functionality you want (e.g. vi input mode) will be available by configuring |
|
253 | the functionality you want (e.g. vi input mode) will be available by configuring | |
241 | IPython directly (see :doc:`/config/options/terminal`). |
|
254 | IPython directly (see :doc:`/config/options/terminal`). | |
242 | If something's missing, please file an issue. |
|
255 | If something's missing, please file an issue. | |
243 |
|
256 | |||
244 | The ``PromptManager`` class has been removed, and the prompt machinery simplified. |
|
257 | The ``PromptManager`` class has been removed, and the prompt machinery simplified. | |
245 | See :ref:`custom_prompts` to customise prompts with the new machinery. |
|
258 | See :ref:`custom_prompts` to customise prompts with the new machinery. | |
246 |
|
259 | |||
247 | :mod:`IPython.core.debugger` now provides a plainer interface. |
|
260 | :mod:`IPython.core.debugger` now provides a plainer interface. | |
248 | :mod:`IPython.terminal.debugger` contains the terminal debugger using |
|
261 | :mod:`IPython.terminal.debugger` contains the terminal debugger using | |
249 | prompt_toolkit. |
|
262 | prompt_toolkit. | |
250 |
|
263 | |||
251 | There are new options to configure the colours used in syntax highlighting. |
|
264 | There are new options to configure the colours used in syntax highlighting. | |
252 | We have tried to integrate them with our classic ``--colors`` option and |
|
265 | We have tried to integrate them with our classic ``--colors`` option and | |
253 | ``%colors`` magic, but there's a mismatch in possibilities, so some configurations |
|
266 | ``%colors`` magic, but there's a mismatch in possibilities, so some configurations | |
254 | may produce unexpected results. See :ref:`termcolour` for more information. |
|
267 | may produce unexpected results. See :ref:`termcolour` for more information. | |
255 |
|
268 | |||
256 | The new interface is not compatible with Emacs 'inferior-shell' feature. To |
|
269 | The new interface is not compatible with Emacs 'inferior-shell' feature. To | |
257 | continue using this, add the ``--simple-prompt`` flag to the command Emacs |
|
270 | continue using this, add the ``--simple-prompt`` flag to the command Emacs | |
258 | runs. This flag disables most IPython features, relying on Emacs to provide |
|
271 | runs. This flag disables most IPython features, relying on Emacs to provide | |
259 | things like tab completion. |
|
272 | things like tab completion. | |
260 |
|
273 | |||
261 | Provisional Changes |
|
274 | Provisional Changes | |
262 | ------------------- |
|
275 | ------------------- | |
263 |
|
276 | |||
264 | Provisional changes are experimental functionality that may, or may not, make |
|
277 | Provisional changes are experimental functionality that may, or may not, make | |
265 | it into a future version of IPython, and which API may change without warnings. |
|
278 | it into a future version of IPython, and which API may change without warnings. | |
266 | Activating these features and using these API are at your own risk, and may have |
|
279 | Activating these features and using these API are at your own risk, and may have | |
267 | security implication for your system, especially if used with the Jupyter notebook, |
|
280 | security implication for your system, especially if used with the Jupyter notebook, | |
268 |
|
281 | |||
269 | When running via the Jupyter notebook interfaces, or other compatible client, |
|
282 | When running via the Jupyter notebook interfaces, or other compatible client, | |
270 | you can enable rich documentation experimental functionality: |
|
283 | you can enable rich documentation experimental functionality: | |
271 |
|
284 | |||
272 | When the ``docrepr`` package is installed setting the boolean flag |
|
285 | When the ``docrepr`` package is installed setting the boolean flag | |
273 | ``InteractiveShell.sphinxify_docstring`` to ``True``, will process the various |
|
286 | ``InteractiveShell.sphinxify_docstring`` to ``True``, will process the various | |
274 | object through sphinx before displaying them (see the ``docrepr`` package |
|
287 | object through sphinx before displaying them (see the ``docrepr`` package | |
275 | documentation for more information. |
|
288 | documentation for more information. | |
276 |
|
289 | |||
277 | You need to also enable the IPython pager display rich HTML representation |
|
290 | You need to also enable the IPython pager display rich HTML representation | |
278 | using the ``InteractiveShell.enable_html_pager`` boolean configuration option. |
|
291 | using the ``InteractiveShell.enable_html_pager`` boolean configuration option. | |
279 | As usual you can set these configuration options globally in your configuration |
|
292 | As usual you can set these configuration options globally in your configuration | |
280 | files, alternatively you can turn them on dynamically using the following |
|
293 | files, alternatively you can turn them on dynamically using the following | |
281 | snippet: |
|
294 | snippet: | |
282 |
|
295 | |||
283 | .. code-block:: python |
|
296 | .. code-block:: python | |
284 |
|
297 | |||
285 | ip = get_ipython() |
|
298 | ip = get_ipython() | |
286 | ip.sphinxify_docstring = True |
|
299 | ip.sphinxify_docstring = True | |
287 | ip.enable_html_pager = True |
|
300 | ip.enable_html_pager = True | |
288 |
|
301 | |||
289 |
|
302 | |||
290 | You can test the effect of various combinations of the above configuration in |
|
303 | You can test the effect of various combinations of the above configuration in | |
291 | the Jupyter notebook, with things example like : |
|
304 | the Jupyter notebook, with things example like : | |
292 |
|
305 | |||
293 | .. code-block:: ipython |
|
306 | .. code-block:: ipython | |
294 |
|
307 | |||
295 | import numpy as np |
|
308 | import numpy as np | |
296 | np.histogram? |
|
309 | np.histogram? | |
297 |
|
310 | |||
298 |
|
311 | |||
299 | This is part of an effort to make Documentation in Python richer and provide in |
|
312 | This is part of an effort to make Documentation in Python richer and provide in | |
300 | the long term if possible dynamic examples that can contain math, images, |
|
313 | the long term if possible dynamic examples that can contain math, images, | |
301 | widgets... As stated above this is nightly experimental feature with a lot of |
|
314 | widgets... As stated above this is nightly experimental feature with a lot of | |
302 | (fun) problem to solve. We would be happy to get your feedback and expertise on |
|
315 | (fun) problem to solve. We would be happy to get your feedback and expertise on | |
303 | it. |
|
316 | it. | |
304 |
|
317 | |||
305 |
|
318 | |||
306 |
|
319 | |||
307 | Deprecated Features |
|
320 | Deprecated Features | |
308 | ------------------- |
|
321 | ------------------- | |
309 |
|
322 | |||
310 | Some deprecated features are listed in this section. Don't forget to enable |
|
323 | Some deprecated features are listed in this section. Don't forget to enable | |
311 | ``DeprecationWarning`` as an error if you are using IPython in a Continuous |
|
324 | ``DeprecationWarning`` as an error if you are using IPython in a Continuous | |
312 | Integration setup or in your testing in general: |
|
325 | Integration setup or in your testing in general: | |
313 |
|
326 | |||
314 | .. code-block:: python |
|
327 | .. code-block:: python | |
315 |
|
328 | |||
316 | import warnings |
|
329 | import warnings | |
317 | warnings.filterwarnings('error', '.*', DeprecationWarning, module='yourmodule.*') |
|
330 | warnings.filterwarnings('error', '.*', DeprecationWarning, module='yourmodule.*') | |
318 |
|
331 | |||
319 |
|
332 | |||
320 | - ``hooks.fix_error_editor`` seems unused and is pending deprecation. |
|
333 | - ``hooks.fix_error_editor`` seems unused and is pending deprecation. | |
321 | - `IPython/core/excolors.py:ExceptionColors` is deprecated. |
|
334 | - `IPython/core/excolors.py:ExceptionColors` is deprecated. | |
322 | - `IPython.core.InteractiveShell:write()` is deprecated; use `sys.stdout` instead. |
|
335 | - `IPython.core.InteractiveShell:write()` is deprecated; use `sys.stdout` instead. | |
323 | - `IPython.core.InteractiveShell:write_err()` is deprecated; use `sys.stderr` instead. |
|
336 | - `IPython.core.InteractiveShell:write_err()` is deprecated; use `sys.stderr` instead. | |
324 | - The `formatter` keyword argument to `Inspector.info` in `IPython.core.oinspec` has no effect. |
|
337 | - The `formatter` keyword argument to `Inspector.info` in `IPython.core.oinspec` has no effect. | |
325 | - The `global_ns` keyword argument of IPython Embed was deprecated, and has no effect. Use `module` keyword argument instead. |
|
338 | - The `global_ns` keyword argument of IPython Embed was deprecated, and has no effect. Use `module` keyword argument instead. | |
326 |
|
339 | |||
327 |
|
340 | |||
328 | Known Issues: |
|
341 | Known Issues: | |
329 | ------------- |
|
342 | ------------- | |
330 |
|
343 | |||
331 | - ``<Esc>`` Key does not dismiss the completer and does not clear the current |
|
344 | - ``<Esc>`` Key does not dismiss the completer and does not clear the current | |
332 | buffer. This is an on purpose modification due to current technical |
|
345 | buffer. This is an on purpose modification due to current technical | |
333 | limitation. Cf :ghpull:`9572`. Escape the control character which is used |
|
346 | limitation. Cf :ghpull:`9572`. Escape the control character which is used | |
334 | for other shortcut, and there is no practical way to distinguish. Use Ctr-G |
|
347 | for other shortcut, and there is no practical way to distinguish. Use Ctr-G | |
335 | or Ctrl-C as an alternative. |
|
348 | or Ctrl-C as an alternative. | |
336 |
|
349 | |||
337 | - Cannot use ``Shift-Enter`` and ``Ctrl-Enter`` to submit code in terminal. cf |
|
350 | - Cannot use ``Shift-Enter`` and ``Ctrl-Enter`` to submit code in terminal. cf | |
338 | :ghissue:`9587` and :ghissue:`9401`. In terminal there is no practical way to |
|
351 | :ghissue:`9587` and :ghissue:`9401`. In terminal there is no practical way to | |
339 | distinguish these key sequences from a normal new line return. |
|
352 | distinguish these key sequences from a normal new line return. | |
340 |
|
353 | |||
341 | - ``PageUp`` and ``pageDown`` do not move through completion menu. |
|
354 | - ``PageUp`` and ``pageDown`` do not move through completion menu. | |
342 |
|
355 | |||
343 | - Color styles might not adapt to terminal emulator themes. This will need new |
|
356 | - Color styles might not adapt to terminal emulator themes. This will need new | |
344 | version of Pygments to be released, and can be mitigated with custom themes. |
|
357 | version of Pygments to be released, and can be mitigated with custom themes. | |
345 |
|
358 | |||
346 |
|
359 |
General Comments 0
You need to be logged in to leave comments.
Login now