Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import module from parent directory without sys.path?

Tags:

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.

like image 481
Ejaz Avatar asked Sep 27 '19 13:09

Ejaz


People also ask

How do I import a module into a folder?

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.

What is SYS path append in Python?

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.


1 Answers

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
like image 200
meTchaikovsky Avatar answered Nov 15 '22 04:11

meTchaikovsky