如何在包内引用Python中的顶级模块? [英] How to reference to the top-level module in Python inside a package?
问题描述
在下面的层次结构中,是否存在一种方便且通用的方式来使用下面所有.py文件中的通用术语来引用top_package?我想以一种一致的方式导入其他模块,以便即使在"top_package"更改名称时也不会中断.
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 to import other modules, so that even when the "top_package" changes name nothing breaks.
我不赞成使用"..level_one_a"之类的相对导入,因为相对路径将不同于下面的每个python文件.我正在寻找一种方法:
I am not in favour of using the relative import like "..level_one_a" as relative path will be different to each python file below. I am looking for a way that:
- 每个python文件对于包中的相同模块可以具有相同的import语句.
-
该包内任何.py文件中对"top_package"的解耦引用,因此无论"top_package"名称更改为什么,都不会中断.
- Each python file can have the same import statement for the same module in the package.
A decoupling reference to "top_package" in any .py file inside the package, so whatever name "top_package" changes to, nothing breaks.
top_package/
__init__.py
level_one_a/
__init__.py
my_lib.py
level_two/
__init__.py
hello_world.py
level_one_b/
__init__.py
my_lib.py
main.py
推荐答案
这应该可以完成:
top_package = __import__(__name__.split('.')[0])
此处的窍门是,对于每个模块,__name__
变量都包含指向模块的完整路径,该路径由点(例如top_package.level_one_a.my_lib
)分隔.因此,如果要获取顶级软件包名称,则只需获取路径的第一部分并使用__import__
导入.
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__
.
尽管用于访问程序包的变量名仍称为top_package
,但是您可以重命名程序包,如果仍然有效.
Despite the variable name used to access the package is still called top_package
, you can rename the package and if will still work.
这篇关于如何在包内引用Python中的顶级模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!