Skip to content

Instantly share code, notes, and snippets.

Last active September 5, 2023 21:28
  • Star 19 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
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:
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]
except ValueError: # already removed
__package__ = '.'.join([len(])
importlib.import_module(__package__) # won't be needed after that
if __name__ == '__main__' and __package__ is None:
# level = 3
if __name__ == '__main__' and __package__ is None:
from ... import module
from ...module.submodule import thing
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?

I have recently posted this question to SO (with no answer yet):

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