1

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?

Prophacy
  • 108
  • 8

1 Answers1

1

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
    
ti7
  • 16,375
  • 6
  • 40
  • 68
  • with that in tracker.py, it works from run.py but errors when running from tracker.py – Prophacy Feb 17 '21 at 23:27
  • 1
    Ah - if you wish to use it _both_ as a library in a directory and directly run it, consider a separate runner in the root directory or simply try/excepting `ImportError` amongst the imports and importing it with the relative import as you were in the except block – ti7 Feb 17 '21 at 23:29
  • sounds good, wasnt sure what the proper way to do something like this was, try/excepting the import seems like a good solution. ill accept it if you write up a new answer or add it to the one above – Prophacy Feb 17 '21 at 23:32