First of all, my apologies if this question has already be asked elsewhere. I really searched for it, but didn't find anything.
The situation is the following:
In a folder mod
, I have the files __init__.py
and sub.py
.
They contain the following data:
__init__.py
:
print "mod"
sub.py
:
import __init__
print "sub"
Now let's do the following:
>>> import mod
mod
>>> import mod.sub
mod
sub
But when doing import mod.sub
, why is mod/__init__.py
executed again? It had been imported already.
The same strange feature exists if we just call:
>>> import mod.sub
mod
mod
sub
Can I change the behaviour by changing the import __init__
? This is the line that seems most likely wrong to me.
You can actually inspect what is going on by using the dictionary sys.modules
. Python decides to reload a module depending on the keys in that dictionary.
When you run import mod
, it creates one entry, mod
in sys.modules
.
When you run import mod.sub
, after the call to import __init__
, Python checks whether the key mod.__init__
is in sys.modules
, but there is no such key, so it is imported again.
The bottom line is that Python decides to re-import a module by keys present in sys.modules
, not because the actual module had already been imported.
you should replace
import __init__
by
import mod
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With