Supplement for my answer on Stack Overflow.
Please treat it as a proof of concept rather than an actual solution. It isn't well-suited for use in real-world code.
# level = 1 | |
if __name__ == '__main__' and __package__ is None: | |
import_parents() | |
from . import module | |
from .module.submodule import thing |
import sys, importlib | |
from pathlib import Path | |
def import_parents(level=1): | |
global __package__ | |
file = Path(__file__).resolve() | |
parent, top = file.parent, file.parents[level] | |
sys.path.append(str(top)) | |
try: | |
sys.path.remove(str(parent)) | |
except ValueError: # already removed | |
pass | |
__package__ = '.'.join(parent.parts[len(top.parts):]) | |
importlib.import_module(__package__) # won't be needed after that | |
if __name__ == '__main__' and __package__ is None: | |
import_parents(level=...) |
# level = 3 | |
if __name__ == '__main__' and __package__ is None: | |
import_parents(level=3) | |
from ... import module | |
from ...module.submodule import thing |
Hi, I really like your solution to this issue. I am wondering: What is the purpose of removing the script's directory from the system path?
sys.path.remove(str(parent))
I have recently posted this question to SO (with no answer yet):
https://stackoverflow.com/questions/49809290/package-modules-path-hinders-python-intra-package-imports