Fragment – Custom display_formatter Rendering of Python Types & Rendering Custom MimeTypes in JupyterLab and RetroLab

From a passing tweet, I notice a post on Fine tuning your Jupyter notebook’s displays which includes a reminder of how to roll your own custom __repr__ methods:

and this rather neat treat for creating customised rich displays around built-in types using the IPython display_formatter, which lets you define a custom formatter for a typed object:

Also in passing, I note from the JupyterLab vega5-extension that you can create a simple extension to define a custom mimi-type renderer, allowing you to do things like:

from IPython.display import display

display({
    "application/vnd.vegalite.v3+json": {
        "$schema": "https://vega.github.io/schema/vega-lite/v3.json",
        "description": "A simple bar chart with embedded data.",
        "data": {
            "values": [
                {"a": "A", "b": 28}, {"a": "B", "b": 55}, {"a": "C", "b": 43},
                {"a": "D", "b": 91}, {"a": "E", "b": 81}, {"a": "F", "b": 53},
                {"a": "G", "b": 19}, {"a": "H", "b": 87}, {"a": "I", "b": 52}
            ]
        },
        "mark": "bar",
        "encoding": {
            "x": {"field": "a", "type": "ordinal"},
            "y": {"field": "b", "type": "quantitative"}
        }
    }
}, raw=True

This suggests the possiblility of custom renderers for different JSON objects / Python dicts etc implement via an extension rather than eg a (simpler?) IPython _repr_ method.

Agood example of a custom mime-type renderer is the deshaw/jupyterlab-skip-traceback extension. This extension mimics the behaviour of the classic notebook skip-traceback nbextension which provided a simplified, collapsible view onto Python traceback error messages.

The JupyterLab extension works by defining a custom handler for the application/vnd.jupyter.error mime-type, parsing the result and rendering the improved output.

Author: Tony Hirst

I'm a Senior Lecturer at The Open University, with an interest in #opendata policy and practice, as well as general web tinkering...

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: