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

前端 未结 5 567
醉梦人生
醉梦人生 2021-02-01 17:51

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

5条回答
  •  广开言路
    2021-02-01 18:12

    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.

提交回复
热议问题