0

i have the following folder structure:

project:
  src:
    dirA:
      __init__.py
      dirA_file.py
    dirB:
      __init__.py
      utils:
         __init__.py
         utils_file.py
      serve

in utils_file.py i'm trying to import class A from dirA/dirA_file.py. i'm running app from the root(project dir), by running python src/dirB/serve.

Imports i tried:

from src.dirA.dirA_file import A -> error 'No module named "src"'
from ..dirA.dirA_file import A -> error 'attempted relative import beyond top-level package'
from ...dirA.dirA_file import A -> error 'attempted relative import beyond top-level package'

looking at similar questions on StackOverflow didn't really make my import work.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • I think you have two options - either change the directory structure such that `dirA` is inside the `dirB` directory, and then use `import dirA.dirA_file` or set the `PYTHONPATH` environment variable to include the full path to `src` and do `import dirA.dirA_file`. – mkimball Aug 14 '23 at 15:00
  • should i set it something like `os.environ["PYTHONPATH"] = path to src`. where do i need to set it? – Mahanchello Aug 14 '23 at 15:20
  • You should set it in your shell before running the script. Something like `export PYTHONPATH=/home/name/project/src` – mkimball Aug 14 '23 at 15:39
  • You can avoid some of the issues by running your script with the `-m` flag, rather than passing the full path of the file to `python`. If you do `python -m src.dirB.serve`, then first two versions of your imports should work. If `src` is not supposed to be your top-level package (but `dirA` and `dirB` are), you probably want to change directories into `src` before running the script with `python -m dirB.serve`. I'd also note that `serve` probably needs a `.py` extension if it's a Python script! – Blckknght Aug 14 '23 at 17:29
  • Check out [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – JonSG Aug 14 '23 at 18:19

0 Answers0