Skip to content
Advertisement

Python Relative Import in Jupyter Notebook

Let’s say I have the following structure:

 dir_1
 ├── functions.py
 └── dir_2
     └── code.ipynb

In, code.ipynb, I simply want to access a function inside functions.py and tried this:

from ..functions import some_function

I get the error:

attempted relative import with no known parent package

I have checked a bunch of similar posts but not yet figured this out… I am running jupyter notebook from a conda env and my python version is 3.7.6.

Advertisement

Answer

In your notebook do:

import os, sys
dir2 = os.path.abspath('')
dir1 = os.path.dirname(dir2)
if not dir1 in sys.path: sys.path.append(dir1)
from functions import some_function
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement