Re:Guide to Python Import Statements
by loa-in-backup on Wednesday August 22, 2018 @06:52PM
(#17822975)
I guess "one way to do the thing" motto is at work here - run python as modules every time. I guess the script part should run the file it contains as a module for graceful fallback
Here is a quick example of how it works. Consider the following directory layout:
You would expect foo.py to start with these lines: As the article explains, these will not work if you just run foo.py as a script, because sys.path will start with "topdir/pkg/sub/": The simple fix here is to run the python file as a module, with "topdir/" as your working directory, so sys.path starts with "topdir/": After briefly mentioning python -m, the article has quite a lot of text on how to modify sys.path instead. That variable is interesting for understanding what's going on, but you should certainly not be modifying it. The exception is that if you have multiple different root directories containing packages (multiple directories like "topdir"), in which case you should indirectly modify sys.path by setting the environment variable PYTHONPATH. Code should never touch sys.path because the location of packages on your computer is a property of that computer's environment, not of the code.