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.
Python module’s code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module’s dictionary by reusing the loader which originally loaded the module.
a
和b
都加载一次。当您导入一个模块时,它的内容会被缓存,因此当您再次加载同一个模块时,您不会调用使用“finder”完成导入的原始脚本:这可以跨模块工作,因此如果有一个
d.py
导入b
,它将绑定到与c.py
内导入相同的缓存。你知道吗一些有趣的内置模块有助于理解导入过程中发生的情况:
https://docs.python.org/3/reference/import.html#importsystem
值得注意的是这里的第一次导入,之后的所有导入都跟随
__import__
。查找程序的内部缓存存储在sys.meta_path
。https://docs.python.org/3/library/functions.html#import
您可以利用导入系统使这些缓存失效,例如:
https://docs.python.org/3/library/importlib.html#importlib.import_module
imp
(和importlib
py3.4+)允许在导入后重新编译模块:相关问题 更多 >
编程相关推荐