当模块被多次导入时,python会优化它们吗?

2024-06-28 19:00:17 发布

您现在位置:Python中文网/ 问答频道 /正文

如果代码的某个子模块加载了一个大模块,那么从该命名空间引用该模块而不是再次导入它有什么好处吗?

例如: 我有一个模块MyLib,它广泛使用ReallyBigLib。如果我有导入MyLib的代码,我应该像这样挖掘模块吗

import MyLib
ReallyBigLib = MyLib.SomeModule.ReallyBigLib

或者只是

import MyLib
import ReallyBigLib

Tags: 模块代码import空间命名mylibsomemodulereallybiglib
3条回答

Python模块可以看作是单例的。。。无论导入多少次,它们都只初始化一次,因此最好执行以下操作:

import MyLib
import ReallyBigLib

进口声明相关文件:

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.

这没有实质性的区别。如果已经加载了大模块,那么第二个示例中的第二个导入除了将“ReallyBigLib”添加到当前命名空间之外什么也不做。

正如其他人指出的那样,Python维护了所有已导入模块的内部列表。第一次导入模块时,模块(脚本)将在其自己的命名空间中执行,直到结束,更新内部列表,并在import语句之后继续执行。

请尝试以下代码:

   # module/file a.py
   print "Hello from a.py!"
   import b

   # module/file b.py
   print "Hello from b.py!"
   import a

没有循环:只有缓存查找。

>>> import b
Hello from b.py!
Hello from a.py!
>>> import a
>>>

Python的一个优点是如何将所有内容转移到命名空间中执行脚本。

相关问题 更多 >