Jupyter Tidbit: Display handles

November 03, 2018

This post originates from a gist that supports comments, forks, and execution in binder.


IPython's display() function can return a DisplayHandle object. You can use a DisplayHandle to update the output of one cell from any other cell in a Jupyter Notebook.



The display_handle.ipynb notebook below calls display(display_id=True) to get a display handle instance. It then uses the DisplayHandle.display method to show some initial, static Markdown. Later, in a different cell, it calls DisplayHandle.update in a loop to show a range of emoji characters.

Why is this useful?

You can use display handles to redraw matplotlib plots, re-render DataFrame tables, print log file updates, etc. from code executed anywhere in the notebook.


In [ ]:
import itertools
import time

from IPython.display import Markdown

Make a display handle.

In [ ]:
dh = display(display_id=True)

Show some Markdown (or plain text, or a plot, or ...)

In [ ]:
display(Markdown('# Display Update Fun'))

Update the display above.

In [ ]:
for i in itertools.cycle(range(0x1F600, 0x1F650)):
    dh.update(Markdown(f'## &#{i}; {hex(i)}'))

Another Read: Jupyter Tidbit: IPython's ! returns an SList »

IPython shell assignment (the ! operator) evaluates a command using the local shell (e.g., bash) and returns a string list (IPython.utils.text.SList). An SList is a list-like object containing "chunks" of stdout and stderr, properties for accessing those chunks in different forms, and convenience methods for operating on them.