Can someone explain why executing the following code:
file “hello.py“:
import hello
print "hello"
hello = reload(hello)
executing as python hello.py prints the following?
hello
hello
hello
hello
Why 4 times? I know that when a module is already imported it’s not imported again, but reload forces to reload a module even if it’s already loaded. I’d have expected as a result unlimit ‘hello’ prints.
What has to happen so reload won’t reload a module?
python hello.py(A) runs the code once, when (A) callsimport hellothe code is run again (B), when (A) and (B) callreload(hello), the code is run twice more, for four times total.In general, for the lifetime of a program a module’s code will be executed at the following times:
reload()is called on the moduleAs for why the
reload()is not called recursively, there is an early exit point to the PyImport_ReloadModule() function (CPython, file is import.c) to prevent this:http://svn.python.org/view/python/trunk/Python/import.c?view=markup#l2646