Skip to content

Instantly share code, notes, and snippets.

@vaultah
Last active September 5, 2023 21:28
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vaultah/d63cb4c86be2774377aa674b009f759a to your computer and use it in GitHub Desktop.
Save vaultah/d63cb4c86be2774377aa674b009f759a to your computer and use it in GitHub Desktop.
Generic boilerplate code for setting __package__ attribute for relative imports

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
@padraicshafer
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment