Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

importing functions from another jupyter notebook

Tags:

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?

like image 677
data_person Avatar asked May 29 '18 04:05

data_person


People also ask

How do I import a function from another Jupyter?

py file), or Jupyter Notebook. Remember the file that contains the function definitions and the file calling the functions must be in the same directory. To use the functions written in one file inside another file include the import line, from filename import function_name .

How do I call a Jupyter Notebook from another Jupyter Notebook?

Running a Jupyter Notebook from Another Jupyter NotebookFrom the left Sidebar, select and right-click on the Jupyter notebook that has to be run from another notebook. From the context menu, select Copy Path. Open the Jupyter notebook from which you want to run another notebook. Click Run.


1 Answers

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 
like image 173
Oppy Avatar answered Oct 14 '22 11:10

Oppy