0

I am new to Jupyter Notebooks and using the Anaconda install for Python 3.7. What is the best way to execute a function from another notebook? I found this 2-year-old answer here, but I don't know if there is a new/better way to do it with the Anaconda install (nbimporter has to be installed separately, it's not in Anaconda).

Here is the code/info in the notebooks:

Try #1 (fail)

# working directory files:
# mytest.ipynb # this contains the function I am trying to call
# Untitled.ipynb # this is the Notebook I am working in


# mytest.ipynb contents:
def testfcn(x):
    return print("input is", str(x))


# Untitled.ipynb contents:
from mytest import testfcn
testfcn(4)

ModuleNotFoundError: No module named 'mytest'

Try #2 (okay, not ideal)

# Untitled.ipynb contents:

%run mytest.ipynb
testfcn(4)

# returns this, extra stuff:
0.019999999999999997
<class 'float'>
input is 4
a11
  • 3,122
  • 4
  • 27
  • 66
  • Thanks @Wayne, the solution there is for running a function from .py files (and that solution works for me in Notebook). I'm trying to run a function from a .ipynb file. I tried to implement MEdwin 's comment, but it didn't work (error message "no module named mytest") – a11 Mar 11 '20 at 15:07
  • @Wayne it sort of works; but it returns extra output (which it doesn't do if I just call it from a .py) and yes, they are in the same working directory. – a11 Mar 11 '20 at 20:40
  • @wayne removing the return statements, thanks. I'll accept your answer if you copy/paste the comments into an answer – a11 Mar 11 '20 at 21:15

1 Answers1

1

The discussion here includes a comment by MEdwin on how to run another notebook from within yours and then you'll be able to call the functions of the other notebook in the noteboook where you ran the %run other_notebook.ipynb step.
Update: I just came across the subnotebook project that let's you run a notebook as you would call a Python function, pass parameters and get results back, including output contents. Might be useful in this context. END OF UPDATE.

Additionally, for Python functions, you don't want to do return print. You'd either remove the return and leave the print part or return the string that you could then print.

Wayne
  • 6,607
  • 8
  • 36
  • 93
  • Interestingly, I just tested your version #2 and my notebook/Python combination of current Jupyter and Python 3.7, doesn't mind the `return print`. However, as you've seen it is best to avoid. – Wayne Mar 11 '20 at 21:30
  • Also, you can add in using `%%capture` as the first line of the cell where the `%run` command is if you want to suppress any input from the other notebook, see my comments [here](https://stackoverflow.com/q/60662583/8508004). – Wayne Mar 13 '20 at 20:52