0

I am sure the question might seem pretty stupid, but searching around didn't yield me much result, so a redirection towards a response would be quite welcome.

So, I have a Python project with nested modules:

src
 |-package_1
  |-__init__.py
  |-module_1_1
  |-module_1_2
 |-package_2
  |-__init__.py
  |module_2_1
  |module_2_2
 |-main_module
 |-__init__.py

From the main_module I import the contents of package_2 and from modules inside package_2 I import contents of package_1 modules with the similar statements:

(main_module)

from package_2.module_2_1 import foo

(module_2_1)

from package_1.module_1_1 import bar

It all works well as a long as I run

Python main_module

but as soon as I try to run, for instance to use a function of the module_2_1 on it's own

Python module_2_1,

if fails with a message that it could not resolve the following import:

from package_1.module_1_1 import bar

From my understanding, Python is not aware of where it should go look for package_1, because it is not aware of where the project root is.

As a remedy, I am currently pre-pending the following line to all the inner modules to properly resolve the import:

if __name__ == "__main__":
    import os
    os.chdir("..")

But it just don't feel right.

What would be the correct way of solving this problem?

chiffa
  • 2,026
  • 3
  • 26
  • 41
  • Do you have `__init__.py` s? – C.B. Feb 12 '15 at 20:28
  • why do you need to run your program from `module_2_1`, is `main_module` your package's entry point? – dm03514 Feb 12 '15 at 20:32
  • Yes, __init__.py are inside all the packages and the src. Good point, but I checked it. – chiffa Feb 12 '15 at 20:35
  • Sorry I don't know the technical solution - I've never run into so complicated python project before. But I'm wondering if the directory structure is good. In my opinion, the whole meaning of divide up package1 and package 2 is because they are _independent_. If one should import another, then package1 should be embedded in package 2. – Meng Wang Feb 12 '15 at 20:35
  • Package 1 defines core functions for the 8-9 other packages in the group. Think of it as a config/common tools folder. Common enough to be shared throughout the project, yet not general enough to be installed as an independent module. – chiffa Feb 12 '15 at 20:39

1 Answers1

1

You need to invoke it properly in the first place. Change to src/ and run:

python -m package_2.module_2_1
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358