Does Python Cache Imported Files?
Solution 1:
Both a
and b
are loaded once. When you import a module, its content is cached so when you load the same module again, you're not calling upon the original script for the import, done using a "finder":
- https://www.python.org/dev/peps/pep-0451/#finder
- https://docs.python.org/3/library/importlib.html#importlib.abc.MetaPathFinder
This works across modules so if you had a d.py
of which import b
, it will bind to the same cache as an import within c.py
.
Some interesting builtin modules can help understand what happens during an import:
https://docs.python.org/3/reference/import.html#importsystem
When a module is first imported, Python searches for the module and if found, it creates a module object 1, initializing it.
Notably here the first import, all imports after follow the
__import__
. Internal caches of finders are stored atsys.meta_path
.
You can leverage the import system to invalidate those caches for example:
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.
The imp
(and importlib
py3.4+) allows the recompilation of a module after import:
import imp
import a
imp.reload(a)
- https://docs.python.org/3/library/importlib.html#importlib.reload
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.
- https://docs.python.org/3/library/imp.html
Post a Comment for "Does Python Cache Imported Files?"