AlbertFerras
AlbertFerras

Reputation: 726

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?

Upvotes: 17

Views: 3065

Answers (2)

Andrew Clark
Andrew Clark

Reputation: 208555

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

Upvotes: 12

ecatmur
ecatmur

Reputation: 157414

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.

Upvotes: 8

Related Questions