How to share python classes up a directory tree?

Viewed 45

I have an example file structure provided below.

/.git
/README.md
/project
    /Operation A
        generateinsights.py
        insights.py
    /Operation B
        generatetargets.py
        targets.py

generateinsights.py is run; it references insights.py to get the definition of an insight object. Next, generatetargets.py is run; it refrences targets.py to get the definition of a target object. The issue that I have, is generatetargets.py also needs to understand what an insight object is. How can I set up my imports so that insights.py and targets.py can be referenced by anything in the project directory? It seems like I should use _ init _.py for this, but I can't get it to work properly.

1 Answers

Firstly, you have to rename Operation A and Operation B so that they are composed of only letters, numbers and underscores, for example Operation_A - this is needed to be able to use these in an import statement without raising a SyntaxError.

Then, put an __init__.py file into the project, Operation_A and Operation_B folders. You can leave it empty, but you can also for example define additional attributes for your module.

Finally, you need to make Python find your modules - for this, either:

  • set your PYTHONPATH environment variable so that it includes the folder containing project or
  • put the package folder somewhere into Python's default import directories, for example in ´/usr/lib/python3/site-packages` (requires root permissions)

After that you can import both targets.py and insights.py from any place like this:

from project.Operation_A import insights
from project.Operation_B import targets
Related