Defining Custom Display Logic for Your Own Objects


In Python, objects can declare their textual representation using the __repr__ method. IPython expands on this idea and allows objects to declare other, richer representations including:

  • HTML
  • JSON
  • PNG
  • JPEG
  • SVG
  • LaTeX

This Notebook shows how you can add custom display logic to your own classes, so that they can be displayed using these rich representations. There are two ways of accomplishing this:

  1. Implementing special display methods such as _repr_html_.
  2. Registering a display function for a particular type.

In this Notebook we show how both approaches work.

Before we get started, we will import the various display functions for displaying the different formats we will create.

In [ ]:
from IPython.display import display
from IPython.display import (
    display_html, display_jpeg, display_png,
    display_javascript, display_svg, display_latex

Implementing special display methods

The main idea of the first approach is that you have to implement special display methods, one for each representation you want to use. Here is a list of the names of the special methods and the values they must return:

  • _repr_html_: return raw HTML as a string
  • _repr_json_: return raw JSON as a string
  • _repr_jpeg_: return raw JPEG data
  • _repr_png_: return raw PNG data
  • _repr_svg_: return raw SVG data as a string
  • _repr_latex_: return LaTeX commands in a string surrounded by "$".

Model Citizen: pandas

A prominent example of a package that has IPython-aware rich representations of its objects is pandas.

A pandas DataFrame has a rich HTML table representation, using _repr_html_.

In [ ]:
import pandas
In [ ]:
%%writefile data.csv
Date,Open,High,Low,Close,Volume,Adj Close
In [ ]:
df = pandas.read_csv("data.csv")
pandas.set_option('display.notebook_repr_html', False)

rich HTML can be activated via pandas.set_option.

In [ ]:
pandas.set_option('display.notebook_repr_html', True)
In [ ]:
lines = df._repr_html_().splitlines()


Write a simple Circle Python class. Don't even worry about properties such as radius, position, colors, etc. To help you out use the following representations (remember to wrap them in Python strings):


For SVG:

<svg width="100px" height="100px">
    <circle cx="50" cy="50" r="20" stroke="black" stroke-width="1" fill="white"/>

For LaTeX (wrap with $ and use a raw Python string):


After you write the class, create an instance and then use display_html, display_svg and display_latex to display those representations.

Tips : you can slightly tweek the representation to know from which _repr_*_ method it came from. For example in my solution the svg representation is blue, and the HTML one show "HTML" between brackets.


Here is my simple Circle class:

In [ ]:

Now create an instance and use the display methods:

In [ ]:
c = MyCircle()
In [ ]:
In [ ]:
In [ ]:
In [ ]:

Adding IPython display support to existing objects

When you are directly writing your own classes, you can adapt them for display in IPython by following the above example. But in practice, we often need to work with existing code we can't modify. We now illustrate how to add these kinds of extended display capabilities to existing objects. To continue with our example above, we will add a PNG representation to our Circle class using Matplotlib.

Model citizen: sympy

SymPy is another model citizen that defines rich representations of its object. Unlike pandas above, sympy registers display formatters via IPython's display formatter API, rather than declaring _repr_mime_ methods.

In [ ]:
from sympy import Rational, pi, exp, I, symbols
x, y, z = symbols("x y z")
In [ ]:
r = Rational(3,2)*pi + exp(I*x) / (x**2 + y)

SymPy provides an init_printing function that sets up advanced formatting (including $\LaTeX$ representations) of its objects:

In [ ]:
from sympy.interactive.printing import init_printing
init_printing(use_latex=False)  # no LaTeX enabled, we get unicode printing
In [ ]:
# Now activate LaTeX
init_printing( use_latex=True )

To add a display method to an existing class, we must use IPython's display formatter API. Here we show all of the available formatters:

In [ ]:
ip = get_ipython()

Let's grab the PNG formatter:

In [ ]:
png_f = ip.display_formatter.formatters['image/png']

We will use the for_type method to register our display function.

In [ ]:

As the docstring describes, we need to define a function the takes the object as a parameter and returns the raw PNG data.

In [ ]:
%matplotlib inline
import matplotlib.pyplot as plt
In [ ]:
class AnotherCircle(object):    
    def __repr__(self):
        return "<r Circle with r=1 at (0,0)>"
c = AnotherCircle()
In [ ]:
from IPython.core.pylabtools import print_figure

def png_circle(circle):
    """Render AnotherCircle to png data using matplotlib"""
    fig, ax = plt.subplots()
    patch = plt.Circle((0,0), radius=1.0, fc='r')
    data = print_figure(fig, 'png')
    # We MUST close the figure, otherwise IPython's display machinery
    # will pick it up and send it as output, resulting in a double display
    return data

Now we register the display function for the type:

In [ ]:
png_f.for_type(AnotherCircle, png_circle)

Now all Circle instances have PNG representations!

In [ ]:
c2 = AnotherCircle()
In [ ]:


Register for the AnotherCircle class a LaTeX formatter that uses the same value as the one in the Circle class above, but without adding new methods to AnotherCircle. That is, use the text/latex formatter similarly to how we used the image/png one.


In [ ]: