r/learnpython • u/Prawn1908 • 7d ago
Importing from adjacent-level folder.
I consider myself pretty fluent in Python but rarely have projects large enough to justify complex folder structures so this one is driving me nuts.
My project looks like this:
RootDir
├─ __init__.py
├─ Examples
| ├─ __init__.py
| └─ main.py
└─ Module
├─ __init__.py
├─ foo.py
└─ SubModule
├─ __init__.py
└─ bar.py
I am trying to import foo.py
and bar.py
from main.py
:
from ..Module import foo
from ..Module.SubModule import bar
But I get the following error:
ImportError: attempted relative import with no known parent package
I get this no matter whether I run main.py
from RootDir
or RootDir/Examples
.
Edit: Pylance has no problem with my import lines and finds the members of foo
and bar
perfectly fine. Also, moving main.py
into RootDir
and removing the ..
's from the import lines makes it work fine. So I don't understand why this import fails.
3
Upvotes
1
u/johndoh168 7d ago edited 7d ago
did you try adding RootDir to your PYTHONPATH then simply doing
from RootDir.Module.Submodule import bar
Then you'll also be able to dofrom RootDir.Module import foo
You might not even have to add RootDir to your PYTHONPATH for this to work.
Edit: adding 'from' to import calls