Displaying Jupyter Notebook Code Cell Content As Formatted Markdown/HTML Code Cell Output

Prompted by a Stack Overflow question on whether there was a way to display Python code comments as formatted markdown followed by the code output, I came up with some really simple IPython magic – innovationOUtside/fstring-magic – that will interpret code cell content as a simple formatted string or as an f-string and then display formatted markdown output.

image

My thinking is that this might be useful where a notebook or markdown file is being used to author a Jupyter Book generated HTML site and inline code outputs are required in text without having to use the currently recommended glue approach.

The glue package allows you to “add a key to variables in a notebook, then display those variables in markdown sections of a Jupyter Book by referencing the key. This is similar in style to the  nbextensions/python-markdown package which allows you to display the output value of code objects inline within markdown cells.

Using the f-string magic, we can author markdown that includes code object references similar to the glue or python-markdown approaches (or the use of inline code references in Rmd/bookdown, for example) and then render it via code cell outputs. In a Jupyter Book context, the code cell input can then be removed using a remove-input tag so that only the output formatted markdown is displayed.

In terms of workflow, whilst it would be handy to be able to do this natively in Jupyter Book, we can imagine a hacky workflow to help automate this, as described in this issue, specifically, create a simple pipeline process to transform magicked cells according to something like the following recipe:

if cell.type=='md' and 'f-string` in tags:
  #convert cell type to 'code'
  # tag cell as `remove-input`
  # prefix code cell body with appropriate magic

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

One thought on “Displaying Jupyter Notebook Code Cell Content As Formatted Markdown/HTML Code Cell Output”

Leave a Reply to Rowan Cockett Cancel 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.