I’m coding my first project in python, and I’m unsure as to how to handle importing. I’m working on computers at my university and cannot modify the PYTHONPATH variable. I am also working on this project from a variety of computers/OSs (so the path to the project is not always the same).
I have a number of different modules in different folders which all import eachother. Currently I get the path to one module from another by using file_path = os.path.abspath(__file__) and then backtracking through the directories and then appending the folder with the desired module in it. This is then added to the PYTHONPATH with sys.path.append(symantic_root).
This system works, but it ends up looking very messy and there is a lot of duplicated code at the beginning of each module, for example:
import os
import sys
# Get the path to the directory above the directory this file is in, for any system
file_path = os.path.abspath(__file__)
root_path = os.path.dirname(os.path.dirname(file_path))
# Get the paths to the directories the required modules are in
symantic_root = os.path.join(root_path, "semantic_analysis")
parser_root = os.path.join(root_path, "parser")
# Add the directories to the path variable
sys.path.append(symantic_root)
sys.path.append(parser_root)
import semantic_analyser
import jaml
Any advice on a better way to structure a project such as this will be much appreciated.
First, create a simple
main.pyscript which provides a single point of entry for your application. For example:Next, create a top-level package that groups together all your modules, and provide an access point for it in the same directory as
main.py. You should then be able to eliminate all the path manipulation code, and simply use fully specified import statements likefrom package.module import functionfrom any module within your application.