Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

How to import own modules in Jupyter

Solution one: do it inside jupyter

Here is what I do on my projects in jupyter notebook,

import sys
sys.path.append("../") # go to parent dir
from customFunctions import *

Then, to affect changes in customFunctions.py,

%load_ext autoreload
%autoreload 2

Solution two: prepend the path

Another solution might be to prepend;

e.g. sys.path.insert(0, ".."). If you were to prepend ".." to your path, then the parent directory would be searched first, which is arguably what you should want to happen. Also, this is consistent with how Jupyter notebook modifies the path -- it puts the path of the current notebook directory as the first item on the path.

Solution three: add a ipython config

Jupyter is base on ipython, a permanent solution could be changing the ipython config options.

Create a config file

$ ipython profile create
$ ipython locate
/Users/username/.ipython

Edit the config file

$ cd /Users/username/.ipython
$ vi profile_default/ipython_config.py

The following lines allow you to add your module path to sys.path

c.InteractiveShellApp.exec_lines = [
    'import sys; sys.path.append("/path/to/your/module")'
]

At the jupyter startup the previous line will be executed

Here you can find more details about ipython config https://www.lucypark.kr/blog/2013/02/10/when-python-imports-and-ipython-does-not/

Solution four:

Jupyter has its own PATH variable, JUPYTER_PATH.

Adding this line to the .bashrc file worked for me:

export JUPYTER_PATH=<directory_for_your_module>:$JUPYTER_PATH

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment