Reputation: 2794
I'd like to import a func from another ipython-notebook. Say,
common_func.ipynb
has def func_a()
When I create a new notebook, how can I access the func_a
which is from another notebook but in the same folder and same ipython instance?
Upvotes: 49
Views: 43918
Reputation: 9780
importnb is an option. It has some nice features like fuzzy matching to help you find your notebook and aiding in importing notebooks where the name would normally be an issue.
Imagine you have a notebook named common_func.ipynb
with the following function saved in it:
def func_a(x):
return x + 67
Then you are working in a new notebook, Untitled1.ipynb
.
To use func_a
in the current notebook Untitled1.ipynb
, in a cell run %pip install importnb
. That will install the importnb package
in the current environment backing the current notebook. (It won't do anything if you already have importnb
installed.) You are welcome to install the package your favorite way as well.
Put common_func.ipynb
or a copy of it in the current working directory where you are saving the current notebook Untitled1.ipynb
.
Then in the current notebook you can use importnb
to import the notebook common_func.ipynb
and use func_a
from it, like so:
from importnb import Notebook
with Notebook():
import common_func
common_func.func_a(2)
Upvotes: 2
Reputation: 740
There is now a dedicated function to achieve this called nbimporter
- installed via pip.
Usage:
import nbimporter
import notebookName as name
name.functionName()
And if you update notebookName.ipynb then reload by:
reload(name)
or this for Python 3 (reload not included by default):
from importlib import reload
reload(name)
Upvotes: 29
Reputation: 27456
Another option is ipynb
. A nice benefit over nbimporter
is that it can import just the definitions, while not executing the rest of the code. It's fairly new at this point (0.5).
pip install ipynb
And then:
import ipynb.fs.defs.my_other_notebook as other
Upvotes: 13
Reputation: 20811
In the IPython mailing list this was discussed very recently, see here. Finally (here), an example notebook was found, which shows a way to import code from other notebooks. This notebook can be found in the examples/notebooks
directory, and looks like this. You 'just' have to define the NotebookLoader and NotebookFinder classes as shown in the notebook. I've tried with IPython 1.1.0 and it works fine!
Upvotes: 13
Reputation: 281
When you start ipython use the --script flag: For example
ipython notebook --script
Then whenever you save your notebook "common_func.ipnb" it will also create a file entitled "common_func.py." You can import functions from that by using
from common_func import func_a
If you change the common_func notebook, you may need to use
reload()
Upvotes: 28