Loading...
Random Pearls Random Pearls New Menu
  • All Pearls
    • Random Pearls
  • Coding and Development - Reference …
    • Coding and Development - Reference …  (parent page)
    • Information Technology  (parent page of Coding and Development - Reference …)
  • New Menu
  • Authors
  •  
  • Contact Us
  • Sign up
  • Login
    Forgot Password?
  • Follow us on
Image Back to Top Back to top
Language Preference
This website has language specific content. Here you can set the language(s) of your preference.

This setting does not affect the current page. It is used only for filtering pages in menus, preview tiles and search results.

It can be changed any time by using the login menu (if you are logged in) or by clicking the Language button on the left bottom of the page.
Log in to save your preference permanently.



If you do not set this preference, you may see a header like This page has 'language_name' content in page preview tiles.
Search
  • Navigation
  • Similar
  • Author
  • More...
You are here:
All Content / Science and Technology / Information Technology / Coding and Development - Reference … / Show Markdown from within Code Cells in Jupyter and …
Table of Contents

Subscribe to Our Newsletter
Follow us by subscribing to our newsletter and navigate to the newly added content on this website directly from your inbox!
Login to subscribe to this page.
Categories  
Tags  
Author  
manisar
Author's Display Image

"Whenever you can, share. You never know who all will be able to see far away standing upon your shoulders!"

I write mainly on topics related to science and technology.

Sometimes, I create tools and animation.


Show Markdown from within Code Cells in Jupyter and VS Code's Python Interactive

July 25, 2021

Author - manisar


Recommended

An improved version of the code shown below is now available as a github package here.

What's in the Package

There are extra options such as using different display types like MATH, HTML etc.
And, displaying is not limited to strings - any object can be displayed (just like normal print would do)

Further, overriding print is possible so that your code looks and behaves the same in Python (and IPython, optionally) even if you decide to not use this package (e.g. in production).

So, essentially this package can be used for two quite different purposes:

The code given on this page will be useful in quickly understanding what we are trying to do here, and it is sufficient for the basic functionality.

Jupyter, and Interactive Python in VS Code, have markdown cells that can be used to show documentation in very interesting ways (e.g. we can have formatting, equations, images, videos etc.) that is not possible using normal commenting in any programming language. This is one of the greatest selling points of Jupyter.

However, it becomes slightly annoying to keep adding a markdown cell for every small piece of documentation you want to display.

For example, we may want to keep these little comments in the code block below in a single cell for the sake of avoiding clutter:

But if we, at the same time, wanted these suggestive comments to be displayed as markdown in the cell output, that will not happen, unless we put them in a separate markdown cell, a little too much of a hassle and clutter.

This workaround will let us display markdown from within code cells in IPython output, while ignoring it when run in normal Python (like usual comments) . The only constraint is that we have to use strings in place of comments.

Note: I used forbiddenfruit just for aesthetics, that is not a requirement.

import sys
from IPython.display import display, Markdown # can also use Latex, Math, HTML
from forbiddenfruit import curse
def display_markdown(self):
    if 'ipykernel' in sys.modules: display(Markdown(self))
curse(str, "md", display_markdown)

The code above can reside in a separate file, and which can be imported anywhere needed. Thus it becomes a mini-extension.
After this, the following code (e.g.), when run as a normal script, ignores the string-comments:

import numpy as np
r = 5
h = 20
volume = np.pi * r**2 * h
"""Thus we have calculated the **volume** of the *cylinder* by using the formula
$$ V = \pi r^2 h $$""".md()
"Now we'll calcualte the area as per $A = \pi r^2 + 2 \pi r h$.".md()
A = np.pi * r**2 + 2 * np.pi * r * h

but when run in IPython, displays this (alongside executing the python code):

Thus we have calculated the volume of the cylinder by using the formulaV=πr2h

Now we'll calcualte the area as per A=πr2+2πrh.

Considering that triple quoted strings are often used as multiline comments, this solution may be useful in many scenarios, and will not be a significant deviation from using normal comments.

On the plus side, there are two advantages:

  1. We get fine level control by having the option to decide exactly which comments (strings) are shown in the result cell.
  2. We can include dynamic values in the markdown, generated by code execution at run time by using f-strings.


An improved version of the code (with extra options) shown above is now available as a github package here.
This package can be used for two quite different purposes:

  1. Displaying markdown/HTML/Math/Latex strings from within code cells in IPython output, while ignoring it when run in normal Python (like usual comments).
    "V = {1 \over 3} \pi r^2 h".md()
  2. Displaying objects other than strings in IPython output using an extension-like function .md(). This will be handy for displaying or printing the values of multiple variables in IPython output.
    dot = Digraph()
    # ...
    dot.md()
Advertisement

A Reason to Donate

The page has no or minimal advertisement. If you want to contribute towards keeping this website running, think about donating a small amount. This helps in reducing the number of ads as well. You can decide the amount on the payment page. Thanks!

Advertisement
Close ad Ad

Return to Coding and Development - Reference and Tools

Tell us what you think (select text for formatting, or click )

Copyright © randompearls.com 2020

Privacy Policy