I am fairly new to Python, and despite searching all over and following many guides on this site, I am still stuck with a strange issue.
Folder structure is as follows
ProjectFolder | --> tests | | | --> test_this.py | -->__init__.py --> app.py --> __init__.py
I am trying to simply import something from app.py into test_this.py
I have tried a few different things so far,
from app import func
– This obviously won’t work as it is not in the same dir
So I tried:
from ..app import func
and from . app import func
This gives the following error:
Exception has occurred: ImportError attempted relative import with no known parent package
Clearly I am missing or not understanding something here. I thought that I would be able to import it as I have that __init__.py file in the directory I am trying to import from.
Any chance someone could clarify this for me?
Advertisement
Answer
So the trick for me was to add the files I needed to the sys.path variable.
import sys, os from pathlib import Path path = Path(__file__) sys.path.insert(0, os.path.join(sys.path[0], path.parent.parent.absolute()))
This allowed me to reference a file in a parent or sibling folder without errors.