Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Modules & Packages using jupyter notebook in Google Cloud Platform

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?

like image 701
S.Nori Avatar asked Nov 07 '25 01:11

S.Nori


2 Answers

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
like image 164
Djib2011 Avatar answered Nov 08 '25 19:11

Djib2011


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

like image 29
Akhilesh Kr Avatar answered Nov 08 '25 20:11

Akhilesh Kr