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 __in开发者_如何学Pythonit__
? 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
For completeness, I found another solution playing around with relative imports:
Replace
import __init__
by
from . import __init__
But I don't understand why this works.
edit: This actually doesn't work. the resulting__init__
is not the module mod
, but something else of the type method-wrapper
. Now I'm totally confused.
精彩评论