Importing an Ipynb File from Another Ipynb File

Importing an ipynb file from another ipynb file?

Run

!pip install ipynb

and then import the other notebook as

from ipynb.fs.full.<notebook_name> import *

or

from ipynb.fs.full.<notebook_name> import <function_name>

Make sure that all the notebooks are in the same directory.

Edit 1: You can see the official documentation here - https://ipynb.readthedocs.io/en/stable/

Also, if you would like to import only class & function definitions from a notebook (and not the top level statements), you can use ipynb.fs.defs instead of ipynb.fs.full. Full uppercase variable assignment will get evaluated as well.

Import functions from one ipynb file to another in vs code

For example, import funb() located in b.ipynb in a.ipynb.

  1. install module: pip install ipynb

  2. in a.ipynb:

     import ipynb
    from ipynb.fs.full.b import funb // ipynb.fs.full.<notebook_name>
    funb()

See result:

Sample Image

Jupyter Notebook: Import .ipynb file and access it's method in other .ipynb file giving error

**

Link to sample files on Drive

**

Ok. So, after some struggle and looking around on Internet, and finally found a solution that worked for my sample case.

Firstly, this is the stackoverflow question that was the most helpful to me. Mohideen and Tyhela's answer was the actual solution and not the one with most number of votes.

So, what I did was, I made a folder by the name module and placed all my .ipynb files there. Plus, I created an __init__.py file in that module by using touch __init__.py command such that the import can register it as a valid module. Those guys have given a detailed explanation for it which seems legit.

Then from my working directory I ran the following commands:

str = "Hello Me"
import test.abc as tabc
tabc.prt_n(str)

that gave me Hello Me in the output.

And for,

`import test.efg as tefg`

I got

importing Jupyter notebook from test/efg.ipynb
Hello Note

As my desired output.

I hope this will be of help to others who land up on similar problem.

If you have a better approach then I will appreciate if you can share that with me.

Thank you :)



Related Topics



Leave a reply



Submit