pythondirectorypython-import

Importing from another directory located in parent directory in Python


Suppose we have a project structure like:

project/
    public_app/
        __init__.py
        dir/
            __init__.py
            config.py
            subdir/
                __init__.py
                functions.py
                utils.py
    my_app/
        main.py

In my_app/main.py, I would like to import some functions from public_app/dir/subdir/functions.py. A solution I found was to add the following:

# main.py
import sys
import os
path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))
sys.path.append(path)

from public_app.dir.subdir.functions import *

This seems to work, except now I would also like to import from public_app/dir/subdir/utils.py. However inside this file, it contains other relative imports:

# utils.py
from dir.config import *

If I then try doing

# main.py
from public_app.dir.subdir.utils import *

this gives me a ModuleNotFoundError: No module named 'dir'.

Any suggestion on how to do this? Note that I would ideally like to not mess with public_app at all. This is because it is a frequently updated directory pulled from a public repository, and would require constantly changing the imports. I would also like to also keep my_app in a separate directory for cleanliness/easier maintenance if possible.


Edit: Figured it out actually by sheer chance. See below for answer.


Solution

  • Run the main.py from the parent directory as a reference. That will resolve relative errors and import errors as the interpreter will get the idea of the relations between modules.

    Thus, Instead of doing:

    .../myapp$ python3 main.py
    

    Do:

    <parentfolderofproject>$ python3 -m project.myapp.main