How to reference to the top-level module in Python inside a package?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)