Reputation: 907
I have this directory structure
src
|
|\Lib
| |__init__.py
| |utils.py
| \Scripts
| |__init__.py
| |myscript.py
|__init__.py
and I need to import utils.py
in myscript.py
but from ..utils import function
is giving me
ImportError: attempted relative import with no known parent package
so my attempt is to add the parent package to the path by doing
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parents[1]))
inside the innermost __init__.py
(under the Scripts
folder) without any success.
What am I missing here?
Upvotes: 1
Views: 857
Reputation: 359
My suggestion to have a good understanding of how to deal with this kind of problem is to read this post: Relative imports for the billionth time
One solution to your problem could be the following:
src
|
|\Lib
| |__init__.py
| |utils.py
|
|\Scripts
| |myscript.py
myscript.py
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parents[1]))
and change from ..utils import function
to from Lib.utils import function
This is one way to solve it.
Upvotes: 2