python 在多次导入模块时会优化模块吗?
如果代码的某个子模块加载了一个大模块,那么从该名称空间引用该模块而不是再次导入它有什么好处吗?
例如: 我有一个模块MyLib,它广泛使用ReallyBigLib。 如果我有导入 MyLib 的代码,我应该像这样挖出模块
import MyLib
ReallyBigLib = MyLib.SomeModule.ReallyBigLib
还是只是
import MyLib
import ReallyBigLib
If a large module is loaded by some submodule of your code, is there any benefit to referencing the module from that namespace instead of importing it again?
For example:
I have a module MyLib, which makes extensive use of ReallyBigLib. If I have code that imports MyLib, should I dig the module out like so
import MyLib
ReallyBigLib = MyLib.SomeModule.ReallyBigLib
or just
import MyLib
import ReallyBigLib
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Python 模块可以被视为单例......无论您导入多少次,它们都只会初始化一次,因此最好这样做:
有关导入语句的相关文档:
https://docs.python.org/2/reference/simple_stmts.html#the-import-statement
导入的模块缓存在 sys.modules 中:
Python modules could be considered as singletons... no matter how many times you import them they get initialized only once, so it's better to do:
Relevant documentation on the import statement:
https://docs.python.org/2/reference/simple_stmts.html#the-import-statement
The imported modules are cached in sys.modules:
正如其他人指出的那样,Python 维护了所有已导入模块的内部列表。 当您第一次导入模块时,该模块(脚本)将在其自己的命名空间中执行直到结束,内部列表将被更新,并在导入语句后继续执行。
试试这个代码:
没有循环:只有缓存查找。
Python 的优点之一是一切都转而在命名空间中执行脚本。
As others have pointed out, Python maintains an internal list of all modules that have been imported. When you import a module for the first time, the module (a script) is executed in its own namespace until the end, the internal list is updated, and execution of continues after the import statement.
Try this code:
There is no loop: there is only a cache lookup.
One of the beauties of Python is how everything devolves to executing a script in a namespace.
这没有什么实质性的区别。 如果大模块已加载,则第二个示例中的第二个导入除了将“ReallyBigLib”添加到当前命名空间之外什么也不做。
It makes no substantial difference. If the big module has already been loaded, the second import in your second example does nothing except adding 'ReallyBigLib' to the current namespace.
警告:Python 不保证模块不会被初始化两次。
我偶然发现了这样的问题。 参见讨论:
http://code.djangoproject.com/ticket/8193
WARNING: Python does not guarantee that module will not be initialized twice.
I've stubled upon such issue. See discussion:
http://code.djangoproject.com/ticket/8193
导入模块的内部注册表是 sys.modules 字典,它将模块名称映射到模块对象。 您可以在那里查看当前导入的所有模块。
您还可以通过使用 sys.modules 来实现一些有用的技巧(如果需要) - 例如将您自己的对象添加为可以由其他模块导入的伪模块。
The internal registry of imported modules is the
sys.modules
dictionary, which maps module names to module objects. You can look there to see all the modules that are currently imported.You can also pull some useful tricks (if you need to) by monkeying with
sys.modules
- for example adding your own objects as pseudo-modules which can be imported by other modules.性能上是一样的。 Python 中还没有 JIT 编译器。
It is the same performancewise. There is no JIT compiler in Python yet.