Relative imports in Jupyter notebooks

How do we import a module from a .py or a .ipynb file into a Jupyter notebook from a different directory?
I wrote this post after answering a question on stackoverflow:
https://stackoverflow.com/questions/49282122/import-modules-in-jupyter-notebook-path/

For example, if we have the directory structure:

analysis.ipynb
/src/configuration.py
/src/configuration_nb.ipynb

How do we access the file configuration.py or the notebook configuration_nb.ipynb in the notebook analysis.ipynb?

The nbimporter module helps us here:

[code language="shell" light="true"]
pip install nbimporter
[/code]

/src/configuration.py
[code]
class Configuration():
    def __init__(self):
        print('hello from configuration.py')
[/code]

analysis.ipynb:
[code]
import nbimporter
from src import configuration

new = configuration.Configuration()
[/code]

output:
[code language="shell" light="true"]
hello from configuration.py
[/code]

We can also import and use modules from other notebooks. If you have configuration_nb.ipynb in the /src module:

src/configuration_nb.ipynb:

[code]
class Configuration_nb():
    def __init__(self):
        print('hello from configuration notebook')
[/code]

analysis.ipynb:
[code]
import nbimporter
from src import configuration_nb

new = configuration_nb.Configuration_nb()
[/code]

output:
[code language="shell" light="true"]
Importing Jupyter notebook from ......\src\configuration_nb.ipynb
hello from configuration notebook
[/code]

2 thoughts on “Relative imports in Jupyter notebooks”

  1. I am able to successfully import other jupyter notebooks using nbimporter if they are within the same directory but am not able to do so for any other relative paths. Is there any way to get around this for potential jupyter notebooks in different paths?
    Thanks for the help

    1. Sorry for the late reply. One solution is to use sys. Append the current directory to your path. Then access a notebook in a relative directory. e.g.
      import sys
      sys.path.append(‘..’)

      from src.configuration import Config

Leave a Reply

Your e-mail address will not be published. Required fields are marked *