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

前端 未结 5 566
醉梦人生
醉梦人生 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:36

    You could use a combination of the __import__() function and the __path__ attribute of a package.

    For example, suppose you wish to import .level_one_a.level_two.hello_world from somewhere else in the package. You could do something like this:

    import os
    _temp = __import__(__path__[0].split(os.sep)[0] + ".level_one_a.level_two.hello_world")
    my_hello_world = _temp.level_one_a.level_two.hello_world
    

    This code is independent of the name of the top level package and can be used anywhere in the package. It's also pretty ugly.

提交回复
热议问题