In the below hierachy, is there a convenient and universal way to reference to the top_package using a generic term in all .py file below? I would like to have a consistent way
This should do the job:
top_package = __import__(__name__.split('.')[0])
The trick here is that for every module the __name__
variable contains the full path to the module separated by dots such as, for example, top_package.level_one_a.my_lib
. Hence, if you want to get the top package name, you just need to get the first component of the path and import it using __import__
.
Despite the variable name used to access the package is still called top_package
, you can rename the package and if will still work.