Description
For many years people have requested inline variable insertion in Jupyter Notebook markdown. This is a huge feature in the RMarkdown ecosystem, where you can do things like `r somevar`
and have that variable be inserted into the text at rendering time.
There have been some attempts at doing this in the classic notebook interface, most notably the python-markdown
extension, which uses moustache insertion so that {{ myvar }}
will render whatever myvar
is in the Python kernel:
I am wondering if there is a way that this pattern of moustache insertion could be generalized as a part of the Jupyter Notebook specification.
Benefit?
There are more and more libraries that deal with notebooks programmatically, so codifying a pattern like this could be useful even if it weren’t supported in the interactive user interfaces. I could imagine tools like papermill
and jupyter book
making heavy use of this. I believe that it would be a really useful feature that would bring the RMarkdown and Jupyter ecosystems more aligned with one another. If this could be done in a language-agnostic way, then it would also be really impactful for many other communities.
Potential implementations
I don’t think that this needs to be supported in the live user interfaces in order to be useful. An initial implementation could be done in one of the notebook execution libraries like nbclient
. For example, you could imagine a pattern using nbclient
like:
nbclient
is run on a notebook- It executes the notebook code cells
- It then inspects the markdown cells of the notebook, and searches for anything within curly brackets
two options from there:
- For all items that it finds, it calls
display
on a variable of the same name, and replaces the curly brackets with the resulting string.- For extra fanciness, since that’s in Python, you could also try to do this with
jinja
and support filters for extra formatting
- For extra fanciness, since that’s in Python, you could also try to do this with
- For all items that it finds, it calls
display
on a variable of the same name, and inserts the result in notebook-level metadata. Then downstream packages can do what they want with this metadata.
I don’t think this would be possible currently with nbclient
because it doesn’t give you the state of the live kernel after executing the notebook, but maybe it wouldn’t be too difficult to extend somehow?
Thoughts?
I am curious what others think about this - would it be useful? Does it seem sensible?
Related topics
and a really long issue that has been open for more than 5 years Allow references to Python variables in Markdown cells · Issue #2958 · ipython/ipython · GitHub