Say I have the following structure:
app/
__init__.py
mod.py
pkg/
__init__.py
submod.py
where the module submod has a relative import to mod, i.e.:
from .. import mod
I understand that if I want to execute submod as a script, I can do the following from app/
python -m pkg.submod
But I would like submod.py to be an executable module that I can call from anywhere in the system with
python /path/to/submod.py
I thought that PEP-366 fixed this, i.e. I thought that adding the following boilerplate code before I do any relative imports in submod:
if __name__ == "__main__" and __package__ is None:
__package__ = "app.pkg"
I could then go back to the regular python /path/to/submod.py. However, when I do that I get:
SystemError: Parent module 'app' not loaded, cannot perform relative import
Why?
Finally I understand that one solution is to manipulate sys.path in submod so that it can see mod1 and then do the regular import mod1 and avoid relative imports. But as this question shows, this is dangerous because any changes to sys.path in one module propagate to everything else, so in general it is not a good idea to tamper with sys.path.
Is there any way to have either:
- relative imports with support for regular python /path/to/submod.py calls
or
- the ability to execute my module with python /path/to/submod.py without having to tamper with
sys.pathorPYTHONPATH
?