Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 304
CHRD Avatar asked Oct 16 '22 04:10

CHRD


1 Answers

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
like image 92
Mr_and_Mrs_D Avatar answered Oct 19 '22 01:10

Mr_and_Mrs_D