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 | 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 | 9 | import json |
|
10 | 10 | import mimetypes |
|
11 | 11 | import os |
|
12 | 12 | import struct |
|
13 | import sys | |
|
14 | 13 | import warnings |
|
15 | 14 | from copy import deepcopy |
|
16 | 15 | from os.path import splitext |
@@ -18,14 +17,15 b' from pathlib import Path, PurePath' | |||
|
18 | 17 | |
|
19 | 18 | from IPython.utils.py3compat import cast_unicode |
|
20 | 19 | from IPython.testing.skipdoctest import skip_doctest |
|
20 | from .display_functions import display, clear_output, publish_display_data, update_display, DisplayHandle | |
|
21 | 21 | |
|
22 | 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'] | |
|
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 | 29 | |
|
30 | 30 | #----------------------------------------------------------------------------- |
|
31 | 31 | # utility functions |
@@ -38,17 +38,6 b' def _safe_exists(path):' | |||
|
38 | 38 | except Exception: |
|
39 | 39 | return False |
|
40 | 40 | |
|
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 | 41 | |
|
53 | 42 | def _display_mimetype(mimetype, objs, raw=False, metadata=None): |
|
54 | 43 | """internal implementation of all display_foo methods |
@@ -77,321 +66,6 b' def _display_mimetype(mimetype, objs, raw=False, metadata=None):' | |||
|
77 | 66 | # Main functions |
|
78 | 67 | #----------------------------------------------------------------------------- |
|
79 | 68 | |
|
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 | 69 | |
|
396 | 70 | def display_pretty(*objs, **kwargs): |
|
397 | 71 | """Display the pretty (default) representation of an object. |
@@ -764,16 +438,16 b' class SVG(DisplayObject):' | |||
|
764 | 438 | pass |
|
765 | 439 | svg = cast_unicode(svg) |
|
766 | 440 | self._data = svg |
|
767 | ||
|
441 | ||
|
768 | 442 | def _repr_svg_(self): |
|
769 | 443 | return self._data_and_metadata() |
|
770 | 444 | |
|
771 | 445 | class ProgressBar(DisplayObject): |
|
772 |
"""Progressbar supports displaying a progressbar like element |
|
|
446 | """Progressbar supports displaying a progressbar like element | |
|
773 | 447 | """ |
|
774 | 448 | def __init__(self, total): |
|
775 | 449 | """Creates a new progressbar |
|
776 | ||
|
450 | ||
|
777 | 451 | Parameters |
|
778 | 452 | ---------- |
|
779 | 453 | total : int |
@@ -853,7 +527,7 b' class JSON(DisplayObject):' | |||
|
853 | 527 | metadata: dict |
|
854 | 528 | Specify extra metadata to attach to the json display object. |
|
855 | 529 | root : str |
|
856 |
The name of the root element of the JSON tree |
|
|
530 | The name of the root element of the JSON tree | |
|
857 | 531 | """ |
|
858 | 532 | self.metadata = { |
|
859 | 533 | 'expanded': expanded, |
@@ -916,7 +590,7 b' class GeoJSON(JSON):' | |||
|
916 | 590 | |
|
917 | 591 | Scalar types (None, number, string) are not allowed, only dict containers. |
|
918 | 592 | """ |
|
919 | ||
|
593 | ||
|
920 | 594 | def __init__(self, *args, **kwargs): |
|
921 | 595 | """Create a GeoJSON display object given raw data. |
|
922 | 596 | |
@@ -965,7 +639,7 b' class GeoJSON(JSON):' | |||
|
965 | 639 | the GeoJSON object. |
|
966 | 640 | |
|
967 | 641 | """ |
|
968 | ||
|
642 | ||
|
969 | 643 | super(GeoJSON, self).__init__(*args, **kwargs) |
|
970 | 644 | |
|
971 | 645 | |
@@ -1200,7 +874,7 b' class Image(DisplayObject):' | |||
|
1200 | 874 | self.height = height |
|
1201 | 875 | self.retina = retina |
|
1202 | 876 | self.unconfined = unconfined |
|
1203 |
super(Image, self).__init__(data=data, url=url, filename=filename, |
|
|
877 | super(Image, self).__init__(data=data, url=url, filename=filename, | |
|
1204 | 878 | metadata=metadata) |
|
1205 | 879 | |
|
1206 | 880 | if self.width is None and self.metadata.get('width', {}): |
@@ -1422,23 +1096,6 b' class Video(DisplayObject):' | |||
|
1422 | 1096 | pass |
|
1423 | 1097 | |
|
1424 | 1098 | |
|
1425 | def clear_output(wait=False): | |
|
1426 | """Clear the output of the current cell receiving output. | |
|
1427 | ||
|
1428 | Parameters | |
|
1429 | ---------- | |
|
1430 | wait : bool [default: false] | |
|
1431 | Wait to clear the output until new output is available to replace it.""" | |
|
1432 | from IPython.core.interactiveshell import InteractiveShell | |
|
1433 | if InteractiveShell.initialized(): | |
|
1434 | InteractiveShell.instance().display_pub.clear_output(wait) | |
|
1435 | else: | |
|
1436 | print('\033[2K\r', end='') | |
|
1437 | sys.stdout.flush() | |
|
1438 | print('\033[2K\r', end='') | |
|
1439 | sys.stderr.flush() | |
|
1440 | ||
|
1441 | ||
|
1442 | 1099 | @skip_doctest |
|
1443 | 1100 | def set_matplotlib_formats(*formats, **kwargs): |
|
1444 | 1101 | """Select figure formats for the inline backend. Optionally pass quality for JPEG. |
General Comments 0
You need to be logged in to leave comments.
Login now