Python import more or less goes as
- look if there's a module with that name already, if so return it immediately
- the module has not been imported, so create the module object and put it in the registry immediately, then load the source and execute it
What happens if you execute file1
is that the execution start as a main program then
file1
code importsfile2
: since it was not present so the module object is created and execution offile2
beginsfile2
code importsfile1
: sincefile1
was not present as a module then a module object is created and execution offile1
begins (as a module!)file1
code (as a module) importsfile2
: the module is already present so the partially constructedfile2
module object is returned immediatelyfile1
as a module completes execution andfile2
resumes after importfile2
module completes execution andfile1
as main program resumes after import- the program completes
In other words there will be two instances of spam
: one inside the "main program" file1.py and one inside the module file1
.
Consider this simplified test case:
# p1.py
import p2, sys
p1d = {}
print id(p1d), id(sys.modules['p1'].p1d)
# p2.py
import p1
print "HERE"
running p1.py
you will get as output something like
18465168 18465168
HERE
17940640 18465168
the first two numbers are equal because the print
is executed from the p1
module while the second two numbers are different because print
is executed from p1
main program, that is a different instance.
PS: if you write intentionally code that does this (i.e. a main that indirectly import another instance of itself as a module) you should be put in jail :-)