Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive module import and reload

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?

like image 214
AlbertFerras Avatar asked Jun 08 '12 19:06

AlbertFerras


People also ask

How do I import and reload a module in Python?

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.

What is Importlib reload?

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.

What is the use of reload function?

Definition and Usage The reload() method reloads the current document. The reload() method does the same as the reload button in your browser.

How do you're import a package in Python?

1 Answer. You can re-import a module in python, by using the importlib and its function reload.


2 Answers

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:

  • Once if it is the main module
  • When it is imported the first time by any module (including itself)
  • Any time reload() is called on the module

As 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
like image 71
Andrew Clark Avatar answered Oct 20 '22 00:10

Andrew Clark


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.

like image 37
ecatmur Avatar answered Oct 19 '22 23:10

ecatmur