[Tutor] Help with Package Importing
Peter Otten
__peter__ at web.de
Wed Mar 2 12:36:33 EST 2022
On 02/03/2022 06:15, Colin Daly wrote:
> 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.
When MainDirectory is your current working directory you should be able
to run the script inside the package with with the -m option:
$ python -m sub1.subprogram1_1
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.
Don't do that. The search path for modules should be part of the
environment rather than the program.
Why should SubProgram1_1 need to import
> Sub1.SubProgram1_1 when it's in the same folder?
In Python 2 you could write
import module
and depending on context it could mean
import module
or
from package import module
This caused enough problems to convince Python's developers to change it
https://www.python.org/dev/peps/pep-0328/
PS: It is generally a good idea to follow the style guide for Python
https://www.python.org/dev/peps/pep-0008/#package-and-module-names
which suggests lowercase for module names.
More information about the Tutor
mailing list