In my python script L47_trial.py
, which has the following relative path with respect to my project:
my_scripts/04-trial/L47_trial.py
there is this import line
from ..starting_template import load_img
which should import the function load_img
from the script starting_template
, which has the following relative path with respect to my project:
my_scripts/starting_template.py
So, to be clear:
- my_scripts/
- 04-trial/
- L47_trial.py
- starting_template.py
However, when I run
python my_scripts/04-trial/L47_trial.py
from my project directory (the folder one level upper with respect to my_scripts
), I get this error:
from ..starting_template import load_img
ImportError: attempted relative import with no known parent package
My thinking is that as I run the file, python should do a relative import starting form the path of my_scripts/04-trial/L47_trial.py
, so,
if starting_template
were in the same directory of L47_trial.py
(that is 04-trial/
), I would do
from starting_template import load_img
but since starting_template
is one level upper, then I would expect
from ..starting_template import load_img
to work.
What is the problem with my import?
Is it forbidden in python to import a script "from directories one level above the current script's one"?
What I tried
I tried to change
from ..starting_template import load_img
to
from my_scripts.starting_template import load_img
but I get
from my_scripts.resources.starting_template import load_img
ModuleNotFoundError: No module named 'my_scripts'
Why cannot it find my_scripts
folder ?
2)
I tryed to move starting_template.py in the folder my_scripts/resources/
and change
from ..starting_template import load_img
into
from my_scripts.resources.starting_template import load_img # refactoring made by VScode
but I get again
from my_scripts.resources.starting_template import load_img
ModuleNotFoundError: No module named 'my_scripts'
Notes
Note: I have tested that by moving starting_template.py
into my_scripts/S04-trial
and changing
from ..starting_template import load_img
to
from starting_template import load_img
solves the issue, but I would like to keep the file there where it is.
Note: The directories my_scripts
and my_scripts/S04-trial
contain a void file __init__.py