Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 39 ยท Cells and Magics

Rich Output and display()

Show more than plain text in Jupyter: display(), IPython.display classes for HTML, Markdown, images and math, custom _repr_html_ methods, MIME bundles and live updates.

A terminal can only show text. A notebook can show tables, formatted text, images, audio, video, equations and interactive widgets right below the cell that produced them. This works because the kernel does not send just a string: it sends a bundle with several representations of the same object, and the front end picks the richest one it understands. In this lesson you learn how that mechanism works and how to use it from your own code.

Rich display needs a notebook front end, which this site cannot provide. The IPython.display examples are read-only. The stand-ins reproduce the selection logic with plain Python so you can see how an object becomes a table or a picture.

Three kinds of output

Recall from The .ipynb file format the outputs stored in a cell. You create them in three ways:

  1. print(...) produces stream text.
  2. The last expression of the cell becomes an execute_result, shown with its richest representation. It is displayed once, as the cell's Out [n].
  3. display(obj) produces a display_data output at any point of the cell, as many times as you like.
Python
from IPython.display import display

for n in (1, 2, 3):
    display(n * n)       # three separate outputs
n * 100                   # and the final expression

display is imported automatically in IPython kernels in recent versions, but importing it explicitly makes the code clear and portable.

The IPython.display toolbox

Class or function Shows
HTML("<b>text</b>") Rendered HTML
Markdown("**bold** text") Rendered Markdown
Math(r"\frac{a}{b}") and Latex(...) Formulas through MathJax
Image(filename="plot.png") or Image(url=...) A picture
SVG(data) Vector graphics
JSON(data) An expandable JSON tree
Audio(data=..., rate=...), Video(...) Players
IFrame(src, width, height) An embedded page
Javascript("code") Run JavaScript in the browser page
clear_output(wait=True) Erase output before showing new output
display(obj, display_id=True) A handle you can later update in place

Example with a formatted summary (read-only):

Python
from IPython.display import display, HTML, Markdown

total = 128
display(Markdown(f"### Result\n\nWe processed **{total}** records."))
display(HTML("<span style='color: seagreen'>All checks passed</span>"))

Only trusted code should produce HTML or JavaScript from external text. If you build HTML from user data, escape it first (html.escape), the same rule as in any web page.

How an object chooses its look

When you show an object, IPython calls special methods if they exist on its class:

Method Returns MIME type
_repr_html_() An HTML string text/html
_repr_markdown_() Markdown text/markdown
_repr_latex_() LaTeX text/latex
_repr_svg_() SVG source image/svg+xml
_repr_png_() / _repr_jpeg_() Image bytes image/png, image/jpeg
_repr_json_() A dict or list application/json
_repr_mimebundle_() A dict of several types at once any
__repr__() A plain string text/plain (always the fallback)

pandas DataFrames, Matplotlib figures and SymPy expressions all use these hooks. That is why df shows a nice table and print(df) shows text. The front end receives all representations in a MIME bundle ({"text/plain": ..., "text/html": ...}) and shows the richest one it supports. A viewer that cannot show HTML (for example a plain terminal) falls back to text/plain.

flowchart LR
    O["Python object"] --> F["IPython formatters"]
    F --> B["MIME bundle: text/plain, text/html, image/png"]
    B --> UI["Front end chooses the richest it can show"]
    UI --> T["Notebook: HTML table"]
    UI --> C["Terminal: plain text"]

One object, several representations, a front end that picks.

Try it: your own repr_html

The class below defines a plain and an HTML representation. The helper function plays the role of IPython: it collects every available representation into a bundle. We run it in plain Python.

Python Stand-in: build a MIME bundle for an object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a real notebook, typing Temperature(34) as the last line of a cell would render the coloured text, because the kernel's formatter calls _repr_html_ for you.

Display several things and update in place

display() can show many items from one cell, and when you pass display_id=True it returns a handle. Calling handle.update(new_object) replaces the output without adding a new one, perfect for a progress counter. A stand-in makes the idea concrete:

Python Stand-in: updating an output in place

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The real version looks like this (read-only):

Python
from IPython.display import display
import time

handle = display("starting...", display_id=True)
for step in range(1, 4):
    time.sleep(1)
    handle.update(f"processed {step} of 3")

clear_output(wait=True) achieves a similar effect by erasing the whole output area just before the next write; use it for live-updating text, but use update when you want to change only one item.

Output size and control

  • Long outputs can be collapsed or put into a scrollable area: click the blue bar to the left of the output.
  • Clear outputs from the Edit menu removes stale results.
  • %%capture (Line and cell magics) keeps noisy output out of the notebook.
  • Printing a huge object stores all of it in the file and slows the browser. Show df.head() or a summary instead.
  • Sensitive data in outputs is saved in the .ipynb; clear it before sharing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which method makes a custom class show a table or styled text in a notebook?

    IPython calls _repr_html_ (and the other _repr_*_ methods) to build rich representations.
  2. 2. What is a MIME bundle?

    The kernel sends several representations (text/plain, text/html, image/png) and the front end chooses.
  3. 3. How does display(x) differ from ending a cell with x?

    Only the final expression becomes the cell's result; display can be called anywhere, repeatedly.
  4. 4. How do you update one output in place, such as a progress message?

    A display handle lets you replace that output without adding a new one.

Summary

  • Output is stream text, the last expression's result, or anything shown with display().
  • IPython.display offers HTML, Markdown, Math, Image, SVG, JSON, Audio, Video, IFrame and more.
  • Objects choose their look with _repr_html_, _repr_markdown_, _repr_png_ and similar methods.
  • The kernel sends a MIME bundle and the front end picks the richest type it supports.
  • display_id with update, or clear_output(wait=True), gives live-updating output.
  • Keep outputs small and free of secrets, since they are saved in the file.

Next: Timing and profiling