7

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 times is b.py loaded?

More generally, I would like to know how is Python handling imported files and functions/variables?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Gulzar
  • 23,452
  • 27
  • 113
  • 201
  • 4
    https://realpython.com/absolute-vs-relative-python-imports/ `The first thing Python will do is look up the name abc in sys.modules. This is a cache of all modules that have been previously imported.` – clubby789 Aug 04 '19 at 13:11
  • You can run `strace -e trace=file python3 d.py` to see which files python is accessing and in which order – hek2mgl Aug 04 '19 at 13:19
  • 2
    Possible duplicate of [Does python optimize modules when they are imported multiple times?](https://stackoverflow.com/questions/296036/does-python-optimize-modules-when-they-are-imported-multiple-times) – Mihai Chelaru Aug 04 '19 at 13:40

1 Answers1

9

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)
Glycerine
  • 7,157
  • 4
  • 39
  • 65