如果您的代码的某个子模块加载了一个大模块,那么从该命名空间引用该模块而不是再次导入它有什么好处?
例如: 我有一个模块MyLib,它广泛使用了ReallyBigLib。如果我有导入 MyLib 的代码,我应该像这样挖掘模块吗
import MyLib
ReallyBigLib = MyLib.SomeModule.ReallyBigLib
或者只是
import MyLib
import ReallyBigLib
最佳答案
Python 模块可以被视为单例...无论您导入多少次,它们都只会被初始化一次,所以最好这样做:
import MyLib
import ReallyBigLib
import 声明的相关文档:
https://docs.python.org/2/reference/simple_stmts.html#the-import-statement
Once the name of the module is known (unless otherwise specified, the term “module” will refer to both packages and modules), searching for the module or package can begin. The first place checked is sys.modules, the cache of all modules that have been imported previously. If the module is found there then it is used in step (2) of import.
导入的模块缓存在sys.modules :
This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. Note that removing a module from this dictionary is not the same as calling reload() on the corresponding module object.
关于python - python 是否会在多次导入模块时优化模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/296036/