Python import issue for different subpackages

249 views Asked by At

I am trying to implement following hierarchy. My final goal is myscpt.sh should run from any folder

But I am getting import errors.

What is the best approach to implement such type of hierarchical architecture?

FooSoft
|
|-- foo/
    |
    |-- test.py   
    |
    |-- common/     
    |
    |-- utils/
    |
    |-- api/
    |
    |-- scripts/
          |-- myscript.py
|
|-- bin/myscpt.sh
|
|-- etc/foo.conf

bin/myscpt.sh

/usr/bin/python /path/FooSoft/foo/script/myscript.py /path/FooSoft/etc/foo.conf

foo/script/myscript.py

from ..common import *
from ..utils import *
from ..test import *
.
.
<Doing some stuff>

I am using .. import in most of modules to avoid absolute path.

2

There are 2 answers

0
Madison May On

Typically I resolve import errors by always using the package root as a reference.

First, I would include a setup.py file in the project root, and add in a minimal setuptools wrapper.

python setup.py develop

Then you don't have to worry about where you run the script from. Your imports become as follows:

from foo.common import *
from foo.utils import *
from foo.test import *
0
hynekcer On

Explicit relative imports with leading dots like from ..common import anything can be used only from a code that has been imported as a submodule of the package e.g. foo.scripts, but not from the the code imported as __main__ script, even if the script path contains .../foo/scripts/.... The main script must use absolute imports or it can be used as module by something like python -c "from foo.scripts import myscript; myscript.run()". (install the foo or use PYTHONPATH=/path/FooSoft). See Intra-package References in the docs or a similar question.