Technique-1
You can use the sys.path.insert() builtin-method to insert the path of main.py to position 1 of the system’s path variable. This ensures that it’s loaded with highest priority and avoids any naming conflicts if present.
Please see how I have solved this below:
My folder structure is as shown below:
import_test
├── functions
│ └── function.py
├── main.py
My main.py
def printFromMainA():
print("FromMainA")
def printFromMainB():
print("FromMainB")
My functions/function.py
import sys
sys.path.insert(1, "Absolute path to import_test/")
from main import *
def printFunction():
print("FromFunction")
printFromMainA()
printFromMainB()
printFunction()
And then finally when I run from import_test folder
python functions/function.py
I get the following output:
FromFunctionA
FromMainA
FromMainB
Technique-2
You can also use the sys.path.append() method which appends the path of the main.py to the system’s path variable. This will add the current path to the last position of the system’s paths list.
In this case all you need to do to the function.py is:
import sys
sys.path.append("Absolute path to import_test/")
from main import *
def printFunction():
print("FromFunction")
printFromMainA()
printFromMainB()
printFunction()
This should also give you the desired output.