Import Logic Python Project

Viewed 1555

After reading a lot of stackoverflow posts, the Python documentation and running some tests. I think I have a grasp of how the import logic works in Python. However, since I am working on a substantially large Python project for the first time I'd like to confirm my understanding is correct (and hope this post can help people in the future as I personally found it frustrating to fully understand what was going on)

General structure of project used for reference:

`
source/
  main.py
  test_main.py
  __init__.py
  Package1/
    moduleA.py
    moduleB.py
    __init__.py
  Package2/
    moduleC.py
    __init__.py
  Package3/
    moduleD.py
    __init__.py
  tests/
    test_module1.py
    test_module2.py
    __init__.py
`

Could someone confirm the following points are correct? (Below I assume I don't do any manually manipulation of sys.path in any of the files)

(1) If the only entry point to my project is main.py then it is recommended to use absolute import statements in all files? (ie - if moduleA.py needed to import moduleB.py I'd just have import moduleB but if moduleA.py also needed to import moduleD then I would put from package3 import moduleD) And doing it this way would cause no import errors correct? (because sys.path would be in the source directory and thus would know that is has subpackages Package1, Package2, Package3 and Test)

(2) Running moduleA.py directly:

  • If I ran this file directly (ie through command line) while my current directory was source/ then the above mentioned import statements would still work? (for the same reason I gave for (1))
  • If I ran it directly but the current working directory was Package1 then I would get import errors saying cannot find module/pacakge Package3 correct? (as Package1 wouldn't know it had a parent and thus couldn't reference Package3?)
0 Answers
Related