python是否缓存导入的文件?

2024-09-27 19:21:28 发布

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

考虑以下几点:

a.py公司

foo = 1

b.py公司

bar = 2

c.py公司

import a
kik = 3

德比

import a
import c
def main():
    import b
main()
main()

  • a.py加载了多少次?你知道吗
  • b.py加载了多少次?你知道吗

一般来说,我想知道python如何处理导入的文件和函数/变量。你知道吗


Tags: 文件函数pyimportfoomaindefbar
1条回答
网友
1楼 · 发布于 2024-09-27 19:21:28

ab都加载一次。当您导入一个模块时,它的内容会被缓存,因此当您再次加载同一个模块时,您不会调用使用“finder”完成导入的原始脚本:

这可以跨模块工作,因此如果有一个d.py导入b,它将绑定到与c.py内导入相同的缓存。你知道吗


一些有趣的内置模块有助于理解导入过程中发生的情况:

您可以利用导入系统使这些缓存失效,例如:

https://docs.python.org/3/library/importlib.html#importlib.import_module

If you are dynamically importing a module that was created since the interpreter began execution (e.g., created a Python source file), you may need to call invalidate_caches() in order for the new module to be noticed by the import system.


imp(和importlibpy3.4+)允许在导入后重新编译模块:

import imp
import a
imp.reload(a)

相关问题 更多 >

    热门问题