This Jupyter Notebook Best Practice Will Make Your Manager Happy

Phillip Peng
2 min readSep 17, 2020

--

How to configure your notebook readable anywhere?

my own copyrighted photo: ‘Give Thanks’

There are many Jupyter Notebook best practices. But I would say this particular best practice will make your manager happy. Here’s why.

When we write or review the code in Jupyter Notebook, we have to start Python and work in a certain environment. Otherwise, your code in Jupyter Notebook is not that much readable. The Jupyter Notebook files are not rendered user-friendly in many settings, even in Azure Repos. Therefore, it is very inconvenient for your manager to read your code in the notebook format.

What Is This Best Practice?

I come across the talk of best practices of Jupyter Notebook for data science by Jonathan Whitmore (YouTube recording). Jonathan shared the best practice of automatically saving notebook files in two additional formats: python file (.py) and web page (.html), which will have exactly the same contents but different formats.

Your manager can then read the HTML webpage file without any dependency. He can even read your code files on his cell phone without any glitch. For developers, some additional advantages include deploying the python file directly and showing changes clearer in Git.

Configuration Steps

You only need to run through the following configuration steps once.

Step 1: Start anaconda and activate the environment.

Step 2: Generate the config file:

jupyter notebook --generate-config

Step 3: Find out the path of .jupyter folder:

jupyter --paths

Step 4: Edit file ‘.jupyter\jupyter_notebook_config.py’

You can open this file using vim or notepad++ at your choice. At the end of the code file, paste the following code (link to this gist):

import os
from subprocess import check_call

def post_save(model, os_path, contents_manager):
"""post-save hook for converting notebooks to .py and .html files."""
if model['type'] != 'notebook':
return # only do this for notebooks
d, fname = os.path.split(os_path)
check_call(['jupyter', 'nbconvert', '--to', 'script', fname], cwd=d)
check_call(['jupyter', 'nbconvert', '--to', 'html', fname], cwd=d)

c.FileContentsManager.post_save_hook = post_save

Save the changes to this configuration file. From now on, whenever you save your notebook files, automatically or manually, you will get two additional file formats: .py file and .html file.

Please clap this post if you like this tip.

--

--

No responses yet