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?
The reload() - reloads a previously imported module or loaded module. This comes handy in a situation where you repeatedly run a test script during an interactive session, it always uses the first version of the modules we are developing, even we have mades changes to the code.
When reload() is executed: Python module's code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module's dictionary by reusing the loader which originally loaded the module.
Definition and Usage The reload() method reloads the current document. The reload() method does the same as the reload button in your browser.
1 Answer. You can re-import a module in python, by using the importlib and its function reload.
python hello.py
(A) runs the code once, when (A) calls import hello
the code is run again (B), when (A) and (B) call reload(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
...
existing_m = PyDict_GetItemString(modules_reloading, name);
if (existing_m != NULL) {
/* Due to a recursive reload, this module is already
being reloaded. */
Py_INCREF(existing_m);
return existing_m;
}
... load module code is below here
reload
keeps a list (actually a dict) of modules it is currently reloading to avoid reloading modules recursively.
See http://hg.python.org/cpython/file/e6b8202443b6/Lib/imp.py#l236
This isn't documented, as such, but I think you can probably rely on it remaining the case.
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