[Tutor] Help with Package Importing

Mats Wichmann mats at wichmann.us
Wed Mar 2 09:06:02 EST 2022


I sent this but seem to have not sent it to the list, doing so now for
completeness:

> 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], ".."))

You don't want to do that.

> but that seems not very clean. Why should SubProgram1_1 need to import
> Sub1.SubProgram1_1 when it's in the same folder?

Because it's not in the same file, Python sees it as a separate module
(the directory makes it a package, but it's still has multiple modules).
Try it this way, which may be more readable to you:

from . import SubProgram1 as s1


BTW, Importing as a different name will probably lead to confusion at
some point. I know there are a few places where it's done a lot (import
numpy as np) but using the name of the module makes it easier to keep
track of what you're doing - and for other readers to be able to find
the context more quickly.  That's just a suggestion, it's not any kind
of rule - if you weren't allowed to "import as" the facility wouldn't exist!




More information about the Tutor mailing list