Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Import file in grandparent directory

Hierarchy:

scripts/
    web/
        script1.py
    tests/
        script2.py
common/
    utils.py

How would I import utils in script1 and script2, and still be able to run those scripts seperately (i.e., python script1.py). Where would I place the __init__.py files, and is that the correct way to go about this? Thank you!

like image 530
Jared Zoneraich Avatar asked Jul 18 '13 17:07

Jared Zoneraich


1 Answers

package/
    __init__.py
    scripts/
        web/
            __init__.py
            script1.py
        tests/
            __init__.py
            script2.py
    common/
        __init__.py
        utils.py

I've added a bunch of empty __init__.py files to your package. Now you have 2 choices, you can use an absolute import:

 from package.common import utils

or equivalently:

 import package.common.utils as utils

The downside here is that package must somehow be on PYTHONPATH. The other option is to use relative imports:

from ....common import utils

I would generally discourage this approach... It just gets too hard to tell where things are coming from (is that 4 periods or 6?).

like image 78
mgilson Avatar answered Sep 28 '22 07:09

mgilson