Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function written in different file from jupyter notebook

From a jupyter notebook, I'd like to call a function written in another .ipynb file. The partial answer is given in this thread Reusing code from different IPython notebooks by drevicko. As an example, I'm using plus_one function written in plus_one.ipynb:

def plus_one(x):
    print(x + 1)

Then, in my current notebook, I execute the cell:

%run plus_one.ipynb 3

which gives me no output. My expected output is 4. How to pass an argument (3) to this script? Thanks!

like image 589
koch Avatar asked Jun 07 '17 04:06

koch


People also ask

How do you call a function from another file in Colab?

If you expand the files tab in Colab you can navigate to the files in Google Drive. Then you can right click on the file or folder you want and do Copy path . You can then paste this into the cell where path_to_module is defined.


1 Answers

From the %run? documentation

This is similar to running at a system prompt python file args, but with the advantage of giving you IPython's tracebacks, and of loading all variables into your interactive namespace for further use

so all the cells from plus_one.ipynb are run and all it's variables are added to the namespace of the calling notebook. This does not call the plus_one method directly (unless it is called in the other notebook), but it defines it in the current namespace, kind of like an import in a regular python script.so from that moment on, you should be able to do plus_one(3) in the calling notebook, and expect 4 as return value

like image 102
Maarten Fabré Avatar answered Oct 27 '22 00:10

Maarten Fabré