parente.dev

Jupyter Tidbit: Display handles

November 03, 2018

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


Summary

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.

Example

Binder

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.

display_handle.ipynb

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'))
dh.display(Markdown(''))

Update the display above.

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

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.