How to use another notebook function with Jupyter notebook is also introduced on the official website and Qiita, but I will show you how to make it a little more convenient.
It's basically the same as the official website. https://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Importing%20Notebooks.html
Qiita also has a good introductory article. https://qiita.com/tdual/items/32d3918b4c8dd1f703e7
However, the difficulty is that all the contents of the notebook are executed when importing. I want to use only the variables and functions defined in some cells instead of all cells in other notebooks! In fastai's nbdev, in such a case, mark "#export" at the beginning of the cell. But I don't want to exaggerate like nbdev.
So, modify the NotebookLoader class of the program on the official website so that only the cells marked "#export" at the beginning are imported.
import io, os, sys, types
from IPython import get_ipython
from nbformat import read
from IPython.core.interactiveshell import InteractiveShell
def find_notebook(fullname, path=None):
    name = fullname.rsplit('.', 1)[-1]
    if not path:
        path = ['']
    for d in path:
        nb_path = os.path.join(d, name + ".ipynb")
        if os.path.isfile(nb_path):
            return nb_path
        nb_path = nb_path.replace("_", " ")
        if os.path.isfile(nb_path):
            return nb_path
class NotebookLoader(object):
    def __init__(self, path=None):
        self.shell = InteractiveShell.instance()
        self.path = path
    def load_module(self, fullname):
        path = find_notebook(fullname, self.path)
        with io.open(path, 'r', encoding='utf-8') as f:
            nb = read(f, 4)
        mod = types.ModuleType(fullname)
        mod.__file__ = path
        mod.__loader__ = self
        mod.__dict__['get_ipython'] = get_ipython
        sys.modules[fullname] = mod
        save_user_ns = self.shell.user_ns
        self.shell.user_ns = mod.__dict__
        try:
          for cell in nb.cells:
            if cell.cell_type == 'code':
                code = self.shell.input_transformer_manager.transform_cell(cell.source)
                #At the beginning of the cell"#export"Execute only the cell described as
                if code.startswith("#export"):
                    exec(code, mod.__dict__)
        except Exception as ex:
            #In the cell"#export"I often forget to add, so let me know where the error occurred
            print(code)
            raise ex
        finally:
            self.shell.user_ns = save_user_ns
        return mod
class NotebookFinder(object):
    def __init__(self):
        self.loaders = {}
    def find_module(self, fullname, path=None):
        nb_path = find_notebook(fullname, path)
        if not nb_path:
            return
        key = path
        if path:
            # lists aren't hashable
            key = os.path.sep.join(path)
        if key not in self.loaders:
            self.loaders[key] = NotebookLoader(path)
        return self.loaders[key]
Save this with a file name such as nb_finder.py. When using
import sys
import nb_finder as nbf
sys.meta_path.append(nbf.NotebookFinder())
Then you can import other notebooks after that.
from mynotebook import *
In the import source notebook, add "#export" to the beginning of the cell that describes the variables and functions that you want to use in other notebooks. Don't forget to add #export to the cell that has the import statement needed to execute that cell as well. You may also want to specify #hide for an unwanted cell instead of #export to prevent that cell from being imported.
Recommended Posts