0

I've tested modules with nested importing like below.

a.py

var1 = 2
import b
b.var2 = b.var2 + 1

b.py

var2 = 5
import a
a.var1 = a.var1 + 1

c.py

import b
import a
print(a.var1)
print(b.var2)

Regardless of importing order, the printed result of c.py was always 3, 6 which means each module is loaded only once.

Can I assume that each module is loaded only once even with nested imports?

Community
  • 1
  • 1
  • yes... it will only import the first time you call it. if you want to reload the imported function or value you will have to use importlib.reload(packagename) – Andy_101 Jan 10 '20 at 09:55
  • "Can I assume that each module is loaded only once even with nested imports?" yes, module imports are cached the first time they are imported. With circular imports it becomes a little complicated though; see existing answers regarding circular imports in Python – Iguananaut Jan 10 '20 at 09:56

0 Answers0