Skip to content Skip to sidebar Skip to footer

Does Python Cache Imported Files?

Consider the following: a.py foo = 1 b.py bar = 2 c.py import a kik = 3 d.py import a import c def main(): import b main() main() How many times is a.py loaded? How many

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":

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:

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)

Post a Comment for "Does Python Cache Imported Files?"