A picture of me.

Tom Hodson

Maker, Baker Programmer Reformed Physicist RSE@ECMWF


Executable code snippets in docs and HTML object representations

Just a quick one. Lately I’ve started writing the documention for a new software project involving trees.

While debugging that in a Jupyter notebook I made a small HTML representation of the tree that mimis the output of tree but using the HTML details tag so you can open and close the subtrees.

This works using by giving the object a β€œrepr_html” method that returns a HTML string. If it’s present, Jupyter notebooks will use the output of that instead of repr to display a rich version of the object in a notebook.

class Title():
    def __init__(self, x):
        self.x = x
    def _repr_html_(self):
        return f"<h1>{self.x}</h1>"

I then set up executable code snippets in these docs so I could give code examples and not have to paste the output in myself. I’m using MyST-NB in sphinx to do this, it gives you a nicely syntax highlighted code block along with the output evaluated against the actual code. Since the NB in Myst-NB stands for notebook, it’s perhaps not so surprising that the HTML inline output also works!

The overall effect looks a bit like the below but see it in place for a better idea of how it looks with proper CSS.

from qubed import Qube

q = Qube.from_dict({
    "class=od" : {
        "expver=0001": {"param=1":{}, "param=2":{}},
        "expver=0002": {"param=1":{}, "param=2":{}},
    },
    "class=rd" : {
        "expver=0001": {"param=1":{}, "param=2":{}, "param=3":{}},
        "expver=0002": {"param=1":{}, "param=2":{}},
    },
})

# depth controls how much of the tree is open when rendered as html.
q.html(depth=100)
root
β”œβ”€β”€ class=od
β”‚ β”œβ”€β”€ expver=0001β”‚ β”‚ β”œβ”€β”€ param=1β”‚ β”‚ └── param=2
β”‚ └── expver=0002β”‚ β”œβ”€β”€ param=1β”‚ └── param=2
└── class=rd
β”œβ”€β”€ expver=0001 β”‚ β”œβ”€β”€ param=1 β”‚ β”œβ”€β”€ param=2 β”‚ └── param=3
└── expver=0002 β”œβ”€β”€ param=1 └── param=2

</div> </div>