Python:导入模块一次用于整个包 [英] Python : import module once for a whole package
问题描述
我正在编写一个基本结构化的应用程序:
I'm currently coding an app which is basically structured that way :
main.py
+ Package1
+ --- Class1.py
+ ---应用程序
+ Package2
+ --- Class1.py
+ ---应用程序
main.py
+ Package1
+--- Class1.py
+--- Apps
+ Package2
+--- Class1.py
+--- Apps
所以我有两个问题:
首先,在两个软件包中,所有应用程序都需要模块,例如:re。有没有办法可以一次为整个包导入一个模块,而不是在每个需要它的文件中导入它?
So I have two questions : First, inside both packages, there are modules needed by all Apps, eg : re. Is there a way I can import a module for the whole package at once, instead of importing it in every file that needs it ?
并且,正如你所看到的,Class1用于两个包中。有没有一种很好的方法在两个包之间共享它以避免代码重复?
And, as you can see, Class1 is used in both packages. Is there a good way to share it between both packages to avoid code duplication ?
推荐答案
我强烈建议不要这样做:将导入与使用该功能的模块分开,使得跟踪模块之间的依赖关系变得更加困难。
I would strongly recommend against doing this: by separating the imports from the module that uses the functionality, you make it more difficult to track dependencies between modules.
如果你真的想这样做,一个选项就是创建一个名为 common_imports
的新模块(例如)并让它执行您所追求的导入。
If you really want to do it though, one option would be to create a new module called common_imports
(for example) and have it do the imports you are after.
然后在您的其他模块中,添加以下内容:
Then in your other modules, add the following:
from common_imports import *
这应该为您提供该模块的所有公共名称(包括所有导入)。
This should give you all the public names from that module (including all the imports).
这篇关于Python:导入模块一次用于整个包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!