Show More
@@ -0,0 +1,367 b'' | |||||
|
1 | # -*- coding: utf-8 -*- | |||
|
2 | """Top-level display functions for displaying object in different formats.""" | |||
|
3 | ||||
|
4 | # Copyright (c) IPython Development Team. | |||
|
5 | # Distributed under the terms of the Modified BSD License. | |||
|
6 | ||||
|
7 | ||||
|
8 | from binascii import b2a_hex | |||
|
9 | import os | |||
|
10 | import sys | |||
|
11 | ||||
|
12 | __all__ = ['display', 'clear_output', 'publish_display_data', 'update_display', 'DisplayHandle'] | |||
|
13 | ||||
|
14 | #----------------------------------------------------------------------------- | |||
|
15 | # utility functions | |||
|
16 | #----------------------------------------------------------------------------- | |||
|
17 | ||||
|
18 | ||||
|
19 | def _merge(d1, d2): | |||
|
20 | """Like update, but merges sub-dicts instead of clobbering at the top level. | |||
|
21 | ||||
|
22 | Updates d1 in-place | |||
|
23 | """ | |||
|
24 | ||||
|
25 | if not isinstance(d2, dict) or not isinstance(d1, dict): | |||
|
26 | return d2 | |||
|
27 | for key, value in d2.items(): | |||
|
28 | d1[key] = _merge(d1.get(key), value) | |||
|
29 | return d1 | |||
|
30 | ||||
|
31 | ||||
|
32 | #----------------------------------------------------------------------------- | |||
|
33 | # Main functions | |||
|
34 | #----------------------------------------------------------------------------- | |||
|
35 | ||||
|
36 | ||||
|
37 | # use * to indicate transient is keyword-only | |||
|
38 | def publish_display_data(data, metadata=None, source=None, *, transient=None, **kwargs): | |||
|
39 | """Publish data and metadata to all frontends. | |||
|
40 | ||||
|
41 | See the ``display_data`` message in the messaging documentation for | |||
|
42 | more details about this message type. | |||
|
43 | ||||
|
44 | Keys of data and metadata can be any mime-type. | |||
|
45 | ||||
|
46 | Parameters | |||
|
47 | ---------- | |||
|
48 | data : dict | |||
|
49 | A dictionary having keys that are valid MIME types (like | |||
|
50 | 'text/plain' or 'image/svg+xml') and values that are the data for | |||
|
51 | that MIME type. The data itself must be a JSON'able data | |||
|
52 | structure. Minimally all data should have the 'text/plain' data, | |||
|
53 | which can be displayed by all frontends. If more than the plain | |||
|
54 | text is given, it is up to the frontend to decide which | |||
|
55 | representation to use. | |||
|
56 | metadata : dict | |||
|
57 | A dictionary for metadata related to the data. This can contain | |||
|
58 | arbitrary key, value pairs that frontends can use to interpret | |||
|
59 | the data. mime-type keys matching those in data can be used | |||
|
60 | to specify metadata about particular representations. | |||
|
61 | source : str, deprecated | |||
|
62 | Unused. | |||
|
63 | transient : dict, keyword-only | |||
|
64 | A dictionary of transient data, such as display_id. | |||
|
65 | """ | |||
|
66 | from IPython.core.interactiveshell import InteractiveShell | |||
|
67 | ||||
|
68 | display_pub = InteractiveShell.instance().display_pub | |||
|
69 | ||||
|
70 | # only pass transient if supplied, | |||
|
71 | # to avoid errors with older ipykernel. | |||
|
72 | # TODO: We could check for ipykernel version and provide a detailed upgrade message. | |||
|
73 | if transient: | |||
|
74 | kwargs['transient'] = transient | |||
|
75 | ||||
|
76 | display_pub.publish( | |||
|
77 | data=data, | |||
|
78 | metadata=metadata, | |||
|
79 | **kwargs | |||
|
80 | ) | |||
|
81 | ||||
|
82 | ||||
|
83 | def _new_id(): | |||
|
84 | """Generate a new random text id with urandom""" | |||
|
85 | return b2a_hex(os.urandom(16)).decode('ascii') | |||
|
86 | ||||
|
87 | ||||
|
88 | def display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs): | |||
|
89 | """Display a Python object in all frontends. | |||
|
90 | ||||
|
91 | By default all representations will be computed and sent to the frontends. | |||
|
92 | Frontends can decide which representation is used and how. | |||
|
93 | ||||
|
94 | In terminal IPython this will be similar to using :func:`print`, for use in richer | |||
|
95 | frontends see Jupyter notebook examples with rich display logic. | |||
|
96 | ||||
|
97 | Parameters | |||
|
98 | ---------- | |||
|
99 | *objs : object | |||
|
100 | The Python objects to display. | |||
|
101 | raw : bool, optional | |||
|
102 | Are the objects to be displayed already mimetype-keyed dicts of raw display data, | |||
|
103 | or Python objects that need to be formatted before display? [default: False] | |||
|
104 | include : list, tuple or set, optional | |||
|
105 | A list of format type strings (MIME types) to include in the | |||
|
106 | format data dict. If this is set *only* the format types included | |||
|
107 | in this list will be computed. | |||
|
108 | exclude : list, tuple or set, optional | |||
|
109 | A list of format type strings (MIME types) to exclude in the format | |||
|
110 | data dict. If this is set all format types will be computed, | |||
|
111 | except for those included in this argument. | |||
|
112 | metadata : dict, optional | |||
|
113 | A dictionary of metadata to associate with the output. | |||
|
114 | mime-type keys in this dictionary will be associated with the individual | |||
|
115 | representation formats, if they exist. | |||
|
116 | transient : dict, optional | |||
|
117 | A dictionary of transient data to associate with the output. | |||
|
118 | Data in this dict should not be persisted to files (e.g. notebooks). | |||
|
119 | display_id : str, bool optional | |||
|
120 | Set an id for the display. | |||
|
121 | This id can be used for updating this display area later via update_display. | |||
|
122 | If given as `True`, generate a new `display_id` | |||
|
123 | kwargs: additional keyword-args, optional | |||
|
124 | Additional keyword-arguments are passed through to the display publisher. | |||
|
125 | ||||
|
126 | Returns | |||
|
127 | ------- | |||
|
128 | ||||
|
129 | handle: DisplayHandle | |||
|
130 | Returns a handle on updatable displays for use with :func:`update_display`, | |||
|
131 | if `display_id` is given. Returns :any:`None` if no `display_id` is given | |||
|
132 | (default). | |||
|
133 | ||||
|
134 | Examples | |||
|
135 | -------- | |||
|
136 | ||||
|
137 | >>> class Json(object): | |||
|
138 | ... def __init__(self, json): | |||
|
139 | ... self.json = json | |||
|
140 | ... def _repr_pretty_(self, pp, cycle): | |||
|
141 | ... import json | |||
|
142 | ... pp.text(json.dumps(self.json, indent=2)) | |||
|
143 | ... def __repr__(self): | |||
|
144 | ... return str(self.json) | |||
|
145 | ... | |||
|
146 | ||||
|
147 | >>> d = Json({1:2, 3: {4:5}}) | |||
|
148 | ||||
|
149 | >>> print(d) | |||
|
150 | {1: 2, 3: {4: 5}} | |||
|
151 | ||||
|
152 | >>> display(d) | |||
|
153 | { | |||
|
154 | "1": 2, | |||
|
155 | "3": { | |||
|
156 | "4": 5 | |||
|
157 | } | |||
|
158 | } | |||
|
159 | ||||
|
160 | >>> def int_formatter(integer, pp, cycle): | |||
|
161 | ... pp.text('I'*integer) | |||
|
162 | ||||
|
163 | >>> plain = get_ipython().display_formatter.formatters['text/plain'] | |||
|
164 | >>> plain.for_type(int, int_formatter) | |||
|
165 | <function _repr_pprint at 0x...> | |||
|
166 | >>> display(7-5) | |||
|
167 | II | |||
|
168 | ||||
|
169 | >>> del plain.type_printers[int] | |||
|
170 | >>> display(7-5) | |||
|
171 | 2 | |||
|
172 | ||||
|
173 | See Also | |||
|
174 | -------- | |||
|
175 | ||||
|
176 | :func:`update_display` | |||
|
177 | ||||
|
178 | Notes | |||
|
179 | ----- | |||
|
180 | ||||
|
181 | In Python, objects can declare their textual representation using the | |||
|
182 | `__repr__` method. IPython expands on this idea and allows objects to declare | |||
|
183 | other, rich representations including: | |||
|
184 | ||||
|
185 | - HTML | |||
|
186 | - JSON | |||
|
187 | - PNG | |||
|
188 | - JPEG | |||
|
189 | - SVG | |||
|
190 | - LaTeX | |||
|
191 | ||||
|
192 | A single object can declare some or all of these representations; all are | |||
|
193 | handled by IPython's display system. | |||
|
194 | ||||
|
195 | The main idea of the first approach is that you have to implement special | |||
|
196 | display methods when you define your class, one for each representation you | |||
|
197 | want to use. Here is a list of the names of the special methods and the | |||
|
198 | values they must return: | |||
|
199 | ||||
|
200 | - `_repr_html_`: return raw HTML as a string, or a tuple (see below). | |||
|
201 | - `_repr_json_`: return a JSONable dict, or a tuple (see below). | |||
|
202 | - `_repr_jpeg_`: return raw JPEG data, or a tuple (see below). | |||
|
203 | - `_repr_png_`: return raw PNG data, or a tuple (see below). | |||
|
204 | - `_repr_svg_`: return raw SVG data as a string, or a tuple (see below). | |||
|
205 | - `_repr_latex_`: return LaTeX commands in a string surrounded by "$", | |||
|
206 | or a tuple (see below). | |||
|
207 | - `_repr_mimebundle_`: return a full mimebundle containing the mapping | |||
|
208 | from all mimetypes to data. | |||
|
209 | Use this for any mime-type not listed above. | |||
|
210 | ||||
|
211 | The above functions may also return the object's metadata alonside the | |||
|
212 | data. If the metadata is available, the functions will return a tuple | |||
|
213 | containing the data and metadata, in that order. If there is no metadata | |||
|
214 | available, then the functions will return the data only. | |||
|
215 | ||||
|
216 | When you are directly writing your own classes, you can adapt them for | |||
|
217 | display in IPython by following the above approach. But in practice, you | |||
|
218 | often need to work with existing classes that you can't easily modify. | |||
|
219 | ||||
|
220 | You can refer to the documentation on integrating with the display system in | |||
|
221 | order to register custom formatters for already existing types | |||
|
222 | (:ref:`integrating_rich_display`). | |||
|
223 | ||||
|
224 | .. versionadded:: 5.4 display available without import | |||
|
225 | .. versionadded:: 6.1 display available without import | |||
|
226 | ||||
|
227 | Since IPython 5.4 and 6.1 :func:`display` is automatically made available to | |||
|
228 | the user without import. If you are using display in a document that might | |||
|
229 | be used in a pure python context or with older version of IPython, use the | |||
|
230 | following import at the top of your file:: | |||
|
231 | ||||
|
232 | from IPython.display import display | |||
|
233 | ||||
|
234 | """ | |||
|
235 | from IPython.core.interactiveshell import InteractiveShell | |||
|
236 | ||||
|
237 | if not InteractiveShell.initialized(): | |||
|
238 | # Directly print objects. | |||
|
239 | print(*objs) | |||
|
240 | return | |||
|
241 | ||||
|
242 | raw = kwargs.pop('raw', False) | |||
|
243 | if transient is None: | |||
|
244 | transient = {} | |||
|
245 | if metadata is None: | |||
|
246 | metadata={} | |||
|
247 | if display_id: | |||
|
248 | if display_id is True: | |||
|
249 | display_id = _new_id() | |||
|
250 | transient['display_id'] = display_id | |||
|
251 | if kwargs.get('update') and 'display_id' not in transient: | |||
|
252 | raise TypeError('display_id required for update_display') | |||
|
253 | if transient: | |||
|
254 | kwargs['transient'] = transient | |||
|
255 | ||||
|
256 | if not objs and display_id: | |||
|
257 | # if given no objects, but still a request for a display_id, | |||
|
258 | # we assume the user wants to insert an empty output that | |||
|
259 | # can be updated later | |||
|
260 | objs = [{}] | |||
|
261 | raw = True | |||
|
262 | ||||
|
263 | if not raw: | |||
|
264 | format = InteractiveShell.instance().display_formatter.format | |||
|
265 | ||||
|
266 | for obj in objs: | |||
|
267 | if raw: | |||
|
268 | publish_display_data(data=obj, metadata=metadata, **kwargs) | |||
|
269 | else: | |||
|
270 | format_dict, md_dict = format(obj, include=include, exclude=exclude) | |||
|
271 | if not format_dict: | |||
|
272 | # nothing to display (e.g. _ipython_display_ took over) | |||
|
273 | continue | |||
|
274 | if metadata: | |||
|
275 | # kwarg-specified metadata gets precedence | |||
|
276 | _merge(md_dict, metadata) | |||
|
277 | publish_display_data(data=format_dict, metadata=md_dict, **kwargs) | |||
|
278 | if display_id: | |||
|
279 | return DisplayHandle(display_id) | |||
|
280 | ||||
|
281 | ||||
|
282 | # use * for keyword-only display_id arg | |||
|
283 | def update_display(obj, *, display_id, **kwargs): | |||
|
284 | """Update an existing display by id | |||
|
285 | ||||
|
286 | Parameters | |||
|
287 | ---------- | |||
|
288 | ||||
|
289 | obj: | |||
|
290 | The object with which to update the display | |||
|
291 | display_id: keyword-only | |||
|
292 | The id of the display to update | |||
|
293 | ||||
|
294 | See Also | |||
|
295 | -------- | |||
|
296 | ||||
|
297 | :func:`display` | |||
|
298 | """ | |||
|
299 | kwargs['update'] = True | |||
|
300 | display(obj, display_id=display_id, **kwargs) | |||
|
301 | ||||
|
302 | ||||
|
303 | class DisplayHandle(object): | |||
|
304 | """A handle on an updatable display | |||
|
305 | ||||
|
306 | Call `.update(obj)` to display a new object. | |||
|
307 | ||||
|
308 | Call `.display(obj`) to add a new instance of this display, | |||
|
309 | and update existing instances. | |||
|
310 | ||||
|
311 | See Also | |||
|
312 | -------- | |||
|
313 | ||||
|
314 | :func:`display`, :func:`update_display` | |||
|
315 | ||||
|
316 | """ | |||
|
317 | ||||
|
318 | def __init__(self, display_id=None): | |||
|
319 | if display_id is None: | |||
|
320 | display_id = _new_id() | |||
|
321 | self.display_id = display_id | |||
|
322 | ||||
|
323 | def __repr__(self): | |||
|
324 | return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id) | |||
|
325 | ||||
|
326 | def display(self, obj, **kwargs): | |||
|
327 | """Make a new display with my id, updating existing instances. | |||
|
328 | ||||
|
329 | Parameters | |||
|
330 | ---------- | |||
|
331 | ||||
|
332 | obj: | |||
|
333 | object to display | |||
|
334 | **kwargs: | |||
|
335 | additional keyword arguments passed to display | |||
|
336 | """ | |||
|
337 | display(obj, display_id=self.display_id, **kwargs) | |||
|
338 | ||||
|
339 | def update(self, obj, **kwargs): | |||
|
340 | """Update existing displays with my id | |||
|
341 | ||||
|
342 | Parameters | |||
|
343 | ---------- | |||
|
344 | ||||
|
345 | obj: | |||
|
346 | object to display | |||
|
347 | **kwargs: | |||
|
348 | additional keyword arguments passed to update_display | |||
|
349 | """ | |||
|
350 | update_display(obj, display_id=self.display_id, **kwargs) | |||
|
351 | ||||
|
352 | ||||
|
353 | def clear_output(wait=False): | |||
|
354 | """Clear the output of the current cell receiving output. | |||
|
355 | ||||
|
356 | Parameters | |||
|
357 | ---------- | |||
|
358 | wait : bool [default: false] | |||
|
359 | Wait to clear the output until new output is available to replace it.""" | |||
|
360 | from IPython.core.interactiveshell import InteractiveShell | |||
|
361 | if InteractiveShell.initialized(): | |||
|
362 | InteractiveShell.instance().display_pub.clear_output(wait) | |||
|
363 | else: | |||
|
364 | print('\033[2K\r', end='') | |||
|
365 | sys.stdout.flush() | |||
|
366 | print('\033[2K\r', end='') | |||
|
367 | sys.stderr.flush() |
@@ -5,12 +5,11 b'' | |||||
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 |
from binascii import |
|
8 | from binascii import b2a_base64, hexlify | |
9 | import json |
|
9 | import json | |
10 | import mimetypes |
|
10 | import mimetypes | |
11 | import os |
|
11 | import os | |
12 | import struct |
|
12 | import struct | |
13 | import sys |
|
|||
14 | import warnings |
|
13 | import warnings | |
15 | from copy import deepcopy |
|
14 | from copy import deepcopy | |
16 | from os.path import splitext |
|
15 | from os.path import splitext | |
@@ -18,14 +17,37 b' from pathlib import Path, PurePath' | |||||
18 |
|
17 | |||
19 | from IPython.utils.py3compat import cast_unicode |
|
18 | from IPython.utils.py3compat import cast_unicode | |
20 | from IPython.testing.skipdoctest import skip_doctest |
|
19 | from IPython.testing.skipdoctest import skip_doctest | |
|
20 | from . import display_functions | |||
|
21 | ||||
|
22 | ||||
|
23 | __all__ = ['display_pretty', 'display_html', 'display_markdown', | |||
|
24 | 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json', | |||
|
25 | 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject', | |||
|
26 | 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'ProgressBar', 'JSON', | |||
|
27 | 'GeoJSON', 'Javascript', 'Image', 'set_matplotlib_formats', | |||
|
28 | 'set_matplotlib_close', | |||
|
29 | 'Video'] | |||
|
30 | ||||
|
31 | _deprecated_names = ["display", "clear_output", "publish_display_data", "update_display", "DisplayHandle"] | |||
|
32 | ||||
|
33 | __all__ = __all__ + _deprecated_names | |||
|
34 | ||||
|
35 | ||||
|
36 | # ----- warn to import from IPython.display ----- | |||
|
37 | ||||
|
38 | from warnings import warn | |||
|
39 | ||||
|
40 | ||||
|
41 | def __getattr__(name): | |||
|
42 | if name in _deprecated_names: | |||
|
43 | warn(f"Importing {name} from IPython.core.display is deprecated since IPython 7.14, please import from IPython display", DeprecationWarning, stacklevel=2) | |||
|
44 | return getattr(display_functions, name) | |||
|
45 | ||||
|
46 | if name in globals().keys(): | |||
|
47 | return globals()[name] | |||
|
48 | else: | |||
|
49 | raise AttributeError(f"module {__name__} has no attribute {name}") | |||
21 |
|
50 | |||
22 | __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown', |
|
|||
23 | 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json', |
|
|||
24 | 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject', |
|
|||
25 | 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'ProgressBar', 'JSON', |
|
|||
26 | 'GeoJSON', 'Javascript', 'Image', 'clear_output', 'set_matplotlib_formats', |
|
|||
27 | 'set_matplotlib_close', 'publish_display_data', 'update_display', 'DisplayHandle', |
|
|||
28 | 'Video'] |
|
|||
29 |
|
51 | |||
30 | #----------------------------------------------------------------------------- |
|
52 | #----------------------------------------------------------------------------- | |
31 | # utility functions |
|
53 | # utility functions | |
@@ -38,17 +60,6 b' def _safe_exists(path):' | |||||
38 | except Exception: |
|
60 | except Exception: | |
39 | return False |
|
61 | return False | |
40 |
|
62 | |||
41 | def _merge(d1, d2): |
|
|||
42 | """Like update, but merges sub-dicts instead of clobbering at the top level. |
|
|||
43 |
|
||||
44 | Updates d1 in-place |
|
|||
45 | """ |
|
|||
46 |
|
||||
47 | if not isinstance(d2, dict) or not isinstance(d1, dict): |
|
|||
48 | return d2 |
|
|||
49 | for key, value in d2.items(): |
|
|||
50 | d1[key] = _merge(d1.get(key), value) |
|
|||
51 | return d1 |
|
|||
52 |
|
63 | |||
53 | def _display_mimetype(mimetype, objs, raw=False, metadata=None): |
|
64 | def _display_mimetype(mimetype, objs, raw=False, metadata=None): | |
54 | """internal implementation of all display_foo methods |
|
65 | """internal implementation of all display_foo methods | |
@@ -77,321 +88,6 b' def _display_mimetype(mimetype, objs, raw=False, metadata=None):' | |||||
77 | # Main functions |
|
88 | # Main functions | |
78 | #----------------------------------------------------------------------------- |
|
89 | #----------------------------------------------------------------------------- | |
79 |
|
90 | |||
80 | # use * to indicate transient is keyword-only |
|
|||
81 | def publish_display_data(data, metadata=None, source=None, *, transient=None, **kwargs): |
|
|||
82 | """Publish data and metadata to all frontends. |
|
|||
83 |
|
||||
84 | See the ``display_data`` message in the messaging documentation for |
|
|||
85 | more details about this message type. |
|
|||
86 |
|
||||
87 | Keys of data and metadata can be any mime-type. |
|
|||
88 |
|
||||
89 | Parameters |
|
|||
90 | ---------- |
|
|||
91 | data : dict |
|
|||
92 | A dictionary having keys that are valid MIME types (like |
|
|||
93 | 'text/plain' or 'image/svg+xml') and values that are the data for |
|
|||
94 | that MIME type. The data itself must be a JSON'able data |
|
|||
95 | structure. Minimally all data should have the 'text/plain' data, |
|
|||
96 | which can be displayed by all frontends. If more than the plain |
|
|||
97 | text is given, it is up to the frontend to decide which |
|
|||
98 | representation to use. |
|
|||
99 | metadata : dict |
|
|||
100 | A dictionary for metadata related to the data. This can contain |
|
|||
101 | arbitrary key, value pairs that frontends can use to interpret |
|
|||
102 | the data. mime-type keys matching those in data can be used |
|
|||
103 | to specify metadata about particular representations. |
|
|||
104 | source : str, deprecated |
|
|||
105 | Unused. |
|
|||
106 | transient : dict, keyword-only |
|
|||
107 | A dictionary of transient data, such as display_id. |
|
|||
108 | """ |
|
|||
109 | from IPython.core.interactiveshell import InteractiveShell |
|
|||
110 |
|
||||
111 | display_pub = InteractiveShell.instance().display_pub |
|
|||
112 |
|
||||
113 | # only pass transient if supplied, |
|
|||
114 | # to avoid errors with older ipykernel. |
|
|||
115 | # TODO: We could check for ipykernel version and provide a detailed upgrade message. |
|
|||
116 | if transient: |
|
|||
117 | kwargs['transient'] = transient |
|
|||
118 |
|
||||
119 | display_pub.publish( |
|
|||
120 | data=data, |
|
|||
121 | metadata=metadata, |
|
|||
122 | **kwargs |
|
|||
123 | ) |
|
|||
124 |
|
||||
125 |
|
||||
126 | def _new_id(): |
|
|||
127 | """Generate a new random text id with urandom""" |
|
|||
128 | return b2a_hex(os.urandom(16)).decode('ascii') |
|
|||
129 |
|
||||
130 |
|
||||
131 | def display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs): |
|
|||
132 | """Display a Python object in all frontends. |
|
|||
133 |
|
||||
134 | By default all representations will be computed and sent to the frontends. |
|
|||
135 | Frontends can decide which representation is used and how. |
|
|||
136 |
|
||||
137 | In terminal IPython this will be similar to using :func:`print`, for use in richer |
|
|||
138 | frontends see Jupyter notebook examples with rich display logic. |
|
|||
139 |
|
||||
140 | Parameters |
|
|||
141 | ---------- |
|
|||
142 | *objs : object |
|
|||
143 | The Python objects to display. |
|
|||
144 | raw : bool, optional |
|
|||
145 | Are the objects to be displayed already mimetype-keyed dicts of raw display data, |
|
|||
146 | or Python objects that need to be formatted before display? [default: False] |
|
|||
147 | include : list, tuple or set, optional |
|
|||
148 | A list of format type strings (MIME types) to include in the |
|
|||
149 | format data dict. If this is set *only* the format types included |
|
|||
150 | in this list will be computed. |
|
|||
151 | exclude : list, tuple or set, optional |
|
|||
152 | A list of format type strings (MIME types) to exclude in the format |
|
|||
153 | data dict. If this is set all format types will be computed, |
|
|||
154 | except for those included in this argument. |
|
|||
155 | metadata : dict, optional |
|
|||
156 | A dictionary of metadata to associate with the output. |
|
|||
157 | mime-type keys in this dictionary will be associated with the individual |
|
|||
158 | representation formats, if they exist. |
|
|||
159 | transient : dict, optional |
|
|||
160 | A dictionary of transient data to associate with the output. |
|
|||
161 | Data in this dict should not be persisted to files (e.g. notebooks). |
|
|||
162 | display_id : str, bool optional |
|
|||
163 | Set an id for the display. |
|
|||
164 | This id can be used for updating this display area later via update_display. |
|
|||
165 | If given as `True`, generate a new `display_id` |
|
|||
166 | kwargs: additional keyword-args, optional |
|
|||
167 | Additional keyword-arguments are passed through to the display publisher. |
|
|||
168 |
|
||||
169 | Returns |
|
|||
170 | ------- |
|
|||
171 |
|
||||
172 | handle: DisplayHandle |
|
|||
173 | Returns a handle on updatable displays for use with :func:`update_display`, |
|
|||
174 | if `display_id` is given. Returns :any:`None` if no `display_id` is given |
|
|||
175 | (default). |
|
|||
176 |
|
||||
177 | Examples |
|
|||
178 | -------- |
|
|||
179 |
|
||||
180 | >>> class Json(object): |
|
|||
181 | ... def __init__(self, json): |
|
|||
182 | ... self.json = json |
|
|||
183 | ... def _repr_pretty_(self, pp, cycle): |
|
|||
184 | ... import json |
|
|||
185 | ... pp.text(json.dumps(self.json, indent=2)) |
|
|||
186 | ... def __repr__(self): |
|
|||
187 | ... return str(self.json) |
|
|||
188 | ... |
|
|||
189 |
|
||||
190 | >>> d = Json({1:2, 3: {4:5}}) |
|
|||
191 |
|
||||
192 | >>> print(d) |
|
|||
193 | {1: 2, 3: {4: 5}} |
|
|||
194 |
|
||||
195 | >>> display(d) |
|
|||
196 | { |
|
|||
197 | "1": 2, |
|
|||
198 | "3": { |
|
|||
199 | "4": 5 |
|
|||
200 | } |
|
|||
201 | } |
|
|||
202 |
|
||||
203 | >>> def int_formatter(integer, pp, cycle): |
|
|||
204 | ... pp.text('I'*integer) |
|
|||
205 |
|
||||
206 | >>> plain = get_ipython().display_formatter.formatters['text/plain'] |
|
|||
207 | >>> plain.for_type(int, int_formatter) |
|
|||
208 | <function _repr_pprint at 0x...> |
|
|||
209 | >>> display(7-5) |
|
|||
210 | II |
|
|||
211 |
|
||||
212 | >>> del plain.type_printers[int] |
|
|||
213 | >>> display(7-5) |
|
|||
214 | 2 |
|
|||
215 |
|
||||
216 | See Also |
|
|||
217 | -------- |
|
|||
218 |
|
||||
219 | :func:`update_display` |
|
|||
220 |
|
||||
221 | Notes |
|
|||
222 | ----- |
|
|||
223 |
|
||||
224 | In Python, objects can declare their textual representation using the |
|
|||
225 | `__repr__` method. IPython expands on this idea and allows objects to declare |
|
|||
226 | other, rich representations including: |
|
|||
227 |
|
||||
228 | - HTML |
|
|||
229 | - JSON |
|
|||
230 | - PNG |
|
|||
231 | - JPEG |
|
|||
232 | - SVG |
|
|||
233 | - LaTeX |
|
|||
234 |
|
||||
235 | A single object can declare some or all of these representations; all are |
|
|||
236 | handled by IPython's display system. |
|
|||
237 |
|
||||
238 | The main idea of the first approach is that you have to implement special |
|
|||
239 | display methods when you define your class, one for each representation you |
|
|||
240 | want to use. Here is a list of the names of the special methods and the |
|
|||
241 | values they must return: |
|
|||
242 |
|
||||
243 | - `_repr_html_`: return raw HTML as a string, or a tuple (see below). |
|
|||
244 | - `_repr_json_`: return a JSONable dict, or a tuple (see below). |
|
|||
245 | - `_repr_jpeg_`: return raw JPEG data, or a tuple (see below). |
|
|||
246 | - `_repr_png_`: return raw PNG data, or a tuple (see below). |
|
|||
247 | - `_repr_svg_`: return raw SVG data as a string, or a tuple (see below). |
|
|||
248 | - `_repr_latex_`: return LaTeX commands in a string surrounded by "$", |
|
|||
249 | or a tuple (see below). |
|
|||
250 | - `_repr_mimebundle_`: return a full mimebundle containing the mapping |
|
|||
251 | from all mimetypes to data. |
|
|||
252 | Use this for any mime-type not listed above. |
|
|||
253 |
|
||||
254 | The above functions may also return the object's metadata alonside the |
|
|||
255 | data. If the metadata is available, the functions will return a tuple |
|
|||
256 | containing the data and metadata, in that order. If there is no metadata |
|
|||
257 | available, then the functions will return the data only. |
|
|||
258 |
|
||||
259 | When you are directly writing your own classes, you can adapt them for |
|
|||
260 | display in IPython by following the above approach. But in practice, you |
|
|||
261 | often need to work with existing classes that you can't easily modify. |
|
|||
262 |
|
||||
263 | You can refer to the documentation on integrating with the display system in |
|
|||
264 | order to register custom formatters for already existing types |
|
|||
265 | (:ref:`integrating_rich_display`). |
|
|||
266 |
|
||||
267 | .. versionadded:: 5.4 display available without import |
|
|||
268 | .. versionadded:: 6.1 display available without import |
|
|||
269 |
|
||||
270 | Since IPython 5.4 and 6.1 :func:`display` is automatically made available to |
|
|||
271 | the user without import. If you are using display in a document that might |
|
|||
272 | be used in a pure python context or with older version of IPython, use the |
|
|||
273 | following import at the top of your file:: |
|
|||
274 |
|
||||
275 | from IPython.display import display |
|
|||
276 |
|
||||
277 | """ |
|
|||
278 | from IPython.core.interactiveshell import InteractiveShell |
|
|||
279 |
|
||||
280 | if not InteractiveShell.initialized(): |
|
|||
281 | # Directly print objects. |
|
|||
282 | print(*objs) |
|
|||
283 | return |
|
|||
284 |
|
||||
285 | raw = kwargs.pop('raw', False) |
|
|||
286 | if transient is None: |
|
|||
287 | transient = {} |
|
|||
288 | if metadata is None: |
|
|||
289 | metadata={} |
|
|||
290 | if display_id: |
|
|||
291 | if display_id is True: |
|
|||
292 | display_id = _new_id() |
|
|||
293 | transient['display_id'] = display_id |
|
|||
294 | if kwargs.get('update') and 'display_id' not in transient: |
|
|||
295 | raise TypeError('display_id required for update_display') |
|
|||
296 | if transient: |
|
|||
297 | kwargs['transient'] = transient |
|
|||
298 |
|
||||
299 | if not objs and display_id: |
|
|||
300 | # if given no objects, but still a request for a display_id, |
|
|||
301 | # we assume the user wants to insert an empty output that |
|
|||
302 | # can be updated later |
|
|||
303 | objs = [{}] |
|
|||
304 | raw = True |
|
|||
305 |
|
||||
306 | if not raw: |
|
|||
307 | format = InteractiveShell.instance().display_formatter.format |
|
|||
308 |
|
||||
309 | for obj in objs: |
|
|||
310 | if raw: |
|
|||
311 | publish_display_data(data=obj, metadata=metadata, **kwargs) |
|
|||
312 | else: |
|
|||
313 | format_dict, md_dict = format(obj, include=include, exclude=exclude) |
|
|||
314 | if not format_dict: |
|
|||
315 | # nothing to display (e.g. _ipython_display_ took over) |
|
|||
316 | continue |
|
|||
317 | if metadata: |
|
|||
318 | # kwarg-specified metadata gets precedence |
|
|||
319 | _merge(md_dict, metadata) |
|
|||
320 | publish_display_data(data=format_dict, metadata=md_dict, **kwargs) |
|
|||
321 | if display_id: |
|
|||
322 | return DisplayHandle(display_id) |
|
|||
323 |
|
||||
324 |
|
||||
325 | # use * for keyword-only display_id arg |
|
|||
326 | def update_display(obj, *, display_id, **kwargs): |
|
|||
327 | """Update an existing display by id |
|
|||
328 |
|
||||
329 | Parameters |
|
|||
330 | ---------- |
|
|||
331 |
|
||||
332 | obj: |
|
|||
333 | The object with which to update the display |
|
|||
334 | display_id: keyword-only |
|
|||
335 | The id of the display to update |
|
|||
336 |
|
||||
337 | See Also |
|
|||
338 | -------- |
|
|||
339 |
|
||||
340 | :func:`display` |
|
|||
341 | """ |
|
|||
342 | kwargs['update'] = True |
|
|||
343 | display(obj, display_id=display_id, **kwargs) |
|
|||
344 |
|
||||
345 |
|
||||
346 | class DisplayHandle(object): |
|
|||
347 | """A handle on an updatable display |
|
|||
348 |
|
||||
349 | Call `.update(obj)` to display a new object. |
|
|||
350 |
|
||||
351 | Call `.display(obj`) to add a new instance of this display, |
|
|||
352 | and update existing instances. |
|
|||
353 |
|
||||
354 | See Also |
|
|||
355 | -------- |
|
|||
356 |
|
||||
357 | :func:`display`, :func:`update_display` |
|
|||
358 |
|
||||
359 | """ |
|
|||
360 |
|
||||
361 | def __init__(self, display_id=None): |
|
|||
362 | if display_id is None: |
|
|||
363 | display_id = _new_id() |
|
|||
364 | self.display_id = display_id |
|
|||
365 |
|
||||
366 | def __repr__(self): |
|
|||
367 | return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id) |
|
|||
368 |
|
||||
369 | def display(self, obj, **kwargs): |
|
|||
370 | """Make a new display with my id, updating existing instances. |
|
|||
371 |
|
||||
372 | Parameters |
|
|||
373 | ---------- |
|
|||
374 |
|
||||
375 | obj: |
|
|||
376 | object to display |
|
|||
377 | **kwargs: |
|
|||
378 | additional keyword arguments passed to display |
|
|||
379 | """ |
|
|||
380 | display(obj, display_id=self.display_id, **kwargs) |
|
|||
381 |
|
||||
382 | def update(self, obj, **kwargs): |
|
|||
383 | """Update existing displays with my id |
|
|||
384 |
|
||||
385 | Parameters |
|
|||
386 | ---------- |
|
|||
387 |
|
||||
388 | obj: |
|
|||
389 | object to display |
|
|||
390 | **kwargs: |
|
|||
391 | additional keyword arguments passed to update_display |
|
|||
392 | """ |
|
|||
393 | update_display(obj, display_id=self.display_id, **kwargs) |
|
|||
394 |
|
||||
395 |
|
91 | |||
396 | def display_pretty(*objs, **kwargs): |
|
92 | def display_pretty(*objs, **kwargs): | |
397 | """Display the pretty (default) representation of an object. |
|
93 | """Display the pretty (default) representation of an object. | |
@@ -785,16 +481,16 b' class SVG(DisplayObject):' | |||||
785 | pass |
|
481 | pass | |
786 | svg = cast_unicode(svg) |
|
482 | svg = cast_unicode(svg) | |
787 | self._data = svg |
|
483 | self._data = svg | |
788 |
|
484 | |||
789 | def _repr_svg_(self): |
|
485 | def _repr_svg_(self): | |
790 | return self._data_and_metadata() |
|
486 | return self._data_and_metadata() | |
791 |
|
487 | |||
792 | class ProgressBar(DisplayObject): |
|
488 | class ProgressBar(DisplayObject): | |
793 |
"""Progressbar supports displaying a progressbar like element |
|
489 | """Progressbar supports displaying a progressbar like element | |
794 | """ |
|
490 | """ | |
795 | def __init__(self, total): |
|
491 | def __init__(self, total): | |
796 | """Creates a new progressbar |
|
492 | """Creates a new progressbar | |
797 |
|
493 | |||
798 | Parameters |
|
494 | Parameters | |
799 | ---------- |
|
495 | ---------- | |
800 | total : int |
|
496 | total : int | |
@@ -874,7 +570,7 b' class JSON(DisplayObject):' | |||||
874 | metadata: dict |
|
570 | metadata: dict | |
875 | Specify extra metadata to attach to the json display object. |
|
571 | Specify extra metadata to attach to the json display object. | |
876 | root : str |
|
572 | root : str | |
877 |
The name of the root element of the JSON tree |
|
573 | The name of the root element of the JSON tree | |
878 | """ |
|
574 | """ | |
879 | self.metadata = { |
|
575 | self.metadata = { | |
880 | 'expanded': expanded, |
|
576 | 'expanded': expanded, | |
@@ -937,7 +633,7 b' class GeoJSON(JSON):' | |||||
937 |
|
633 | |||
938 | Scalar types (None, number, string) are not allowed, only dict containers. |
|
634 | Scalar types (None, number, string) are not allowed, only dict containers. | |
939 | """ |
|
635 | """ | |
940 |
|
636 | |||
941 | def __init__(self, *args, **kwargs): |
|
637 | def __init__(self, *args, **kwargs): | |
942 | """Create a GeoJSON display object given raw data. |
|
638 | """Create a GeoJSON display object given raw data. | |
943 |
|
639 | |||
@@ -986,7 +682,7 b' class GeoJSON(JSON):' | |||||
986 | the GeoJSON object. |
|
682 | the GeoJSON object. | |
987 |
|
683 | |||
988 | """ |
|
684 | """ | |
989 |
|
685 | |||
990 | super(GeoJSON, self).__init__(*args, **kwargs) |
|
686 | super(GeoJSON, self).__init__(*args, **kwargs) | |
991 |
|
687 | |||
992 |
|
688 | |||
@@ -1221,7 +917,7 b' class Image(DisplayObject):' | |||||
1221 | self.height = height |
|
917 | self.height = height | |
1222 | self.retina = retina |
|
918 | self.retina = retina | |
1223 | self.unconfined = unconfined |
|
919 | self.unconfined = unconfined | |
1224 |
super(Image, self).__init__(data=data, url=url, filename=filename, |
|
920 | super(Image, self).__init__(data=data, url=url, filename=filename, | |
1225 | metadata=metadata) |
|
921 | metadata=metadata) | |
1226 |
|
922 | |||
1227 | if self.width is None and self.metadata.get('width', {}): |
|
923 | if self.width is None and self.metadata.get('width', {}): | |
@@ -1452,23 +1148,6 b' class Video(DisplayObject):' | |||||
1452 | pass |
|
1148 | pass | |
1453 |
|
1149 | |||
1454 |
|
1150 | |||
1455 | def clear_output(wait=False): |
|
|||
1456 | """Clear the output of the current cell receiving output. |
|
|||
1457 |
|
||||
1458 | Parameters |
|
|||
1459 | ---------- |
|
|||
1460 | wait : bool [default: false] |
|
|||
1461 | Wait to clear the output until new output is available to replace it.""" |
|
|||
1462 | from IPython.core.interactiveshell import InteractiveShell |
|
|||
1463 | if InteractiveShell.initialized(): |
|
|||
1464 | InteractiveShell.instance().display_pub.clear_output(wait) |
|
|||
1465 | else: |
|
|||
1466 | print('\033[2K\r', end='') |
|
|||
1467 | sys.stdout.flush() |
|
|||
1468 | print('\033[2K\r', end='') |
|
|||
1469 | sys.stderr.flush() |
|
|||
1470 |
|
||||
1471 |
|
||||
1472 | @skip_doctest |
|
1151 | @skip_doctest | |
1473 | def set_matplotlib_formats(*formats, **kwargs): |
|
1152 | def set_matplotlib_formats(*formats, **kwargs): | |
1474 | """Select figure formats for the inline backend. Optionally pass quality for JPEG. |
|
1153 | """Select figure formats for the inline backend. Optionally pass quality for JPEG. |
@@ -22,7 +22,7 b' from traitlets.config.configurable import Configurable' | |||||
22 | from traitlets import List |
|
22 | from traitlets import List | |
23 |
|
23 | |||
24 | # This used to be defined here - it is imported for backwards compatibility |
|
24 | # This used to be defined here - it is imported for backwards compatibility | |
25 | from .display import publish_display_data |
|
25 | from .display_functions import publish_display_data | |
26 |
|
26 | |||
27 | #----------------------------------------------------------------------------- |
|
27 | #----------------------------------------------------------------------------- | |
28 | # Main payload class |
|
28 | # Main payload class |
@@ -12,7 +12,7 b'' | |||||
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | # Our own packages |
|
14 | # Our own packages | |
15 |
from IPython |
|
15 | from IPython.display import display, Javascript, Latex, SVG, HTML, Markdown | |
16 | from IPython.core.magic import ( |
|
16 | from IPython.core.magic import ( | |
17 | Magics, magics_class, cell_magic |
|
17 | Magics, magics_class, cell_magic | |
18 | ) |
|
18 | ) |
@@ -24,7 +24,7 b' import subprocess' | |||||
24 | from io import UnsupportedOperation |
|
24 | from io import UnsupportedOperation | |
25 |
|
25 | |||
26 | from IPython import get_ipython |
|
26 | from IPython import get_ipython | |
27 |
from IPython |
|
27 | from IPython.display import display | |
28 | from IPython.core.error import TryNext |
|
28 | from IPython.core.error import TryNext | |
29 | from IPython.utils.data import chop |
|
29 | from IPython.utils.data import chop | |
30 | from IPython.utils.process import system |
|
30 | from IPython.utils.process import system |
@@ -354,7 +354,7 b' def import_pylab(user_ns, import_all=True):' | |||||
354 |
|
354 | |||
355 | # IPython symbols to add |
|
355 | # IPython symbols to add | |
356 | user_ns['figsize'] = figsize |
|
356 | user_ns['figsize'] = figsize | |
357 |
from IPython |
|
357 | from IPython.display import display | |
358 | # Add display and getfigs to the user's namespace |
|
358 | # Add display and getfigs to the user's namespace | |
359 | user_ns['display'] = display |
|
359 | user_ns['display'] = display | |
360 | user_ns['getfigs'] = getfigs |
|
360 | user_ns['getfigs'] = getfigs |
@@ -9,7 +9,7 b' from unittest import mock' | |||||
9 |
|
9 | |||
10 | import nose.tools as nt |
|
10 | import nose.tools as nt | |
11 |
|
11 | |||
12 |
from IPython |
|
12 | from IPython import display | |
13 | from IPython.core.getipython import get_ipython |
|
13 | from IPython.core.getipython import get_ipython | |
14 | from IPython.utils.io import capture_output |
|
14 | from IPython.utils.io import capture_output | |
15 | from IPython.utils.tempdir import NamedFileInTemporaryDirectory |
|
15 | from IPython.utils.tempdir import NamedFileInTemporaryDirectory |
@@ -1,16 +1,44 b'' | |||||
1 | """Public API for display tools in IPython. |
|
1 | """Public API for display tools in IPython. | |
2 | """ |
|
2 | """ | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | # ----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2012 The IPython Development Team |
|
5 | # Copyright (C) 2012 The IPython Development Team | |
6 | # |
|
6 | # | |
7 | # Distributed under the terms of the BSD License. The full license is in |
|
7 | # Distributed under the terms of the BSD License. The full license is in | |
8 | # the file COPYING, distributed as part of this software. |
|
8 | # the file COPYING, distributed as part of this software. | |
9 | #----------------------------------------------------------------------------- |
|
9 | # ----------------------------------------------------------------------------- | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | # ----------------------------------------------------------------------------- | |
12 | # Imports |
|
12 | # Imports | |
13 | #----------------------------------------------------------------------------- |
|
13 | # ----------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | from IPython.core.display import * |
|
15 | from IPython.core.display_functions import * | |
|
16 | from IPython.core.display import ( | |||
|
17 | display_pretty, | |||
|
18 | display_html, | |||
|
19 | display_markdown, | |||
|
20 | display_svg, | |||
|
21 | display_png, | |||
|
22 | display_jpeg, | |||
|
23 | display_latex, | |||
|
24 | display_json, | |||
|
25 | display_javascript, | |||
|
26 | display_pdf, | |||
|
27 | DisplayObject, | |||
|
28 | TextDisplayObject, | |||
|
29 | Pretty, | |||
|
30 | HTML, | |||
|
31 | Markdown, | |||
|
32 | Math, | |||
|
33 | Latex, | |||
|
34 | SVG, | |||
|
35 | ProgressBar, | |||
|
36 | JSON, | |||
|
37 | GeoJSON, | |||
|
38 | Javascript, | |||
|
39 | Image, | |||
|
40 | set_matplotlib_formats, | |||
|
41 | set_matplotlib_close, | |||
|
42 | Video, | |||
|
43 | ) | |||
16 | from IPython.lib.display import * |
|
44 | from IPython.lib.display import * |
@@ -57,6 +57,7 b" warnings.filterwarnings('error', message='.*onlyif_any_cmd_exists.*', category=D" | |||||
57 | warnings.filterwarnings('error', message='.*disable_gui.*', category=DeprecationWarning, module='.*') |
|
57 | warnings.filterwarnings('error', message='.*disable_gui.*', category=DeprecationWarning, module='.*') | |
58 |
|
58 | |||
59 | warnings.filterwarnings('error', message='.*ExceptionColors global is deprecated.*', category=DeprecationWarning, module='.*') |
|
59 | warnings.filterwarnings('error', message='.*ExceptionColors global is deprecated.*', category=DeprecationWarning, module='.*') | |
|
60 | warnings.filterwarnings('error', message='.*IPython.core.display.*', category=DeprecationWarning, module='.*') | |||
60 |
|
61 | |||
61 | # Jedi older versions |
|
62 | # Jedi older versions | |
62 | warnings.filterwarnings( |
|
63 | warnings.filterwarnings( |
General Comments 0
You need to be logged in to leave comments.
Login now