I am trying to call a module from a parent package.
My project structure -
be/
__init__.py
api/
__init__.py
models.py
alembic/
env.py
How to call models.py
inside env.py
I tried like below,
from api.models import Base
I get the error - ImportError: No module named 'api'
I thought of restructuring by putting the alembic
directory inside api
directory, still not able to import models
.
Using sys.path
looks hacky, if I should change the project structure, then please suggest.
We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory. As sys.
sys.path. Output: APPENDING PATH- append() is a built-in function of sys module that can be used with path variable to add a specific path for interpreter to search.
You can use relative import
inside env.py
, you only need from ..api.models import Base
If you don't want to use relative import, you can also try absolute import like
from be.api.models import Base
provided that you have exported the PYTHONPATH
to be
by
path_to_be=''
export PYTHONPATH=$path_to_be:$PATH
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With