[Tutor] Help with Package Importing
Colin Daly
colinbdaly at gmail.com
Wed Mar 2 00:15:26 EST 2022
Hello,
I have a question about how to properly import packages. I had created a
basic nested program in order to clearly show my error, but it doesn't look
like I can upload files for sharing. Please excuse me as this is my first
time posting here.
I have the following folder and file structure:
/MainDirectory
MainFile.py
| -- / Sub 1
| -- | -- SubProgram1_1.py
| -- | -- SubProgram1.py
| -- / Sub 2
| -- | -- ReadFile.py
I'm working out of MainDirectory. In MainFile.py I have:
MainFile.py
********************************************************
import Sub1.SubProgram1_1 as s1_1
def DoSomething():
z = s1_1.SubFunc1_2()
print(z)
DoSomething()
********************************************************
And inside ./Sub1/SubProgram1_1 I have
SubProgram1_1.py
********************************************************
import Sub1.SubProgram1 as s1
def SubFunc1_2():
xx = s1.SubFunc1()
yy = xx + 22
return yy
def main():
n = SubFunc1_2()
print(f"you are in subprogram1_1. value from SubFunc1_2 is {n}")
if __name__ == "__main__":
main()
********************************************************
MainFile.py runs fine like this, but SubProgram1_1.py does not run like
this. I need to change
import Sub1.SubProgram1 as s1
to
import SubProgram1 as s1
How should I have things such that I can run MainFile.py and
SubProgram1_1.py without messing with the import statements. Best I can
tell is to add the following to SubProgram1_1.py:
import os, sys
sys.path.insert(0, os.path.join(os.path.split(__file__)[0], ".."))
but that seems not very clean. Why should SubProgram1_1 need to import
Sub1.SubProgram1_1 when it's in the same folder?
Thank you!
More information about the Tutor
mailing list