I have truly tried my best to understand python imports, but it makes no sense to me. I know there's a million SO threads on this but none of them have helped me understand what's going on.
I have this simple structure:
project/
run.py
datasets/
__init__.py
config.py
datasetA.py
datasetA.py:
from config import classes
dosomething()
run.py:
from datasets import datasetA
And when I execute run.py, I get ModuleNotFoundError: No module named 'config'. Why? I have tried to include
import datasetA
import config
as well as
import .datasetA
import .config
in __init__.py
but it makes no difference. datasetA sees __package__ = datasets
, so it I think it should see config. run.py sees __package__ = None
. What am I missing?
CodePudding user response:
Relative vs absolute imports
Your issue relates to the differences between relative and absolute imports. When you try to import config from datasetA
, python looks in the root directory, in this case, project/
. To fix this, what you want to do is use a relative import in datasetA. See the difference between the following:
# project/datasets/datasetA.py
# Absolute import
from config import classes
# Python checks for an available import at the root of the project
# (e.g. project/ in this case) and fails as it does not exist
# Relative import
from .config import classes
# Python checks in the current directory
# (e.g. project/datasets/) and succeeds
You can read more about relative and absolute imports here