Fabian Scheuermann

__repr__ in Jupyter notebooks (draft)

Jupyter notebooks are a popular development environment, especially in the field of data science. The cell structure allows the user to mix code and documentation and execute the code step by step which can be extremely helpful. One has to read the data only once, and can then modify the analysis and visualization without repeating the previous steps.

Especially the visualization of the output is nice as it is shown in-line and remains visible as an intermediate result. Let us consider the following class. print(date) would show 2024-12-21 but if we write the object alone at the bottom of the cell, it will display year=2024, month=12, day=21.

class Date(object):
    def __init__(self,year,month,day):
        self.year = year
        self.month = month
        self.day = day
    def __str__(self):
        return str(f'{self.year}-{self.month}-{self.day}') 
    def __repr__(self):
        return f'year={self.year}, month={self.month}, day={self.day}'

date = Date(2024,12,21)
date

But there is a more advanced way that is used by many packages. This is how matplotlib displays the in-line plots, pandas prints its tables or shaply draws its shapes. It can be done by defining a _repr_html_ method for a class. For example this class we draw a rectangle in a certain color.

class HexColor(object):
    def __init__(self,hex):
        self.hex = hex
    def _repr_html_(self):
        svg = (
            '<svg width="162" height="100" xmlns="http://www.w3.org/2000/svg">' 
            f'<rect width="162" height="100" x="0" y="0" rx="16" ry="16"'
            f'fill="rgb(175,29,29)"/>'
            f'<text x="50%" y="50%" text-anchor="middle" fill="white" font-size="12">#af1d1d</text>'
            '</svg>' 
        )   
        html = f'
{svg}
' return html
#af1d1d

There are a number of special representation functions as described in the ipython documentation.

see also GitHub

back to overview