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

#Then:
a = HelloWorld()
a

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 )

Google photo

You are commenting using your Google 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.