Custom _repr_ printing in Jupyter Notebooks

A simple trick that I’ve been sort of aware from years, but never really used: creating your own simple _repr_ functions to output pretty reports of Python objects (I’m guessing, but haven’t yet checked, that this should work for a Jupyter Book HTML publishing workflow too).

The formulation is:

html_formatter = get_ipython().display_formatter.formatters['text/html']
html_formatter.for_type(CLASS, HTML_REPORT_FUNCTION);

Via: IPython — Formatters for third-party types.

Via a tweet, a simple example of adding repr magic to a class:

class HelloWorld():
  def __repr_html__(self):
    return "<div>Hello world!</div>"

a = HelloWorld()

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...

%d bloggers like this: