1

I'm working with google-colab. Can it be possible to call a function from one colab file in to another colab project, as we do in python like importing file.

ex. I have two colab files 1.ipynb and 2.ipynb.

Let's say 1.ipynb has ABC function. Now I want to utilize this already implemented ABC function into 2.ipynb

is there any way I can do it? or it's not possible?

1 Answers1

1

It's possible using the import-ipynb libary:

!pip install import-ipynb
import import_ipynb

This lets you import code from .ipynb files in the same way you would from .py files - simply by calling import filename or from filename import function, class, etc. (which is more advisable).

Assuming you have your notebooks neatly organized on your Google Drive, eg. in MyDrive/Colab_Notebooks/ you can then mount it:

from google.colab import drive
drive.mount('/content/drive')

and import the functions you want from the source notebook:

from drive.MyDrive.Colab_Notebooks.notebook1 import ABC, someOtherFunction
  • It seems cool. Thanks for such an amazing solution! Do I have to run the notebook which I want to import? – Darshan Tank Mar 09 '22 at 07:10
  • No, you don't have to run it. As long as the function you want to import is properly contained (e.g. doesn't use global variables) you should be good to go. You might need to import references which the function uses. – Jacek Jaskólski Mar 09 '22 at 07:24
  • In the colab every time we have to write "!pip install ......." So in that case should I also install all the dependencies which are required for that imported function!? – Darshan Tank Mar 09 '22 at 07:56
  • In general: yes, you need to install and import all dependencies that the source function uses. You can think about importing the funciton as if it was copy-pasted to your current notebook. Everything that is outside the `def` body that the function needs to run has to be present in the current notebook. Modules imported **within** the funciton body don't have to be imported. That's [not a recommended practice](https://stackoverflow.com/a/3095124/5566957) though. – Jacek Jaskólski Mar 09 '22 at 08:28
  • Ohk, understood, Thanks for making things clear – Darshan Tank Mar 09 '22 at 08:53