Reputation: 1957
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
.
Upvotes: 14
Views: 9576
Reputation: 1531
Given a structure like this:
dir_1
├── functions
│ └──__init__.py # contains some_function
└── dir_2
└── code.ipynb
We are simply inserting a relative path into sys.path
:
import sys
if ".." not in sys.path:
sys.path.insert(0, "..")
from functions import some_function
Upvotes: 3
Reputation: 121
The jupyter notebook starts with the current working directory in sys.path. see sys.path
... the directory containing the script that was used to invoke the Python interpreter.
If your utility functions are in the parent directory, you could do:
import os, sys
parent_dir = os.path.abspath('..')
# the parent_dir could already be there if the kernel was not restarted,
# and we run this cell again
if parent_dir not in sys.path:
sys.path.append(parent_dir)
from functions import some_function
Upvotes: 7
Reputation: 34036
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
Upvotes: 10
Reputation:
You can use sys.path.append('/path/to/application/app/folder')
and then try to import
Upvotes: 1