Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@padraicshafer padraicshafer commented Apr 14, 2018

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