Setting a default sys.path for a Notebook

Sreejith Menon picture Sreejith Menon · Jul 7, 2016 · Viewed 8.8k times · Source

I have all my .py files inside a folder script and all my IPython-notebooks under a folder named Notebook.

There are multiple cross dependencies for each notebook file on one or more files on script.

Having sys.path.append on top of every notebook seems cumbersome and I am hoping there is a way to add a default lookup path just like we add PYTHONPATH to .bash_profile.

Now I do the following:

import sys
sys.path.append("<path where DeriveFinalResultSet.py exists>)
import DeriveFinalResultSet as drs

I wish to have a setting where I can do the below:

import DeriveFinalResultSet as drs

Answer

Nick T picture Nick T · Jul 10, 2016

To avoid "hidden configurations" (i.e. things that aren't in source control/machine-specific) and to maintain a notebook/code separation like you describe, I do something like the below:

code/
    mymodule.py
    mypackage/
        __init__.py

notebooks/
    mynb.ipynb
    mynb2.ipynb
    paths.py   <--- below

In paths.py:

import sys
import pathlib
sys.path.insert(0, str(pathlib.Path(__file__).parents[1] / 'code'))
# sys.path[0] = str(pathlib.Path(__file__).parents[1] / 'code')

Then in mynb*.ipynb I can happily do:

import paths
import mymodule, mypackage

, etc.

The latter form effectively replaces the import path from the empty-string (current directory) to the "code" directory, which is perhaps a bit cleaner. This makes imports insensitive to using stuff like os.chdir().