Python: How to import package root with relative imports

import, python

Solution

You can use `__package__` to know the package name, and `importlib.import_module`; This works for sub-packages.

import importlib
pkg = importlib.import_module(__package__)
print(pkg.a)

Problem

I have a large number of names defined in the top-level __init__.py of a python package. I would like to use a relative import to import this namespace because I do not necessarily know the package name at runtime (it might even be used as a sub-package of some other package). For example, take the following package: ``` my_package/ __init__.py a = 1 b = 2 ... my_module.py from . import ??? as my_package print(my_package.a) ``` How shall I fix the import statement in my_module such that the print statement works correctly? I would also rather avoid `from . import a, b, ...`; I just want the entire package namespace imported as one variable. I have tried `from . import __init__ as my_package`, but in this case `my_package` is imported as a method-wrapper, not a module. I have also tried `my_module = __import__(__package__)`, which works only in the case that my_package is not a sub-package. It seems like there should be a simple answer to this..

Original source