python - python 是否会在多次导入模块时优化模块?

标签 python python-import

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

例如: 我有一个模块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/

相关文章:

python - 如果需要的话安装一个库

python - 有没有办法用 Pillow 绘制渐变颜色的文本?

python - Tkinter Radiobutton "indicatoron"值不会产生任何影响

python - 如果更改值,python 字典中 dictionary.keys() 中键的顺序是否会更改?

python - Django:使用管理上下文扩展基于类的 View 的上下文

setup.py 后的 Python ImportError

python - ImportError:无法导入名称 WebAPI

Python 模块 : how to prevent importing modules called by the new module

python - Airflow dag 失败...但所有任务都成功

python-3.x - 在 Azure Functions 的脚本中导入 python-tabular 时出现错误