##// END OF EJS Templates
Backport PR #10596 on branch 5.x...
Kyle Kelley -
Show More
@@ -144,6 +144,9 b' def display(*objs, **kwargs):'
144 144 By default all representations will be computed and sent to the frontends.
145 145 Frontends can decide which representation is used and how.
146 146
147 In terminal IPython this will be similar to using :func:`print`, for use in richer
148 frontends see Jupyter notebook examples with rich display logic.
149
147 150 Parameters
148 151 ----------
149 152 objs : tuple of objects
@@ -151,11 +154,11 b' def display(*objs, **kwargs):'
151 154 raw : bool, optional
152 155 Are the objects to be displayed already mimetype-keyed dicts of raw display data,
153 156 or Python objects that need to be formatted before display? [default: False]
154 include : list or tuple, optional
157 include : list, tuple or set, optional
155 158 A list of format type strings (MIME types) to include in the
156 159 format data dict. If this is set *only* the format types included
157 160 in this list will be computed.
158 exclude : list or tuple, optional
161 exclude : list, tuple or set, optional
159 162 A list of format type strings (MIME types) to exclude in the format
160 163 data dict. If this is set all format types will be computed,
161 164 except for those included in this argument.
@@ -166,19 +169,113 b' def display(*objs, **kwargs):'
166 169 transient : dict, optional
167 170 A dictionary of transient data to associate with the output.
168 171 Data in this dict should not be persisted to files (e.g. notebooks).
169 display_id : str, optional
172 display_id : str, bool optional
170 173 Set an id for the display.
171 174 This id can be used for updating this display area later via update_display.
172 If given as True, generate a new display_id
175 If given as `True`, generate a new `display_id`
173 176 kwargs: additional keyword-args, optional
174 177 Additional keyword-arguments are passed through to the display publisher.
175
178
176 179 Returns
177 180 -------
178
181
179 182 handle: DisplayHandle
180 Returns a handle on updatable displays, if display_id is given.
181 Returns None if no display_id is given (default).
183 Returns a handle on updatable displays for use with :func:`update_display`,
184 if `display_id` is given. Returns :any:`None` if no `display_id` is given
185 (default).
186
187 Examples
188 --------
189
190 >>> class Json(object):
191 ... def __init__(self, json):
192 ... self.json = json
193 ... def _repr_pretty_(self, pp, cycle):
194 ... import json
195 ... pp.text(json.dumps(self.json, indent=2))
196 ... def __repr__(self):
197 ... return str(self.json)
198 ...
199
200 >>> d = Json({1:2, 3: {4:5}})
201
202 >>> print(d)
203 {1: 2, 3: {4: 5}}
204
205 >>> display(d)
206 {
207 "1": 2,
208 "3": {
209 "4": 5
210 }
211 }
212
213 >>> def int_formatter(integer, pp, cycle):
214 ... pp.text('I'*integer)
215
216 >>> plain = get_ipython().display_formatter.formatters['text/plain']
217 >>> plain.for_type(int, int_formatter)
218 <function _repr_pprint at 0x...>
219 >>> display(7-5)
220 II
221
222 >>> del plain.type_printers[int]
223 >>> display(7-5)
224 2
225
226 See Also
227 --------
228
229 :func:`update_display`
230
231 Notes
232 -----
233
234 In Python, objects can declare their textual representation using the
235 `__repr__` method. IPython expands on this idea and allows objects to declare
236 other, rich representations including:
237
238 - HTML
239 - JSON
240 - PNG
241 - JPEG
242 - SVG
243 - LaTeX
244
245 A single object can declare some or all of these representations; all are
246 handled by IPython's display system.
247
248 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 want to use. Here is a list of the names of the special methods and the
251 values they must return:
252
253 - `_repr_html_`: return raw HTML as a string
254 - `_repr_json_`: return a JSONable dict
255 - `_repr_jpeg_`: return raw JPEG data
256 - `_repr_png_`: return raw PNG data
257 - `_repr_svg_`: return raw SVG data as a string
258 - `_repr_latex_`: return LaTeX commands in a string surrounded by "$".
259 - `_repr_mimebundle_`: return a full mimebundle containing the mapping
260 from all mimetypes to data
261
262 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 often need to work with existing classes that you can't easily modify.
265
266 You can refer to the documentation on IPython display formatters in order to
267 register custom formatters for already existing types.
268
269 .. versionadded:: 5.4 display available without import
270 .. versionadded:: 6.1 display available without import
271
272 Since IPython 5.4 and 6.1 :func:`display` is automatically made available to
273 the user without import. If you are using display in a document that might
274 be used in a pure python context or with older version of IPython, use the
275 following import at the top of your file::
276
277 from IPython.display import display
278
182 279 """
183 280 raw = kwargs.pop('raw', False)
184 281 include = kwargs.pop('include', None)
@@ -189,7 +286,7 b' def display(*objs, **kwargs):'
189 286 if transient is None:
190 287 transient = {}
191 288 if display_id:
192 if display_id == True:
289 if display_id is True:
193 290 display_id = _new_id()
194 291 transient['display_id'] = display_id
195 292 if kwargs.get('update') and 'display_id' not in transient:
@@ -229,6 +326,11 b' def update_display(obj, **kwargs):'
229 326 The object with which to update the display
230 327 display_id: keyword-only
231 328 The id of the display to update
329
330 See Also
331 --------
332
333 :func:`display`
232 334 """
233 335 sentinel = object()
234 336 display_id = kwargs.pop('display_id', sentinel)
@@ -241,10 +343,16 b' def update_display(obj, **kwargs):'
241 343 class DisplayHandle(object):
242 344 """A handle on an updatable display
243 345
244 Call .update(obj) to display a new object.
346 Call `.update(obj)` to display a new object.
245 347
246 Call .display(obj) to add a new instance of this display,
348 Call `.display(obj`) to add a new instance of this display,
247 349 and update existing instances.
350
351 See Also
352 --------
353
354 :func:`display`, :func:`update_display`
355
248 356 """
249 357
250 358 def __init__(self, display_id=None):
@@ -58,6 +58,7 b' from IPython.core.prefilter import PrefilterManager'
58 58 from IPython.core.profiledir import ProfileDir
59 59 from IPython.core.usage import default_banner
60 60 from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest
61 from IPython.display import display
61 62 from IPython.utils import PyColorize
62 63 from IPython.utils import io
63 64 from IPython.utils import py3compat
@@ -636,6 +637,7 b' class InteractiveShell(SingletonConfigurable):'
636 637 # removing on exit or representing the existence of more than one
637 638 # IPython at a time.
638 639 builtin_mod.__dict__['__IPYTHON__'] = True
640 builtin_mod.__dict__['display'] = display
639 641
640 642 self.builtin_trap = BuiltinTrap(shell=self)
641 643
@@ -12,6 +12,7 b' from IPython.core import display'
12 12 from IPython.core.getipython import get_ipython
13 13 from IPython.utils.tempdir import NamedFileInTemporaryDirectory
14 14 from IPython import paths as ipath
15 from IPython.testing.tools import AssertPrints, AssertNotPrints
15 16
16 17 import IPython.testing.decorators as dec
17 18
@@ -123,6 +124,25 b' def test_set_matplotlib_formats_kwargs():'
123 124 expected.update(cfg.print_figure_kwargs)
124 125 nt.assert_equal(cell, expected)
125 126
127 def test_display_available():
128 """
129 Test that display is available without import
130
131 We don't really care if it's in builtin or anything else, but it should
132 always be available.
133 """
134 ip = get_ipython()
135 with AssertNotPrints('NameError'):
136 ip.run_cell('display')
137 try:
138 ip.run_cell('del display')
139 except NameError:
140 pass # it's ok, it might be in builtins
141 # even if deleted it should be back
142 with AssertNotPrints('NameError'):
143 ip.run_cell('display')
144
145
126 146 def test_displayobject_repr():
127 147 h = display.HTML('<br />')
128 148 nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
@@ -1,7 +1,32 b''
1 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 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 30 One major feature of the IPython kernel is the ability to display plots that
6 31 are the output of running code cells. The IPython kernel is designed to work
7 32 seamlessly with the matplotlib_ plotting library to provide this functionality.
@@ -50,6 +50,19 b' Implement display id and ability to update a given display. This should greatly'
50 50 simplify a lot of code by removing the need for widgets and allow other frontend
51 51 to implement things like progress-bars. See :ghpull:`10048`
52 52
53 Display function
54 ----------------
55
56 The :func:`display() <IPython.display.display>` function is now available by
57 default in an IPython session, meaning users can call it on any object to see
58 their rich representation. This should allow for better interactivity both at
59 the REPL and in notebook environment.
60
61 Scripts and library that rely on display and may be run outside of IPython still
62 need to import the display function using ``from IPython.display import
63 display``. See :ghpull:`10596`
64
65
53 66 Miscs
54 67 -----
55 68
General Comments 0
You need to be logged in to leave comments. Login now