Python sub module import

Viewed 195

Lets say i have an app with a GUI.

the folder structure is:

\project
   run.py
   gui.py
   \tracker
      tracker.py
      trackerdialog.py
      trackerDB.py

run.py is the main app entry point. it imports a bunch of packages including "import tracker.tracker"

while I'm working on tracker.py, tracker.py reads: import trackerDialog, trackerDB

when I run tracker.py, everything works but when I import tracker from run.py. run.py errors with "no module named trackerDialog"

What is the proper way to import this submodule so i can test it isolated as tracker.py but also still have run.py be able to import it?

1 Answers

Base it from the working directory of the main program

from tracker import trackerdialog, trackerDB

You may also need to write a file named literally __init__.py (it does not need any content) to mark the directory ./tracker as containing Python libs (more here: What is __init__.py for? )


To use the file as both a library in a directory and also directly run it, consider either

  • creating a dedicated runner in the root directory
  • try/excepting ImportError
    try:
        from tracker import trackerdialog, trackerDB
    except:
        import trackerDialog, trackerDB
    
Related