5

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.

Ejaz
  • 1,504
  • 3
  • 25
  • 51

2 Answers2

3

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
meTchaikovsky
  • 7,478
  • 2
  • 15
  • 34
1

Some suggetions:

1.) Just accept it and modify sys.path ;-)

2.) make sure the environment variable PYTHONPATH points to the parent directory (be) and call your script only then

Example:

export PYTHONPATH=/absolute/path/to/be

3.) add an __init__.py file into the directory alembic and call your script from the be direcrory with. python -m alembic.env

4.) add the __init__.py like for 3.) and a small wrapper script to the be directory and call that script from be this script will then import alembic.env and call it's 'main' function.

Don't hesitate to contact me if my suggestions aren't clear enough.

I don't know your context but I often prefer 3.) and 4.) as nobody has to know about environment variables or sys path changes.

gelonida
  • 5,327
  • 2
  • 23
  • 41