Can't import functions from another file [duplicate]

Interactive Python (ipython) is simply amazing, especially as you are piecing things together on the fly... and does it in such a way that it is easy to go back.

However, what seems to be interesting is the use-case of having multiple ipython notebooks (ipynb files). It apparently seems like a notebook is NOT supposed to have a relationship with other notebooks, which makes sense, except that I would love to import other ipynb files.

The only workaround I see is converting my *.ipynb files into *.py files, which then can be imported into my notebook. Having one file hold everything in a project is a bit weird, especially if I want to really push for code-reuse (isn't that a core tenet of python?).

Am I missing something? Is this not a supported use case of ipython notebooks? Is there another solution I can be using for this import of an ipynb file into another notebook? I'd love to continue to use ipynb, but it's really messing up my workflow right now :(


Solution 1:

It is really simple in newer Jupyter:

%run MyOtherNotebook.ipynb

See here for details.

Official docs: %run IPython magic command

Solution 2:

Install my helper library from the command prompt:

pip install import-ipynb

Import it from your notebook:

import import_ipynb

Now import your .ipynb notebook as if it was a .py file

import TheOtherNotebook

This python-ipynb module is just one file and it strictly adheres to the official howto on the jupyter site.

PS It also supports things like from A import foo, from A import * etc

PPS Works with subdirectories: import A.B

Solution 3:

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.