iPython display

Python
Published

November 25, 2023

The display functions from iPython is nice in an interactive Jupyter notebook. Unfortunately, it does not work equally well in Quarto or in a Jupyter notebook converted into html.

The JSON method is particularly helpful to explore a Python dictionary but does not work in rendered notebooks.

Nevertheless, it was good to get to know the functions and I add them here for the learning record.


see the Jupyter notebook (with nbconvert) and Quarto rendered version.

JSON

from IPython.display import JSON

person = {
    'name': {
        'first': 'Jane',
        'last': 'Doe'
    },
    'age': 43,
    'email': 'jane.doe@example.com'
}

JSON(person)
<IPython.core.display.JSON object>


Single element

from IPython.display import Markdown, HTML, JSON, Math
HTML("<h2>HTML Title</h2>")

HTML Title

Markdown("## Markdown title")

Markdown title

Math("a^2 + b^2 = c^2")

\(\displaystyle a^2 + b^2 = c^2\)

JSON(["foo", {"bar": ("baz", None, 1.0, 2)}], expanded=True)
<IPython.core.display.JSON object>

Multiple elements

display(HTML("<em>HTML element</em>"))
display(Markdown("__Markdown title__"))
display(Math("a^2 + b^2 = c^2"))
HTML element

Markdown title

\(\displaystyle a^2 + b^2 = c^2\)

An example of a Quarto issue with display(). The elements are ordered differently in the code cell and the output.

print("'first element'")
display("second element")
print("'third element'")
'first element'
'second element'
'third element'

Rendering of dictionaries with JSON does not work in Quarto or nbconvert.


Quarto workflow

A note how I render the Jupyter notebook of the post.

cd snippets ;
ruff format ipython-display.ipynb ;
jupyter-nbconvert --execute --inplace ipython-display.ipynb ;
nbdev_clean --fname ipython-display.ipynb ;
jupyter-nbconvert --to html ipython-display.ipynb --output ipython-display-nbconvert.html