python模块是否被导入两次? [英] Do python modules get imported twice?

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

问题描述

如果我有一个运行import math的文件,而另一个文件也具有import math AND并导入了第一个文件,那么是否在内存中两次加载了math模块?

If I have one file that runs import math, and a second file that also has import math AND which imports the first file, does that load the math module twice in memory?

推荐答案

执行import math时,它将导入并放入sys.modules中.接下来,您执行import math,将检查math是否在sys.modules中并从中获取.

When you do import math it is imported and put into sys.modules. Next you do import math it is checked if math is in sys.modules and fetched from there.

因此它只能导入一次.

http://effbot.org/zone/import-confusion.htm

Python导入模块时,首先检查模块注册表 (sys.modules)查看该模块是否已经导入.如果那是 情况下,Python照原样使用现有的模块对象.

When Python imports a module, it first checks the module registry (sys.modules) to see if the module is already imported. If that’s the case, Python uses the existing module object as is.

否则,Python会执行以下操作:

Otherwise, Python does something like this:

  1. 创建一个新的空模块对象(本质上是一个字典)
  2. 在sys.modules词典中插入该模块对象
  3. 加载模块代码对象(如有必要,请先编译模块)
  4. 在新模块的命名空间中执行模块代码对象.代码分配的所有变量都可以通过模块对象获得.

这 意味着导入一个已经导入的模块是相当便宜的; Python只需在字典中查找模块名称即可.

This means that it’s fairly cheap to import an already imported module; Python just has to look the module name up in a dictionary.

这篇关于python模块是否被导入两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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