5

I have project structure like this:

package1/__init__.py
package1/file1.py
package1/file2.py

package2/__init__.py
package2/file1.py
package2/file2.py

__init__.py
script1.py
script2.py

Unfortunately, I found that I can run code only from root directory, for example, from script1.py. If I run say from pakage2/file2.py, all links between files are lost, i.e. all imports of package1 from package2 becomes not found.

What is the correct directory structure in Python, which constraints package structure over all directories?

Dims
  • 47,675
  • 117
  • 331
  • 600

1 Answers1

0

You either need both package1 and package2 to be inside a package, in which case they can both import from each other:

root_package/
    __init__.py
    package1/
    package2/

Or add the packages to your PYTHONPATH, in which case any python script on your system can import from them:

export PYTHONPATH="$PYTHONPATH:/path/to/package1:/path/to/package2"

Update: you cannot import as part of a package if you are running the scripts directly. What you should do is define classes and functions in your packages as desired, then import them from another script:

root_package/
    __init__.py
    my_script.py
    package1/
    package2/

script.py:

from package1 import ...
from package2 import ...
Phydeaux
  • 2,795
  • 3
  • 17
  • 35
  • Sorry, of course I have `__init__.py` file in root directory too, I fixed the question – Dims Sep 14 '17 at 09:48
  • 1
    Anyway, it doesn't help – Dims Sep 14 '17 at 09:49
  • By "another script" you mean "script in root directory but not in any subdirectories"? – Dims Sep 14 '17 at 09:57
  • yes, or a script elsewhere that has `root_package` in it's `PYTHONPATH` – Phydeaux Sep 14 '17 at 09:58
  • I don't want to. Directories were invented to group files in logical groups. I want to keep this invention intact. I don't want to have long plain list of dozens of scripts of different purposes laying in one directory as was in PCM operating system – Dims Sep 14 '17 at 10:00
  • then you can add the root package to your `PYTHONPATH` and put the script anywhere. Or, dynamically add it to `PYTHONPATH` inside your script: https://stackoverflow.com/questions/3108285/in-python-script-how-do-i-set-pythonpath – Phydeaux Sep 14 '17 at 10:03
  • either way, a `.py` file can be part of a package or run as a standalone script, but not both. – Phydeaux Sep 14 '17 at 10:30