Reputation: 113
I'm using Jupyter Notebooks within Google CloudDatalab in Google Cloud Platform for my Python scripts. This creates .ipynb files.
I want to be able to create Modules and Packages using Jupyter Notebooks but it is not able to import the scripts.
For e.g.:
mymodule.ipynb has this:
def test_function():
print("Hello World")
Then in myscript.ipynb when I try to import the above:
from mymodule import test_function
It throws an error :
*ImportErrorTraceback (most recent call last) in ()
----> 1 from mymodule import test_function ImportError: No module named mymodule*
How do I create Modules & Packages using Jupyter Notebooks?
Upvotes: 4
Views: 2379
Reputation: 113
I've received a response on a different forum which answered my question. Here is the answer:
Put your module code into a .py file and make sure that's in the same directory as myscript.ipynb. To create the .py file from the code currently in a notebook, you can download it from within Jupyter as a .py file and tidy it up in your text editor of choice. Remember, the import statement is pure python syntax. It knows nothing about - and has no wish to know anything about - jupyter notebooks. It's looking for a .py file.
This has resolved the issue.
Thanks a lot.
Upvotes: 1
Reputation: 36
You cannot import Jupyter Notebook in the same way as Python files (packages).
Check this link: https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Importing%20Notebooks.html
Upvotes: 2
Reputation: 7432
Notebooks can't be used as modules. You need to create a python file (e.g. mymodule.py
).
If you want you can do this from within a jupyter notebook:
with open('mymodule.py', 'w') as f:
f.write('def test_function():')
f.write(' print("Hello World")')
from mymodule import test_function
test_function()
# Hello World
Upvotes: 2