I've read the following post:
Relative imports for the billionth time
It explains the difference between running a file as a top-level script and importing it as a module in remarkable clarity and detail.
I can't figure out, however, how to write the imports of a runnable script (if __name__ == '__main__'
et cetera) in a way which I'd also be able to import it from my tests, all the while keeping my runnable scripts stand-alone (i.e. not requiring package installation).
Say I have the following project hierarchy:
/reporoot
/mypkg
/mysubpkg
__init__.py
subpkgmodule.py
__init__.py
main1.py
main2.py
/tests
test_main1.py
test_main2.py
test_main1
needs to import main1
in some manner, and main1
needs to import subpkgmodule
in some manner.
If, for instance, main1
imports subpkgmodule
like so:
import mysubpkg.subpkgmodule
This will work fine when running the script as the top-level script because the top level script has its directory added to sys.path
. This import will break, however, when the module is imported rather than run (because its directory will not be added to sys.path
).
If main1
were to import subpkgmodule
like so:
import mypkg.mysubpkg.subpkgmodule
This will only work when the package is an installed package (including python setup.py develop
) and not running as a standalone script (i.e. chuck it on some filesystem and run python main1.py
).
I saw that the standard library's http.server
module has an import http.client
and therefore cannot be run as a standalone script as I mentioned.
What would a clean solution for the imports of my runnable scripts be?