Ben Rei
Ben Rei

Reputation: 109

Python imports within a directory

I have a project that is structured thus:

.
  |-dir
  |  |-subdir
  |  |  |-subsubdir1
  |  |  |-subsubdir2
  |  |  |-subsubdir3
  |  |  |-sub_sub_main.py
  |  |  |-other_relevant.py
  |  |-sub_main1.py
  |-dir2
  |  |-sub_main2.py
  |-main.py

Sometimes I need to import functions from other_relevant.py in main.py, sub_main1.py, sub_main2.py, and sub_sub_main.py. However, importing the script from different levels of the directory tree causes for the necessary import structure to change.

The code in other_relevant.py and sub_sub_main.py relies on code in other python files in subsubdir1, subsubdir2, and subsubdir3. When I change where I import those two files the import statements in all the python files in those subdirectories have to be changed.

If I run main.py or sub_main2.py which imports other_relevant.py, it requires the import in other_relevant.py to use from dir.subdir1.subsubdir1.file import ....

If I am running the sub_main.py script then the import statement becomes from subdir.subsubdir1.file import ...

If I run sub_sub_main.py then the import statement becomes from subsubdir1.file import ....

Since the file structure makes sense in terms of how to organize the files I don't want to really change that. Is there a way to manage the import statements so that I don't have to change all the import statements in the files in subdir depending on where I run sub_sub_main.py and other_relevant.py?

Upvotes: 1

Views: 55

Answers (1)

Jean-Marc Volle
Jean-Marc Volle

Reputation: 3323

Set the env variable PYTHONPATH to your top folder path. Then all import statement will be made relative to this folder wherever you execute a python script. For instance from sub_main2.py you can do:

from dir.subdir.subdir3 import *

Setting up the env variable can be done by sourcing a sourceme.sh file located at the folder path. or directly in the .bashrc if only one project is used.

sample sourceme.sh:

export PYTHONPATH=`pwd -P`

Upvotes: 2

Related Questions