I know that there are many similar questions but none of them addresses my specific problem: I have the following folder structure:
project/
main.py
/subDirec/
__init__.py
function1.py
function2.py
I want to import function2 into function1 and call function1 from main.
In function1 I call
import subDirec.function2
and in main:
import subDirec.function1
It works when I am calling main.py but not when I call function1.py. If I change it in function1 to:
import function2
it works in function1 but not in main anymore.
1 Answer 1
There is one trick you can use to make this work. I don't believe this is considered to be a pythonic way, it looks to me more like a workaround. It might create problems if not properly used.
The idea is to define project and its subdirectories as modules and add the path to the root folder project to the system path.
You will need to create an empty __init__.py in project and in each subdirectories which scripts and functions you want to load somewhere else.
Then the idea is to import like this:
from folder.subDirec.function1 import function_of_interest
In every file in project, you'll have to import using the syntax from folder.subDirect..
This import is possible only if you are located in the folder above project or if project has been added to PATH.
To add the path to project to environment path you can use:
if __name__ == '__main__':
import os
import sys
base_path = os.path.abspath(__file__).split('project')[0]
sys.path.append(base_path)
You can place this code at the top of each file before the imports to functions from project.
For instance:
project/
main.py
__init__.py
/subDirec/
__init__.py
plots.py
utils.py
In utils.py I want to use plots.p1(), thus in utils.py I will have:
if __name__ == '__main__':
import os
import sys
base_path = os.path.abspath(__file__).split('project')[0]
sys.path.append(base_path)
from project.subDirec.plots import p1
p1()