How to import a Jupyter notebook like a Python module

jupyter logo

Life will be easier if you can import a Jupyter notebook as a Python module when you are working on another notebook. However, the command import [notebook name] simply ends up with ModuleNotFoundError since JupyterLab notebooks have a different format and extension from Python scripts. Technically you could export notebooks as executable scripts whenever you edit your codes, but that should be too cumbersome and error-prone.

Solutions

The simplest method

The config file ~/.jupyter/jupyter_notebook_config.py allows you to have JupyterLab automatically export notebooks as Python scripts each time you make changes. By doing so, you can elimitate the step to manually export scripts. All you still have to do is to type import [notebook name], and I hope that it is close enough to our goal of directly importing notebooks. This method is valid as of Version 6.0.1, although the config file says that it is DEPRECATED, use post_save_hook. Will be removed in Notebook 5.0.

Steps

  1. Open the config file in a text editor.
    N.B. The file may sit in a different directory. If there is no such file, first you need to create one by typing a command like jupyter lab --generate-config.
  2. Uncomment the line #c.FileContentsManager.save_script = False and replace False with True.
  3. Save the file.

Other methods

Alternative methods are described here and here.