Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import functions of a jupyter notebook into another jupyter notebook in Google Colab

I would like to import functions of a Jupyter notebook (ending .ipynb) into another Jupyter notebook.

Both notebooks are located in Google Drive in the same file. The notebook in which the functions of the other notebook should be imported, is already open in Google Colab.

Therefore I'm looking for a code snipped like

from  xxx.ipynb  import functionX

I have already installed the PyDrive wrapper and authenticated and created the PyDrive client like follows:

!pip install -U -q PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
like image 517
Code Now Avatar asked Nov 24 '19 16:11

Code Now


1 Answers

You can use import_ipynb library.

First, mount your google drive to access your xxx.ipynb

from google.colab import drive
drive.mount("mnt")

Then change directory to the notebook directory.

%cd "mnt/My Drive/Colab Notebooks"

Now install the import_ipynb library, and import it

!pip install import-ipynb
import import_ipynb

Now you can import your xxx.ipynb

import xxx
xxx.do_something()

Here's an example Colab.

Update (oct 2020)

I have made the process easier, by just installing kora and call a function.

(Please also use auto-mount in a new notebook)

!pip install kora -q
from kora import drive
drive.link_nbs()

Now you can import from any notebooks you made before. For example, if you already have mylib.ipynb you can

import mylib
mylib.do_something()
like image 123
korakot Avatar answered Sep 22 '22 13:09

korakot