'importing functions from another jupyter notebook

I am trying to import a function from another jupyter notebook

In n1.ipynb:

def test_func(x):
  return x + 1
-> run this

In n2.ipynb:

%%capture
%%run n1.ipynb
test_func(2)

Error:

NameError Traceback (most recent call last)<ipython-input-2-4255cde9aae3> in <module>()
----> 1 test_func(1)

NameError: name 'test_func' is not defined

Any easy ways to do this please?



Solution 1:[1]

The nbimporter module helps us here:

pip install nbimporter

For example, with two notebooks in this directory structure:

/src/configuration_nb.ipynb

analysis.ipynb

/src/configuration_nb.ipynb:

class Configuration_nb():
    def __init__(self):
        print('hello from configuration notebook')

analysis.ipynb:

import nbimporter
from src import configuration_nb

new = configuration_nb.Configuration_nb()

output:

Importing Jupyter notebook from ......\src\configuration_nb.ipynb
hello from configuration notebook

We can also import and use modules from python files.

/src/configuration.py

class Configuration():
    def __init__(self):
        print('hello from configuration.py')

analysis.ipynb:

import nbimporter
from src import configuration

new = configuration.Configuration()

output:

hello from configuration.py

Solution 2:[2]

Something I've done to import functions into a Jupyter notebook has been to write the functions in a separate Python .py file then use the magic command %run in the notebook. Here's an example of at least one way to do this:

Both notebook.ipynb and helper_functions.py are in the same directory.

helper_functions.py:

def hello_world():
    print('Hello world!')

notebook.ipynb:

%run -i helper_functions.py
hello_world()

notebook.ipynb output:

Hello world!

The %run command tells the notebook to run the specified file and the -i option runs that file in the IPython namespace, which is not really meaningful in this simple example but is useful if your functions interact with variables in the notebook. Check out the docs if I'm not providing enough detail for you.

For what it's worth, I also tried to run function definitions in an outside .ipynb file rather than a outside .py file and it worked for me. Might be worth exploring if you want to keep everything in notebooks.

Solution 3:[3]

Based on answer of Kurt:

%run -i configuration.ipynb

This runs another notebook and in the next cell you are able to access the variables defined by that notebook.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Kurt Eulau
Solution 3 Stefan