多次导入时python会优化模块吗? [英] Does python optimize modules when they are imported multiple times?

查看:35
本文介绍了多次导入时python会优化模块吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

例如:我有一个模块 MyLib,它广泛使用了 RealBigLib.如果我有导入 MyLib 的代码,我应该像这样挖出模块

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

或者只是

import MyLib
import ReallyBigLib

推荐答案

Python 模块可以被视为单例......无论你导入多少次它们都只会被初始化一次,所以最好这样做:

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:

import MyLib
import ReallyBigLib

import 语句的相关文档:

Relevant documentation on the import statement:

https://docs.python.org/2/参考/simple_stmts.html#the-import-statement

一旦知道模块的名称(除非另有说明,术语模块"将同时指包和模块),就可以开始搜索模块或包.首先检查的是 sys.modules,这是之前导入的所有模块的缓存.如果在那里找到该模块,则在导入的步骤 (2) 中使用它.

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 中:

The imported modules are cached in sys.modules:

这是一个将模块名称映射到已加载模块的字典.这可以被操纵以强制重新加载模块和其他技巧.请注意,从此字典中删除模块与在相应的模块对象上调用 reload() 不同.

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会优化模块吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆